UNPKG

257 kBJavaScriptView Raw
1import Taro from '@tarojs/api';
2import { setNavigationBarLoading, setTitle, setNavigationBarStyle, history, navigateBack, navigateTo, reLaunch, redirectTo, getCurrentPages, switchTab } from '@tarojs/router';
3export { getCurrentPages, history, navigateBack, navigateTo, reLaunch, redirectTo, switchTab } from '@tarojs/router';
4import { isFunction, toKebabCase, PLATFORM_TYPE } from '@tarojs/shared';
5import { hooks, Current as Current$1, getCurrentPage, getHomePage, eventCenter as eventCenter$1 } from '@tarojs/runtime';
6import { fromByteArray, toByteArray } from 'base64-js';
7import { __awaiter, __rest } from 'tslib';
8import platform from 'platform';
9import isNil from 'lodash-es/isNil';
10import { parse, stringify } from 'query-string';
11import throttle from 'lodash-es/throttle';
12import * as ics from 'ics';
13import { defineCustomElementTaroSwiperCore, defineCustomElementTaroSwiperItemCore } from '@tarojs/components/dist/components';
14import { isMobile } from 'is-mobile';
15import 'whatwg-fetch';
16import 'abortcontroller-polyfill/dist/abortcontroller-polyfill-only';
17import jsonpRetry from 'jsonp-retry';
18
19class MethodHandler {
20 constructor({ name, success, fail, complete }) {
21 this.isHandlerError = false;
22 this.methodName = name;
23 this.__success = success;
24 this.__fail = fail;
25 this.__complete = complete;
26 this.isHandlerError = isFunction(this.__complete) || isFunction(this.__fail);
27 }
28 success(res = {}, promise = {}) {
29 if (!res.errMsg) {
30 res.errMsg = `${this.methodName}:ok`;
31 }
32 isFunction(this.__success) && this.__success(res);
33 isFunction(this.__complete) && this.__complete(res);
34 const { resolve = Promise.resolve.bind(Promise) } = promise;
35 return resolve(res);
36 }
37 fail(res = {}, promise = {}) {
38 if (!res.errMsg) {
39 res.errMsg = `${this.methodName}:fail`;
40 }
41 else {
42 res.errMsg = `${this.methodName}:fail ${res.errMsg}`;
43 }
44 isFunction(this.__fail) && this.__fail(res);
45 isFunction(this.__complete) && this.__complete(res);
46 const { resolve = Promise.resolve.bind(Promise), reject = Promise.reject.bind(Promise) } = promise;
47 return this.isHandlerError
48 ? resolve(res)
49 : reject(res);
50 }
51}
52class CallbackManager {
53 constructor() {
54 this.callbacks = [];
55 /** 添加回调 */
56 this.add = (opt) => {
57 if (opt)
58 this.callbacks.push(opt);
59 };
60 /** 移除回调 */
61 this.remove = (opt) => {
62 if (opt) {
63 let pos = -1;
64 this.callbacks.forEach((callback, k) => {
65 if (callback === opt) {
66 pos = k;
67 }
68 });
69 if (pos > -1) {
70 this.callbacks.splice(pos, 1);
71 }
72 }
73 else {
74 // Note: 参数为空,则取消所有的事件监听
75 this.callbacks = [];
76 }
77 };
78 /** 获取回调函数数量 */
79 this.count = () => {
80 return this.callbacks.length;
81 };
82 /** 触发回调 */
83 this.trigger = (...args) => {
84 this.callbacks.forEach(opt => {
85 if (isFunction(opt)) {
86 opt(...args);
87 }
88 else {
89 const { callback, ctx } = opt;
90 isFunction(callback) && callback.call(ctx, ...args);
91 }
92 });
93 };
94 /** 清空所有回调 */
95 this.clear = () => {
96 this.callbacks = [];
97 };
98 }
99}
100
101/**
102 * ease-in-out的函数
103 * @param t 0-1的数字
104 */
105const easeInOut = (t) => (t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1);
106const getTimingFunc = (easeFunc, frameCnt) => {
107 return x => {
108 if (frameCnt <= 1) {
109 return easeFunc(1);
110 }
111 const t = x / (frameCnt - 1);
112 return easeFunc(t);
113 };
114};
115
116function createDownload(url = '', download = '') {
117 const link = document.createElement('a');
118 link.style.display = 'none';
119 link.href = url;
120 link.download = download;
121 // Note: 需要注意,该方案不能监听用户取消或禁止下载等操作,亦不能获取下载成功或失败状态
122 link.click();
123}
124
125const VALID_COLOR_REG = /^#[0-9a-fA-F]{6}$/;
126const isValidColor = (color) => {
127 return VALID_COLOR_REG.test(color);
128};
129
130/* eslint-disable prefer-promise-reject-errors */
131function shouldBeObject(target) {
132 if (target && typeof target === 'object')
133 return { flag: true };
134 return {
135 flag: false,
136 msg: getParameterError({
137 correct: 'Object',
138 wrong: target
139 })
140 };
141}
142function findDOM(inst) {
143 if (inst && hooks.isExist('getDOMNode')) {
144 return hooks.call('getDOMNode', inst);
145 }
146 const page = Current$1.page;
147 const path = page === null || page === void 0 ? void 0 : page.path;
148 const msg = '没有找到已经加载了的页面,请在页面加载完成后时候此 API。';
149 if (path == null) {
150 throw new Error(msg);
151 }
152 const el = document.getElementById(path);
153 if (el == null) {
154 throw new Error('在已加载页面中没有找到对应的容器元素。');
155 }
156 return el;
157}
158function getParameterError({ name = '', para, correct, wrong, level = 'error' }) {
159 const parameter = para ? `parameter.${para}` : 'parameter';
160 const errorType = upperCaseFirstLetter(wrong === null ? 'Null' : typeof wrong);
161 return `${name ? `${name}:fail ` : ''}parameter ${level}: ${parameter} should be ${correct} instead of ${errorType}`;
162}
163function upperCaseFirstLetter(string) {
164 if (typeof string !== 'string')
165 return string;
166 string = string.replace(/^./, match => match.toUpperCase());
167 return string;
168}
169function inlineStyle(style) {
170 let res = '';
171 for (const attr in style)
172 res += `${attr}: ${style[attr]};`;
173 if (res.indexOf('display: flex;') >= 0)
174 res += 'display: -webkit-box;display: -webkit-flex;';
175 res = res.replace(/transform:(.+?);/g, (s, $1) => `${s}-webkit-transform:${$1};`);
176 res = res.replace(/flex-direction:(.+?);/g, (s, $1) => `${s}-webkit-flex-direction:${$1};`);
177 return res;
178}
179function setTransform(el, val) {
180 el.style.webkitTransform = val;
181 el.style.transform = val;
182}
183function serializeParams(params) {
184 if (!params) {
185 return '';
186 }
187 return Object.keys(params)
188 .map(key => (`${encodeURIComponent(key)}=${typeof (params[key]) === 'object'
189 ? encodeURIComponent(JSON.stringify(params[key]))
190 : encodeURIComponent(params[key])}`))
191 .join('&');
192}
193function temporarilyNotSupport(name = '') {
194 return (option = {}, ...args) => {
195 const { success, fail, complete } = option;
196 const handle = new MethodHandler({ name, success, fail, complete });
197 const errMsg = '暂时不支持 API';
198 Taro.eventCenter.trigger('__taroNotSupport', {
199 name,
200 args: [option, ...args],
201 type: 'method',
202 category: 'temporarily',
203 });
204 if (process.env.NODE_ENV === 'production') {
205 console.warn(errMsg);
206 return handle.success({ errMsg });
207 }
208 else {
209 return handle.fail({ errMsg });
210 }
211 };
212}
213function weixinCorpSupport(name) {
214 return (option = {}, ...args) => {
215 const { success, fail, complete } = option;
216 const handle = new MethodHandler({ name, success, fail, complete });
217 const errMsg = 'h5 端当前仅在微信公众号 JS-SDK 环境下支持此 API';
218 Taro.eventCenter.trigger('__taroNotSupport', {
219 name,
220 args: [option, ...args],
221 type: 'method',
222 category: 'weixin_corp',
223 });
224 if (process.env.NODE_ENV === 'production') {
225 console.warn(errMsg);
226 return handle.success({ errMsg });
227 }
228 else {
229 return handle.fail({ errMsg });
230 }
231 };
232}
233function permanentlyNotSupport(name = '') {
234 return (option = {}, ...args) => {
235 const { success, fail, complete } = option;
236 const handle = new MethodHandler({ name, success, fail, complete });
237 const errMsg = '不支持 API';
238 Taro.eventCenter.trigger('__taroNotSupport', {
239 name,
240 args: [option, ...args],
241 type: 'method',
242 category: 'permanently',
243 });
244 if (process.env.NODE_ENV === 'production') {
245 console.warn(errMsg);
246 return handle.success({ errMsg });
247 }
248 else {
249 return handle.fail({ errMsg });
250 }
251 };
252}
253function processOpenApi({ name, defaultOptions, standardMethod, formatOptions = options => options, formatResult = res => res }) {
254 const notSupported = weixinCorpSupport(name);
255 return (options = {}, ...args) => {
256 var _a;
257 // @ts-ignore
258 const targetApi = (_a = window === null || window === void 0 ? void 0 : window.wx) === null || _a === void 0 ? void 0 : _a[name];
259 const opts = formatOptions(Object.assign({}, defaultOptions, options));
260 if (isFunction(targetApi)) {
261 return new Promise((resolve, reject) => {
262 ['fail', 'success', 'complete'].forEach(k => {
263 opts[k] = preRef => {
264 const res = formatResult(preRef);
265 options[k] && options[k](res);
266 if (k === 'success') {
267 resolve(res);
268 }
269 else if (k === 'fail') {
270 reject(res);
271 }
272 };
273 return targetApi(opts);
274 });
275 });
276 }
277 else if (isFunction(standardMethod)) {
278 return standardMethod(opts);
279 }
280 else {
281 return notSupported(options, ...args);
282 }
283 };
284}
285/**
286 * 获取当前页面路径
287 * @returns
288 */
289function getCurrentPath() {
290 var _a, _b, _c, _d, _e, _f;
291 const appConfig = window.__taroAppConfig || {};
292 const routePath = getCurrentPage((_a = appConfig.router) === null || _a === void 0 ? void 0 : _a.mode, (_b = appConfig.router) === null || _b === void 0 ? void 0 : _b.basename);
293 const homePath = 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);
294 /**
295 * createPageConfig 时根据 stack 的长度来设置 stamp 以保证页面 path 的唯一,此函数是在 createPageConfig 之前调用,预先设置 stamp=1
296 * url 上没有指定应用的启动页面时使用 homePath
297 */
298 return `${routePath === '/' ? homePath : routePath}?stamp=1`;
299}
300
301// 广告
302const createRewardedVideoAd = /* @__PURE__ */ temporarilyNotSupport('createRewardedVideoAd');
303const createInterstitialAd = /* @__PURE__ */ temporarilyNotSupport('createInterstitialAd');
304
305// 人脸识别
306const stopFaceDetect = /* @__PURE__ */ temporarilyNotSupport('stopFaceDetect');
307const initFaceDetect = /* @__PURE__ */ temporarilyNotSupport('initFaceDetect');
308const faceDetect = /* @__PURE__ */ temporarilyNotSupport('faceDetect');
309
310// AI推理
311const getInferenceEnvInfo = /* @__PURE__ */ temporarilyNotSupport('getInferenceEnvInfo');
312const createInferenceSession = /* @__PURE__ */ temporarilyNotSupport('createInferenceSession');
313
314// 判断支持版本
315const isVKSupport = /* @__PURE__ */ temporarilyNotSupport('isVKSupport');
316// 视觉算法
317const createVKSession = /* @__PURE__ */ temporarilyNotSupport('createVKSession');
318
319// AliPay
320const getOpenUserInfo = /* @__PURE__ */ temporarilyNotSupport('getOpenUserInfo');
321const tradePay = /* @__PURE__ */ temporarilyNotSupport('tradePay');
322
323// 加密
324const getUserCryptoManager = /* @__PURE__ */ temporarilyNotSupport('getUserCryptoManager');
325
326const setEnableDebug = /* @__PURE__ */ temporarilyNotSupport('setEnableDebug');
327const getRealtimeLogManager = /* @__PURE__ */ temporarilyNotSupport('getRealtimeLogManager');
328const getLogManager = /* @__PURE__ */ temporarilyNotSupport('getLogManager');
329
330// 性能
331const reportPerformance = /* @__PURE__ */ temporarilyNotSupport('reportPerformance');
332const getPerformance = /* @__PURE__ */ temporarilyNotSupport('getPerformance');
333const preloadWebview = /* @__PURE__ */ temporarilyNotSupport('preloadWebview');
334const preloadSkylineView = /* @__PURE__ */ temporarilyNotSupport('preloadSkylineView');
335const preloadAssets = /* @__PURE__ */ temporarilyNotSupport('preloadAssets');
336
337/** 跳转系统蓝牙设置页 */
338const openSystemBluetoothSetting = /* @__PURE__ */ temporarilyNotSupport('openSystemBluetoothSetting');
339/** 跳转系统微信授权管理页 */
340const openAppAuthorizeSetting = /* @__PURE__ */ temporarilyNotSupport('openAppAuthorizeSetting');
341/** 获取窗口信息 */
342const getWindowInfo = () => {
343 const info = {
344 /** 设备像素比 */
345 pixelRatio: window.devicePixelRatio,
346 /** 屏幕宽度,单位px */
347 screenWidth: window.screen.width,
348 /** 屏幕高度,单位px */
349 screenHeight: window.screen.height,
350 /** 可使用窗口宽度,单位px */
351 windowWidth: document.documentElement.clientWidth,
352 /** 可使用窗口高度,单位px */
353 windowHeight: document.documentElement.clientHeight,
354 /** 状态栏的高度,单位px */
355 statusBarHeight: NaN,
356 /** 在竖屏正方向下的安全区域 */
357 safeArea: {
358 bottom: 0,
359 height: 0,
360 left: 0,
361 right: 0,
362 top: 0,
363 width: 0
364 }
365 };
366 return info;
367};
368/** 获取设备设置 */
369const getSystemSetting = () => {
370 const isLandscape = window.screen.width >= window.screen.height;
371 const info = {
372 /** 蓝牙的系统开关 */
373 bluetoothEnabled: false,
374 /** 地理位置的系统开关 */
375 locationEnabled: false,
376 /** Wi-Fi 的系统开关 */
377 wifiEnabled: false,
378 /** 设备方向 */
379 deviceOrientation: isLandscape ? 'landscape' : 'portrait'
380 };
381 return info;
382};
383/** 获取设备设置 */
384const getDeviceInfo = () => {
385 var _a, _b;
386 const info = {
387 /** 应用二进制接口类型(仅 Android 支持) */
388 abi: '',
389 /** 设备二进制接口类型(仅 Android 支持) */
390 deviceAbi: '',
391 /** 设备性能等级(仅Android小游戏)。取值为:-2 或 0(该设备无法运行小游戏),-1(性能未知),>=1(设备性能值,该值越高,设备性能越好,目前最高不到50) */
392 benchmarkLevel: -1,
393 /** 设备品牌 */
394 brand: platform.manufacturer || 'unknown',
395 /** 设备型号 */
396 model: platform.product || 'unknown',
397 /** 操作系统及版本 */
398 system: ((_a = platform.os) === null || _a === void 0 ? void 0 : _a.toString()) || 'unknown',
399 /** 客户端平台 */
400 platform: ((_b = platform.os) === null || _b === void 0 ? void 0 : _b.family) || 'unknown',
401 /** 设备二进制接口类型(仅 Android 支持) */
402 CPUType: '',
403 };
404 return info;
405};
406/** 获取微信APP基础信息 */
407const getAppBaseInfo = () => {
408 var _a;
409 let isDarkMode = false;
410 if ((_a = window.matchMedia) === null || _a === void 0 ? void 0 : _a.call(window, '(prefers-color-scheme: dark)').matches) {
411 isDarkMode = true;
412 }
413 const info = {
414 /** 客户端基础库版本 */
415 SDKVersion: '',
416 /** 是否已打开调试。可通过右上角菜单或 [Taro.setEnableDebug](/docs/apis/base/debug/setEnableDebug) 打开调试。 */
417 enableDebug: process.env.NODE_ENV !== 'production',
418 /** 当前小程序运行的宿主环境 */
419 // host: { appId: '' },
420 /** 微信设置的语言 */
421 language: navigator.language,
422 /** 微信版本号 */
423 version: '',
424 /** 系统当前主题,取值为light或dark,全局配置"darkmode":true时才能获取,否则为 undefined (不支持小游戏) */
425 theme: isDarkMode ? 'dark' : 'light'
426 };
427 return info;
428};
429/** 获取微信APP授权设置 */
430const getAppAuthorizeSetting = () => {
431 const info = {
432 /** 允许微信使用相册的开关(仅 iOS 有效) */
433 albumAuthorized: 'not determined',
434 /** 允许微信使用蓝牙的开关(仅 iOS 有效) */
435 bluetoothAuthorized: 'not determined',
436 /** 允许微信使用摄像头的开关 */
437 cameraAuthorized: 'not determined',
438 /** 允许微信使用定位的开关 */
439 locationAuthorized: 'not determined',
440 /** 定位准确度。true 表示模糊定位,false 表示精确定位(仅 iOS 有效) */
441 locationReducedAccuracy: false,
442 /** 允许微信使用麦克风的开关 */
443 microphoneAuthorized: 'not determined',
444 /** 允许微信通知的开关 */
445 notificationAuthorized: 'not determined',
446 /** 允许微信通知带有提醒的开关(仅 iOS 有效) */
447 notificationAlertAuthorized: 'not determined',
448 /** 允许微信通知带有标记的开关(仅 iOS 有效) */
449 notificationBadgeAuthorized: 'not determined',
450 /** 允许微信通知带有声音的开关(仅 iOS 有效) */
451 notificationSoundAuthorized: 'not determined',
452 /** 允许微信使用日历的开关 */
453 phoneCalendarAuthorized: 'not determined'
454 };
455 return info;
456};
457/** 获取设备设置 */
458const getSystemInfoSync = () => {
459 const windowInfo = getWindowInfo();
460 const systemSetting = getSystemSetting();
461 const deviceInfo = getDeviceInfo();
462 const appBaseInfo = getAppBaseInfo();
463 const appAuthorizeSetting = getAppAuthorizeSetting();
464 delete deviceInfo.abi;
465 const info = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, windowInfo), systemSetting), deviceInfo), appBaseInfo), {
466 /** 用户字体大小(单位px)。以微信客户端「我-设置-通用-字体大小」中的设置为准 */
467 fontSizeSetting: NaN,
468 /** 允许微信使用相册的开关(仅 iOS 有效) */
469 albumAuthorized: appAuthorizeSetting.albumAuthorized === 'authorized',
470 /** 允许微信使用摄像头的开关 */
471 cameraAuthorized: appAuthorizeSetting.cameraAuthorized === 'authorized',
472 /** 允许微信使用定位的开关 */
473 locationAuthorized: appAuthorizeSetting.locationAuthorized === 'authorized',
474 /** 允许微信使用麦克风的开关 */
475 microphoneAuthorized: appAuthorizeSetting.microphoneAuthorized === 'authorized',
476 /** 允许微信通知的开关 */
477 notificationAuthorized: appAuthorizeSetting.notificationAuthorized === 'authorized',
478 /** 允许微信通知带有提醒的开关(仅 iOS 有效) */
479 notificationAlertAuthorized: appAuthorizeSetting.notificationAlertAuthorized === 'authorized',
480 /** 允许微信通知带有标记的开关(仅 iOS 有效) */
481 notificationBadgeAuthorized: appAuthorizeSetting.notificationBadgeAuthorized === 'authorized',
482 /** 允许微信通知带有声音的开关(仅 iOS 有效) */
483 notificationSoundAuthorized: appAuthorizeSetting.notificationSoundAuthorized === 'authorized',
484 /** 允许微信使用日历的开关 */
485 phoneCalendarAuthorized: appAuthorizeSetting.phoneCalendarAuthorized === 'authorized',
486 /** `true` 表示模糊定位,`false` 表示精确定位,仅 iOS 支持 */
487 locationReducedAccuracy: appAuthorizeSetting.locationReducedAccuracy,
488 /** 小程序当前运行环境 */
489 environment: '' });
490 return info;
491};
492/** 获取系统信息 */
493const getSystemInfoAsync = (options = {}) => __awaiter(void 0, void 0, void 0, function* () {
494 const { success, fail, complete } = options;
495 const handle = new MethodHandler({ name: 'getSystemInfoAsync', success, fail, complete });
496 try {
497 const info = yield getSystemInfoSync();
498 return handle.success(info);
499 }
500 catch (error) {
501 return handle.fail({
502 errMsg: error
503 });
504 }
505});
506/** 获取系统信息 */
507const getSystemInfo = (options = {}) => __awaiter(void 0, void 0, void 0, function* () {
508 const { success, fail, complete } = options;
509 const handle = new MethodHandler({ name: 'getSystemInfo', success, fail, complete });
510 try {
511 const info = yield getSystemInfoSync();
512 return handle.success(info);
513 }
514 catch (error) {
515 return handle.fail({
516 errMsg: error
517 });
518 }
519});
520const getSkylineInfoSync = /* @__PURE__ */ temporarilyNotSupport('getSkylineInfoSync');
521const getSkylineInfo = /* @__PURE__ */ temporarilyNotSupport('getSkylineInfo');
522const getRendererUserAgent = /* @__PURE__ */ temporarilyNotSupport('getRendererUserAgent');
523
524// 更新
525const updateWeChatApp = /* @__PURE__ */ temporarilyNotSupport('updateWeChatApp');
526const getUpdateManager = /* @__PURE__ */ temporarilyNotSupport('getUpdateManager');
527
528const unhandledRejectionCallbackManager = new CallbackManager();
529const themeChangeCallbackManager = new CallbackManager();
530const pageNotFoundCallbackManager = new CallbackManager();
531const errorCallbackManager = new CallbackManager();
532const appShowCallbackManager = new CallbackManager();
533const appHideCallbackManager = new CallbackManager();
534const unhandledRejectionListener = (res) => {
535 unhandledRejectionCallbackManager.trigger(res);
536};
537let themeMatchMedia = null;
538const themeChangeListener = (res) => {
539 themeChangeCallbackManager.trigger({
540 theme: res.matches ? 'dark' : 'light'
541 });
542};
543const pageNotFoundListener = (res) => {
544 pageNotFoundCallbackManager.trigger(res);
545};
546const errorListener = (res) => {
547 // @ts-ignore
548 errorCallbackManager.trigger(res.stack || res.message || res);
549};
550const getApp$1 = () => {
551 var _a;
552 const path = (_a = Taro.Current.page) === null || _a === void 0 ? void 0 : _a.path;
553 return {
554 /** 小程序切前台的路径 */
555 path: (path === null || path === void 0 ? void 0 : path.substring(0, path.indexOf('?'))) || '',
556 /** 小程序切前台的 query 参数 */
557 query: parse(location.search),
558 /** 来源信息。 */
559 referrerInfo: {},
560 /** 小程序切前台的[场景值](https://developers.weixin.qq.com/miniprogram/dev/framework/app-service/scene.html) */
561 scene: 0,
562 /** shareTicket,详见[获取更多转发信息](https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share.html) */
563 shareTicket: ''
564 };
565};
566const appShowListener = () => {
567 if (document.visibilityState !== 'hidden') {
568 appShowCallbackManager.trigger(getApp$1());
569 }
570};
571const appHideListener = () => {
572 if (document.visibilityState === 'hidden') {
573 appHideCallbackManager.trigger(getApp$1());
574 }
575};
576// 应用级事件
577const onUnhandledRejection = callback => {
578 unhandledRejectionCallbackManager.add(callback);
579 if (unhandledRejectionCallbackManager.count() === 1) {
580 window.addEventListener('unhandledrejection', unhandledRejectionListener);
581 }
582};
583const onThemeChange = callback => {
584 themeChangeCallbackManager.add(callback);
585 if (themeChangeCallbackManager.count() === 1) {
586 if (isNil(themeMatchMedia)) {
587 themeMatchMedia = window.matchMedia('(prefers-color-scheme: light)');
588 }
589 themeMatchMedia.addEventListener('change', themeChangeListener);
590 }
591};
592const onPageNotFound = callback => {
593 pageNotFoundCallbackManager.add(callback);
594 if (pageNotFoundCallbackManager.count() === 1) {
595 Taro.eventCenter.on('__taroRouterNotFound', pageNotFoundListener);
596 }
597};
598const onLazyLoadError = /* @__PURE__ */ temporarilyNotSupport('onLazyLoadError');
599const onError = callback => {
600 errorCallbackManager.add(callback);
601 if (errorCallbackManager.count() === 1) {
602 window.addEventListener('error', errorListener);
603 }
604};
605const onAudioInterruptionEnd = /* @__PURE__ */ temporarilyNotSupport('onAudioInterruptionEnd');
606const onAudioInterruptionBegin = /* @__PURE__ */ temporarilyNotSupport('onAudioInterruptionBegin');
607const onAppShow = callback => {
608 appShowCallbackManager.add(callback);
609 if (appShowCallbackManager.count() === 1) {
610 window.addEventListener('visibilitychange', appShowListener);
611 }
612};
613const onAppHide = callback => {
614 appHideCallbackManager.add(callback);
615 if (appHideCallbackManager.count() === 1) {
616 window.addEventListener('visibilitychange', appHideListener);
617 }
618};
619const offUnhandledRejection = callback => {
620 unhandledRejectionCallbackManager.remove(callback);
621 if (unhandledRejectionCallbackManager.count() === 0) {
622 window.removeEventListener('unhandledrejection', unhandledRejectionListener);
623 }
624};
625const offThemeChange = callback => {
626 themeChangeCallbackManager.remove(callback);
627 if (themeChangeCallbackManager.count() === 0) {
628 if (isNil(themeMatchMedia)) {
629 themeMatchMedia = window.matchMedia('(prefers-color-scheme: light)');
630 }
631 themeMatchMedia.removeEventListener('change', themeChangeListener);
632 themeMatchMedia = null;
633 }
634};
635const offPageNotFound = callback => {
636 pageNotFoundCallbackManager.remove(callback);
637 if (pageNotFoundCallbackManager.count() === 0) {
638 Taro.eventCenter.off('__taroRouterNotFound', pageNotFoundListener);
639 }
640};
641const offLazyLoadError = /* @__PURE__ */ temporarilyNotSupport('offLazyLoadError');
642const offError = callback => {
643 errorCallbackManager.remove(callback);
644 if (errorCallbackManager.count() === 0) {
645 window.removeEventListener('error', errorListener);
646 }
647};
648const offAudioInterruptionEnd = /* @__PURE__ */ temporarilyNotSupport('offAudioInterruptionEnd');
649const offAudioInterruptionBegin = /* @__PURE__ */ temporarilyNotSupport('offAudioInterruptionBegin');
650const offAppShow = callback => {
651 appShowCallbackManager.remove(callback);
652 if (appShowCallbackManager.count() === 0) {
653 window.removeEventListener('visibilitychange', appShowListener);
654 }
655};
656const offAppHide = callback => {
657 appHideCallbackManager.remove(callback);
658 if (appHideCallbackManager.count() === 0) {
659 window.removeEventListener('visibilitychange', appHideListener);
660 }
661};
662
663const launchOptions = {
664 path: '',
665 query: {},
666 scene: 0,
667 shareTicket: '',
668 referrerInfo: {}
669};
670function initLaunchOptions(options = {}) {
671 Object.assign(launchOptions, options);
672}
673Taro.eventCenter.once('__taroRouterLaunch', initLaunchOptions);
674// 生命周期
675const getLaunchOptionsSync = () => launchOptions;
676const getEnterOptionsSync = () => launchOptions;
677
678const env = {
679 FRAMEWORK: process.env.FRAMEWORK,
680 TARO_ENV: process.env.TARO_ENV,
681 TARO_PLATFORM: process.env.TARO_PLATFORM,
682 TARO_VERSION: process.env.TARO_VERSION,
683};
684// Note: 该方法由 taro-plugin-platform-h5 实现
685
686function arrayBufferToBase64(arrayBuffer) {
687 return fromByteArray(arrayBuffer);
688}
689function base64ToArrayBuffer(base64) {
690 return toByteArray(base64).buffer;
691}
692
693const TextBaseLineMap = {
694 top: 'top',
695 bottom: 'bottom',
696 middle: 'middle',
697 normal: 'alphabetic',
698 hanging: 'hanging',
699 alphabetic: 'alphabetic',
700 ideographic: 'ideographic'
701};
702class CanvasContext {
703 constructor(canvas, ctx) {
704 this.actions = [];
705 this.canvas = canvas;
706 this.ctx = ctx;
707 }
708 set ctx(e) {
709 this.__raw__ = e;
710 }
711 get ctx() {
712 return this.__raw__ || {};
713 }
714 emptyActions() {
715 this.actions.length = 0;
716 }
717 enqueueActions(func, ...args) {
718 this.actions.push({
719 func,
720 args
721 });
722 }
723 set fillStyle(e) { this.enqueueActions(() => { this.ctx.fillStyle = e; }); }
724 get fillStyle() { return this.ctx.fillStyle; }
725 set font(e) { this.ctx.font = e; }
726 get font() { return this.ctx.font; }
727 set globalAlpha(e) { this.enqueueActions(() => { this.ctx.globalAlpha = e; }); }
728 get globalAlpha() { return this.ctx.globalAlpha; }
729 set globalCompositeOperation(e) { this.enqueueActions(() => { this.ctx.globalCompositeOperation = e; }); }
730 get globalCompositeOperation() { return this.ctx.globalCompositeOperation; }
731 set lineCap(e) { this.enqueueActions(() => { this.ctx.lineCap = e; }); }
732 get lineCap() { return this.ctx.lineCap; }
733 set lineDashOffset(e) { this.enqueueActions(() => { this.ctx.lineDashOffset = e; }); }
734 get lineDashOffset() { return this.ctx.lineDashOffset; }
735 set lineJoin(e) { this.enqueueActions(() => { this.ctx.lineJoin = e; }); }
736 get lineJoin() { return this.ctx.lineJoin; }
737 set lineWidth(e) { this.enqueueActions(() => { this.ctx.lineWidth = e; }); }
738 get lineWidth() { return this.ctx.lineWidth; }
739 set miterLimit(e) { this.enqueueActions(() => { this.ctx.miterLimit = e; }); }
740 get miterLimit() { return this.ctx.miterLimit; }
741 set shadowBlur(e) { this.enqueueActions(() => { this.ctx.shadowBlur = e; }); }
742 get shadowBlur() { return this.ctx.shadowBlur; }
743 set shadowColor(e) { this.enqueueActions(() => { this.ctx.shadowColor = e; }); }
744 get shadowColor() { return this.ctx.shadowColor; }
745 set shadowOffsetX(e) { this.enqueueActions(() => { this.ctx.shadowOffsetX = e; }); }
746 get shadowOffsetX() { return this.ctx.shadowOffsetX; }
747 set shadowOffsetY(e) { this.enqueueActions(() => { this.ctx.shadowOffsetY = e; }); }
748 get shadowOffsetY() { return this.ctx.shadowOffsetY; }
749 set strokeStyle(e) { this.enqueueActions(() => { this.ctx.strokeStyle = e; }); }
750 get strokeStyle() { return this.ctx.strokeStyle; }
751 /** 小程序文档中不包括 ↓↓↓ */
752 set textAlign(e) { this.ctx.textAlign = e; }
753 get textAlign() { return this.ctx.textAlign; }
754 set textBaseline(e) { this.ctx.textBaseline = e; }
755 get textBaseline() { return this.ctx.textBaseline; }
756 set direction(e) { this.ctx.direction = e; }
757 get direction() { return this.ctx.direction; }
758 set imageSmoothingEnabled(e) { this.enqueueActions(() => { this.ctx.imageSmoothingEnabled = e; }); }
759 get imageSmoothingEnabled() { return this.ctx.imageSmoothingEnabled; }
760 set imageSmoothingQuality(e) { this.enqueueActions(() => { this.ctx.imageSmoothingQuality = e; }); }
761 get imageSmoothingQuality() { return this.ctx.imageSmoothingQuality; }
762 set filter(e) { this.enqueueActions(() => { this.ctx.filter = e; }); }
763 get filter() { return this.ctx.filter; }
764 /** 小程序文档中不包括 ↑↑↑ */
765 arc(...args) { return this.enqueueActions(this.ctx.arc, ...args); }
766 arcTo(...args) { return this.enqueueActions(this.ctx.arcTo, ...args); }
767 beginPath(...args) { return this.enqueueActions(this.ctx.beginPath, ...args); }
768 bezierCurveTo(...args) { return this.enqueueActions(this.ctx.bezierCurveTo, ...args); }
769 clearRect(...args) { return this.enqueueActions(this.ctx.clearRect, ...args); }
770 clip(...args) { return this.enqueueActions(this.ctx.clip, ...args); }
771 closePath(...args) { return this.enqueueActions(this.ctx.closePath, ...args); }
772 createPattern(imageResource, repetition) {
773 // 需要转换为 Image
774 if (typeof imageResource === 'string') {
775 const img = new Image();
776 img.src = imageResource;
777 return new Promise((resolve, reject) => {
778 img.onload = () => {
779 resolve(this.ctx.createPattern(img, repetition));
780 };
781 img.onerror = reject;
782 });
783 }
784 return this.ctx.createPattern(imageResource, repetition);
785 }
786 /**
787 * 将之前在绘图上下文中的描述(路径、变形、样式)画到 canvas 中。
788 * @todo 每次 draw 都会读取 width 和 height
789 */
790 draw(reserve, callback) {
791 return __awaiter(this, void 0, void 0, function* () {
792 try {
793 if (!reserve) {
794 this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
795 }
796 // 部分 action 是异步的
797 for (const { func, args } of this.actions) {
798 yield func.apply(this.ctx, args);
799 }
800 this.emptyActions();
801 callback && callback();
802 }
803 catch (e) {
804 /* eslint-disable no-throw-literal */
805 throw {
806 errMsg: e.message
807 };
808 }
809 });
810 }
811 drawImage(imageResource, ...extra) {
812 this.enqueueActions(() => {
813 // 需要转换为 Image
814 if (typeof imageResource === 'string') {
815 const img = new Image();
816 img.src = imageResource;
817 return new Promise((resolve, reject) => {
818 img.onload = () => {
819 this.ctx.drawImage(img, ...extra);
820 resolve();
821 };
822 img.onerror = reject;
823 });
824 }
825 this.ctx.drawImage(imageResource, ...extra);
826 });
827 }
828 fill(...args) { return this.enqueueActions(this.ctx.fill, ...args); }
829 fillRect(...args) { return this.enqueueActions(this.ctx.fillRect, ...args); }
830 fillText(...args) { return this.enqueueActions(this.ctx.fillText, ...args); }
831 lineTo(...args) { return this.enqueueActions(this.ctx.lineTo, ...args); }
832 moveTo(...args) { return this.enqueueActions(this.ctx.moveTo, ...args); }
833 quadraticCurveTo(...args) { return this.enqueueActions(this.ctx.quadraticCurveTo, ...args); }
834 rect(...args) { return this.enqueueActions(this.ctx.rect, ...args); }
835 // @ts-ignore
836 reset() { return this.ctx.reset(); }
837 restore() { return this.ctx.restore(); }
838 rotate(...args) { return this.enqueueActions(this.ctx.rotate, ...args); }
839 save() { return this.ctx.save(); }
840 scale(...args) { return this.enqueueActions(this.ctx.scale, ...args); }
841 setFillStyle(color) {
842 this.enqueueActions(() => { this.ctx.fillStyle = color; });
843 }
844 setFontSize(fontSize) {
845 const arr = this.font.split(/\s/);
846 const idx = arr.findIndex(e => /^\d+px$/.test(e));
847 if (idx !== -1) {
848 arr[idx] = `${fontSize}px`;
849 this.font = arr.join(' ');
850 }
851 }
852 setGlobalAlpha(alpha) {
853 this.globalAlpha = alpha;
854 }
855 setLineCap(lineCap) {
856 this.lineCap = lineCap;
857 }
858 setLineDash(pattern, offset) {
859 this.enqueueActions(() => {
860 this.ctx.setLineDash(pattern);
861 this.ctx.lineDashOffset = offset;
862 });
863 }
864 setLineJoin(lineJoin) {
865 this.lineJoin = lineJoin;
866 }
867 setLineWidth(lineWidth) {
868 this.lineWidth = lineWidth;
869 }
870 setMiterLimit(miterLimit) {
871 this.miterLimit = miterLimit;
872 }
873 setShadow(offsetX, offsetY, blur, color) {
874 this.enqueueActions(() => {
875 this.ctx.shadowOffsetX = offsetX;
876 this.ctx.shadowOffsetY = offsetY;
877 this.ctx.shadowColor = color;
878 this.ctx.shadowBlur = blur;
879 });
880 }
881 setStrokeStyle(color) {
882 this.enqueueActions(() => { this.ctx.strokeStyle = color; });
883 }
884 setTextAlign(align) {
885 this.textAlign = align;
886 }
887 setTextBaseline(textBaseline) {
888 this.textBaseline = TextBaseLineMap[textBaseline] || 'alphabetic';
889 }
890 setTransform(...args) { return this.enqueueActions(this.ctx.setTransform, ...args); }
891 stroke(...args) { return this.enqueueActions(this.ctx.stroke, ...args); }
892 strokeRect(...args) { return this.enqueueActions(this.ctx.strokeRect, ...args); }
893 strokeText(...args) { return this.enqueueActions(this.ctx.strokeText, ...args); }
894 transform(...args) { return this.enqueueActions(this.ctx.transform, ...args); }
895 translate(...args) { return this.enqueueActions(this.ctx.translate, ...args); }
896 measureText(text) {
897 return this.ctx.measureText(text);
898 }
899 createCircularGradient(x, y, r) {
900 const radialGradient = this.ctx.createRadialGradient(x, y, 0, x, y, r);
901 return radialGradient;
902 }
903 createLinearGradient(x0, y0, x1, y1) {
904 return this.ctx.createLinearGradient(x0, y0, x1, y1);
905 }
906}
907
908/**
909 * 创建 canvas 的绘图上下文 CanvasContext 对象
910 */
911const createCanvasContext = (canvasId, inst) => {
912 const el = findDOM(inst);
913 const canvas = el === null || el === void 0 ? void 0 : el.querySelector(`canvas[canvas-id="${canvasId}"]`);
914 const ctx = canvas === null || canvas === void 0 ? void 0 : canvas.getContext('2d');
915 const context = new CanvasContext(canvas, ctx);
916 if (!ctx)
917 return context;
918 context.canvas = canvas;
919 context.ctx = ctx;
920 return context;
921};
922
923/**
924 * 把当前画布指定区域的内容导出生成指定大小的图片。在 draw() 回调里调用该方法才能保证图片导出成功。
925 * @todo 暂未支持尺寸相关功能
926 */
927const canvasToTempFilePath = ({ canvasId, fileType, quality, success, fail, complete }, inst) => {
928 const handle = new MethodHandler({ name: 'canvasToTempFilePath', success, fail, complete });
929 const el = findDOM(inst);
930 const canvas = el === null || el === void 0 ? void 0 : el.querySelector(`canvas[canvas-id="${canvasId}"]`);
931 try {
932 const dataURL = canvas === null || canvas === void 0 ? void 0 : canvas.toDataURL(`image/${(fileType === 'jpg' ? 'jpeg' : fileType) || 'png'}`, quality);
933 return handle.success({
934 tempFilePath: dataURL
935 });
936 }
937 catch (e) {
938 return handle.fail({
939 errMsg: e.message
940 });
941 }
942};
943
944/**
945 * 将像素数据绘制到画布。在自定义组件下,第二个参数传入自定义组件实例 this,以操作组件内 <canvas> 组件
946 * @todo 暂未支持尺寸相关功能
947 */
948const canvasPutImageData = ({ canvasId, data, x, y, success, fail, complete }, inst) => {
949 const handle = new MethodHandler({ name: 'canvasPutImageData', success, fail, complete });
950 const el = findDOM(inst);
951 const canvas = el === null || el === void 0 ? void 0 : el.querySelector(`canvas[canvas-id="${canvasId}"]`);
952 try {
953 const ctx = canvas.getContext('2d');
954 // TODO Uint8ClampedArray => ImageData
955 ctx === null || ctx === void 0 ? void 0 : ctx.putImageData(data, x, y);
956 return handle.success();
957 }
958 catch (e) {
959 return handle.fail({
960 errMsg: e.message
961 });
962 }
963};
964
965/**
966 * 获取 canvas 区域隐含的像素数据。
967 */
968const canvasGetImageData = ({ canvasId, success, fail, complete, x, y, width, height }, inst) => {
969 const handle = new MethodHandler({ name: 'canvasGetImageData', success, fail, complete });
970 const el = findDOM(inst);
971 const canvas = el === null || el === void 0 ? void 0 : el.querySelector(`canvas[canvas-id="${canvasId}"]`);
972 try {
973 const ctx = canvas === null || canvas === void 0 ? void 0 : canvas.getContext('2d');
974 // TODO ImageData => Uint8ClampedArray
975 const data = ctx === null || ctx === void 0 ? void 0 : ctx.getImageData(x, y, width, height);
976 return handle.success({
977 width,
978 height,
979 data
980 });
981 }
982 catch (e) {
983 return handle.fail({
984 errMsg: e.message
985 });
986 }
987};
988
989// 画布
990/** 创建离屏 canvas 实例 */
991const createOffscreenCanvas = /* @__PURE__ */ temporarilyNotSupport('createOffscreenCanvas');
992
993class cloud {
994 constructor() {
995 this.init = temporarilyNotSupport('cloud.init');
996 this.CloudID = temporarilyNotSupport('cloud.CloudID');
997 // @ts-ignore
998 this.callFunction = temporarilyNotSupport('cloud.callFunction');
999 // @ts-ignore
1000 this.uploadFile = temporarilyNotSupport('cloud.uploadFile');
1001 // @ts-ignore
1002 this.downloadFile = temporarilyNotSupport('cloud.downloadFile');
1003 // @ts-ignore
1004 this.getTempFileURL = temporarilyNotSupport('cloud.getTempFileURL');
1005 // @ts-ignore
1006 this.deleteFile = temporarilyNotSupport('cloud.deleteFile');
1007 // @ts-ignore
1008 this.database = temporarilyNotSupport('cloud.database');
1009 // @ts-ignore
1010 this.callContainer = temporarilyNotSupport('cloud.callContainer');
1011 }
1012}
1013
1014const reportMonitor = /* @__PURE__ */ temporarilyNotSupport('reportMonitor');
1015const reportAnalytics = /* @__PURE__ */ temporarilyNotSupport('reportAnalytics');
1016const reportEvent = /* @__PURE__ */ temporarilyNotSupport('reportEvent');
1017const getExptInfoSync = /* @__PURE__ */ temporarilyNotSupport('getExptInfoSync');
1018
1019const callbackManager$3 = new CallbackManager();
1020let devicemotionListener;
1021/**
1022 * 停止监听加速度数据。
1023 */
1024const stopAccelerometer = ({ success, fail, complete } = {}) => {
1025 const res = {};
1026 const handle = new MethodHandler({ name: 'stopAccelerometer', success, fail, complete });
1027 try {
1028 window.removeEventListener('devicemotion', devicemotionListener, true);
1029 return handle.success(res);
1030 }
1031 catch (e) {
1032 res.errMsg = e.message;
1033 return handle.fail(res);
1034 }
1035};
1036const INTERVAL_MAP$1 = {
1037 game: {
1038 interval: 20,
1039 frequency: 50
1040 },
1041 ui: {
1042 interval: 60,
1043 frequency: 16.67
1044 },
1045 normal: {
1046 interval: 200,
1047 frequency: 5
1048 }
1049};
1050/**
1051 * 开始监听加速度数据。
1052 */
1053const startAccelerometer = ({ interval = 'normal', success, fail, complete } = {}) => {
1054 const handle = new MethodHandler({ name: 'startAccelerometer', success, fail, complete });
1055 try {
1056 if (window.DeviceMotionEvent) {
1057 const intervalObj = INTERVAL_MAP$1[interval];
1058 if (devicemotionListener) {
1059 stopAccelerometer();
1060 }
1061 devicemotionListener = throttle((evt) => {
1062 var _a, _b, _c;
1063 callbackManager$3.trigger({
1064 x: ((_a = evt.acceleration) === null || _a === void 0 ? void 0 : _a.x) || 0,
1065 y: ((_b = evt.acceleration) === null || _b === void 0 ? void 0 : _b.y) || 0,
1066 z: ((_c = evt.acceleration) === null || _c === void 0 ? void 0 : _c.z) || 0
1067 });
1068 }, intervalObj.interval);
1069 window.addEventListener('devicemotion', devicemotionListener, true);
1070 }
1071 else {
1072 throw new Error('accelerometer is not supported');
1073 }
1074 return handle.success();
1075 }
1076 catch (e) {
1077 return handle.fail({ errMsg: e.message });
1078 }
1079};
1080/**
1081 * 监听加速度数据事件。频率根据 Taro.startAccelerometer() 的 interval 参数。可使用 Taro.stopAccelerometer() 停止监听。
1082 */
1083const onAccelerometerChange = callback => {
1084 callbackManager$3.add(callback);
1085};
1086/**
1087 * 取消监听加速度数据事件,参数为空,则取消所有的事件监听
1088 */
1089const offAccelerometerChange = callback => {
1090 callbackManager$3.remove(callback);
1091};
1092
1093// 无障碍
1094const checkIsOpenAccessibility = /* @__PURE__ */ temporarilyNotSupport('checkIsOpenAccessibility');
1095
1096// 电量
1097// Note: 浏览器标准下不支持,其他实现方案不准确,不建议开发者使用
1098const getBatteryInfoSync = /* @__PURE__ */ permanentlyNotSupport('getBatteryInfoSync');
1099const getBatteryInfo = ({ success, fail, complete } = {}) => __awaiter(void 0, void 0, void 0, function* () {
1100 var _a;
1101 const handle = new MethodHandler({ name: 'getBatteryInfo', success, fail, complete });
1102 try {
1103 // @ts-ignore
1104 const battery = yield ((_a = navigator.getBattery) === null || _a === void 0 ? void 0 : _a.call(navigator));
1105 return handle.success({
1106 isCharging: battery.charging,
1107 level: Number(battery.level || 0) * 100
1108 });
1109 }
1110 catch (error) {
1111 return handle.fail({
1112 errMsg: (error === null || error === void 0 ? void 0 : error.message) || error
1113 });
1114 }
1115});
1116
1117// 蓝牙-通用
1118const stopBluetoothDevicesDiscovery = /* @__PURE__ */ temporarilyNotSupport('stopBluetoothDevicesDiscovery');
1119const startBluetoothDevicesDiscovery = /* @__PURE__ */ temporarilyNotSupport('startBluetoothDevicesDiscovery');
1120const openBluetoothAdapter = /* @__PURE__ */ temporarilyNotSupport('openBluetoothAdapter');
1121const onBluetoothDeviceFound = /* @__PURE__ */ temporarilyNotSupport('onBluetoothDeviceFound');
1122const onBluetoothAdapterStateChange = /* @__PURE__ */ temporarilyNotSupport('onBluetoothAdapterStateChange');
1123const offBluetoothDeviceFound = /* @__PURE__ */ temporarilyNotSupport('offBluetoothDeviceFound');
1124const offBluetoothAdapterStateChange = /* @__PURE__ */ temporarilyNotSupport('offBluetoothAdapterStateChange');
1125const makeBluetoothPair = /* @__PURE__ */ temporarilyNotSupport('makeBluetoothPair');
1126const isBluetoothDevicePaired = /* @__PURE__ */ temporarilyNotSupport('isBluetoothDevicePaired');
1127const getConnectedBluetoothDevices = /* @__PURE__ */ temporarilyNotSupport('getConnectedBluetoothDevices');
1128const getBluetoothDevices = /* @__PURE__ */ temporarilyNotSupport('getBluetoothDevices');
1129const getBluetoothAdapterState = /* @__PURE__ */ temporarilyNotSupport('getBluetoothAdapterState');
1130const closeBluetoothAdapter = /* @__PURE__ */ temporarilyNotSupport('closeBluetoothAdapter');
1131
1132// 蓝牙-低功耗中心设备
1133const writeBLECharacteristicValue = /* @__PURE__ */ temporarilyNotSupport('writeBLECharacteristicValue');
1134const setBLEMTU = /* @__PURE__ */ temporarilyNotSupport('setBLEMTU');
1135const readBLECharacteristicValue = /* @__PURE__ */ temporarilyNotSupport('readBLECharacteristicValue');
1136const onBLEMTUChange = /* @__PURE__ */ temporarilyNotSupport('onBLEMTUChange');
1137const onBLEConnectionStateChange = /* @__PURE__ */ temporarilyNotSupport('onBLEConnectionStateChange');
1138const onBLECharacteristicValueChange = /* @__PURE__ */ temporarilyNotSupport('onBLECharacteristicValueChange');
1139const offBLEMTUChange = /* @__PURE__ */ temporarilyNotSupport('offBLEMTUChange');
1140const offBLEConnectionStateChange = /* @__PURE__ */ temporarilyNotSupport('offBLEConnectionStateChange');
1141const offBLECharacteristicValueChange = /* @__PURE__ */ temporarilyNotSupport('offBLECharacteristicValueChange');
1142const notifyBLECharacteristicValueChange = /* @__PURE__ */ temporarilyNotSupport('notifyBLECharacteristicValueChange');
1143const getBLEMTU = /* @__PURE__ */ temporarilyNotSupport('getBLEMTU');
1144const getBLEDeviceServices = /* @__PURE__ */ temporarilyNotSupport('getBLEDeviceServices');
1145const getBLEDeviceRSSI = /* @__PURE__ */ temporarilyNotSupport('getBLEDeviceRSSI');
1146const getBLEDeviceCharacteristics = /* @__PURE__ */ temporarilyNotSupport('getBLEDeviceCharacteristics');
1147const createBLEConnection = /* @__PURE__ */ temporarilyNotSupport('createBLEConnection');
1148const closeBLEConnection = /* @__PURE__ */ temporarilyNotSupport('closeBLEConnection');
1149
1150// 蓝牙-低功耗外围设备
1151const onBLEPeripheralConnectionStateChanged = /* @__PURE__ */ temporarilyNotSupport('onBLEPeripheralConnectionStateChanged');
1152const offBLEPeripheralConnectionStateChanged = /* @__PURE__ */ temporarilyNotSupport('offBLEPeripheralConnectionStateChanged');
1153const createBLEPeripheralServer = /* @__PURE__ */ temporarilyNotSupport('createBLEPeripheralServer');
1154
1155// 日历
1156const addPhoneRepeatCalendar = (options) => {
1157 const methodName = 'addPhoneRepeatCalendar';
1158 // options must be an Object
1159 const isObject = shouldBeObject(options);
1160 if (!isObject.flag) {
1161 const res = { errMsg: `${methodName}:fail ${isObject.msg}` };
1162 console.error(res.errMsg);
1163 return Promise.reject(res);
1164 }
1165 const { title, startTime = new Date().getTime(), allDay = false, description = '', location = '', endTime, alarm = true, alarmOffset = 0, repeatInterval = 'month', repeatEndTime, success, fail, complete, } = options;
1166 const handle = new MethodHandler({ name: methodName, success, fail, complete });
1167 if (typeof title !== 'string') {
1168 return handle.fail({
1169 errMsg: getParameterError({
1170 para: 'title',
1171 correct: 'String',
1172 wrong: title
1173 })
1174 });
1175 }
1176 const start = new Date(startTime);
1177 const end = new Date(endTime || startTime);
1178 if (!endTime && allDay) {
1179 end.setDate(end.getDate() + 1);
1180 }
1181 const interval = 1000 * 60 * 60 * 24;
1182 let days = 1;
1183 let repeat = 1;
1184 if (repeatEndTime) {
1185 const repeatEnd = new Date(repeatEndTime);
1186 if (repeatEnd < start) {
1187 return handle.fail({
1188 errMsg: 'repeatEndTime must be greater than startTime'
1189 });
1190 }
1191 switch (repeatInterval) {
1192 case 'week':
1193 days = 7;
1194 break;
1195 case 'month':
1196 days = 30;
1197 break;
1198 case 'year':
1199 days = 365;
1200 break;
1201 default:
1202 }
1203 repeat = Math.ceil((repeatEnd.getTime() - start.getTime()) / (interval * days));
1204 }
1205 const { error, value } = ics.createEvent({
1206 title,
1207 start: parseTime2Array(start, allDay),
1208 description,
1209 location,
1210 end: parseTime2Array(end, allDay),
1211 alarms: alarm ? [{
1212 action: 'display',
1213 description,
1214 trigger: {
1215 before: true,
1216 seconds: alarmOffset,
1217 },
1218 duration: {
1219 days,
1220 },
1221 repeat,
1222 }] : [],
1223 });
1224 if (error || !value) {
1225 return handle.fail({
1226 errMsg: error === null || error === void 0 ? void 0 : error.message
1227 });
1228 }
1229 const url = URL.createObjectURL(new Blob([value]));
1230 createDownload(url, `${title}.ics`);
1231 return handle.success();
1232};
1233const addPhoneCalendar = (options) => {
1234 const methodName = 'addPhoneCalendar';
1235 // options must be an Object
1236 const isObject = shouldBeObject(options);
1237 if (!isObject.flag) {
1238 const res = { errMsg: `${methodName}:fail ${isObject.msg}` };
1239 console.error(res.errMsg);
1240 return Promise.reject(res);
1241 }
1242 const { title, startTime = new Date().getTime(), allDay = false, description = '', location = '', endTime, alarm = true, alarmOffset = 0, success, fail, complete, } = options;
1243 const handle = new MethodHandler({ name: methodName, success, fail, complete });
1244 if (typeof title !== 'string') {
1245 return handle.fail({
1246 errMsg: getParameterError({
1247 para: 'title',
1248 correct: 'String',
1249 wrong: title
1250 })
1251 });
1252 }
1253 const start = new Date(startTime);
1254 const end = new Date(endTime || startTime);
1255 if (!endTime && allDay) {
1256 end.setDate(end.getDate() + 1);
1257 }
1258 const { error, value } = ics.createEvent({
1259 title,
1260 start: parseTime2Array(start, allDay),
1261 description,
1262 location,
1263 end: parseTime2Array(end, allDay),
1264 alarms: alarm ? [{
1265 action: 'display',
1266 description,
1267 trigger: {
1268 before: true,
1269 seconds: alarmOffset,
1270 },
1271 }] : [],
1272 });
1273 if (error || !value) {
1274 return handle.fail({
1275 errMsg: error === null || error === void 0 ? void 0 : error.message
1276 });
1277 }
1278 const url = URL.createObjectURL(new Blob([value]));
1279 createDownload(url, `${title}.ics`);
1280 return handle.success();
1281};
1282function parseTime2Array(time, allDay = false) {
1283 const t = new Date(time);
1284 const timeArr = [
1285 t.getFullYear(),
1286 t.getMonth() + 1,
1287 t.getDate(),
1288 ];
1289 if (!allDay) {
1290 timeArr.push(t.getHours(), t.getMinutes());
1291 }
1292 return timeArr;
1293}
1294
1295// 周期性更新
1296const setBackgroundFetchToken = /* @__PURE__ */ temporarilyNotSupport('setBackgroundFetchToken');
1297const onBackgroundFetchData = /* @__PURE__ */ temporarilyNotSupport('onBackgroundFetchData');
1298const getBackgroundFetchToken = /* @__PURE__ */ temporarilyNotSupport('getBackgroundFetchToken');
1299const getBackgroundFetchData = /* @__PURE__ */ temporarilyNotSupport('getBackgroundFetchData');
1300
1301// 周期性更新
1302const createCacheManager = /* @__PURE__ */ temporarilyNotSupport('createCacheManager');
1303
1304function getItem(key) {
1305 let item;
1306 try {
1307 item = JSON.parse(localStorage.getItem(key) || '');
1308 }
1309 catch (e) { } // eslint-disable-line no-empty
1310 // 只返回使用 Taro.setStorage API 存储的数据
1311 if (item && typeof item === 'object' && item.hasOwnProperty('data')) {
1312 return { result: true, data: item.data };
1313 }
1314 else {
1315 return { result: false };
1316 }
1317}
1318// 数据缓存
1319const setStorageSync = (key, data = '') => {
1320 if (typeof key !== 'string') {
1321 console.error(getParameterError({
1322 name: 'setStorage',
1323 correct: 'String',
1324 wrong: key
1325 }));
1326 return;
1327 }
1328 const type = typeof data;
1329 let obj = {};
1330 if (type === 'symbol') {
1331 obj = { data: '' };
1332 }
1333 else {
1334 obj = { data };
1335 }
1336 localStorage.setItem(key, JSON.stringify(obj));
1337};
1338const setStorage = (options) => {
1339 // options must be an Object
1340 const isObject = shouldBeObject(options);
1341 if (!isObject.flag) {
1342 const res = { errMsg: `setStorage:fail ${isObject.msg}` };
1343 console.error(res.errMsg);
1344 return Promise.reject(res);
1345 }
1346 const { key, data, success, fail, complete } = options;
1347 const handle = new MethodHandler({ name: 'setStorage', success, fail, complete });
1348 if (typeof key !== 'string') {
1349 return handle.fail({
1350 errMsg: getParameterError({
1351 para: 'key',
1352 correct: 'String',
1353 wrong: key
1354 })
1355 });
1356 }
1357 setStorageSync(key, data);
1358 return handle.success();
1359};
1360const revokeBufferURL = /* @__PURE__ */ temporarilyNotSupport('revokeBufferURL');
1361const removeStorageSync = (key) => {
1362 if (typeof key !== 'string') {
1363 console.error(getParameterError({
1364 name: 'removeStorage',
1365 correct: 'String',
1366 wrong: key
1367 }));
1368 return;
1369 }
1370 localStorage.removeItem(key);
1371};
1372const removeStorage = (options) => {
1373 // options must be an Object
1374 const isObject = shouldBeObject(options);
1375 if (!isObject.flag) {
1376 const res = { errMsg: `removeStorage:fail ${isObject.msg}` };
1377 console.error(res.errMsg);
1378 return Promise.reject(res);
1379 }
1380 const { key, success, fail, complete } = options;
1381 const handle = new MethodHandler({ name: 'removeStorage', success, fail, complete });
1382 if (typeof key !== 'string') {
1383 return handle.fail({
1384 errMsg: getParameterError({
1385 para: 'key',
1386 correct: 'String',
1387 wrong: key
1388 })
1389 });
1390 }
1391 removeStorageSync(key);
1392 return handle.success();
1393};
1394const getStorageSync = (key) => {
1395 if (typeof key !== 'string') {
1396 console.error(getParameterError({
1397 name: 'getStorageSync',
1398 correct: 'String',
1399 wrong: key
1400 }));
1401 return;
1402 }
1403 const res = getItem(key);
1404 if (res.result)
1405 return res.data;
1406 return '';
1407};
1408const getStorageInfoSync = () => {
1409 const res = {
1410 keys: Object.keys(localStorage),
1411 limitSize: NaN,
1412 currentSize: NaN
1413 };
1414 return res;
1415};
1416const getStorageInfo = ({ success, fail, complete } = {}) => {
1417 const handle = new MethodHandler({ name: 'getStorageInfo', success, fail, complete });
1418 return handle.success(getStorageInfoSync());
1419};
1420const getStorage = (options) => {
1421 // options must be an Object
1422 const isObject = shouldBeObject(options);
1423 if (!isObject.flag) {
1424 const res = { errMsg: `getStorage:fail ${isObject.msg}` };
1425 console.error(res.errMsg);
1426 return Promise.reject(res);
1427 }
1428 const { key, success, fail, complete } = options;
1429 const handle = new MethodHandler({ name: 'getStorage', success, fail, complete });
1430 if (typeof key !== 'string') {
1431 return handle.fail({
1432 errMsg: getParameterError({
1433 para: 'key',
1434 correct: 'String',
1435 wrong: key
1436 })
1437 });
1438 }
1439 const { result, data } = getItem(key);
1440 if (result) {
1441 return handle.success({ data });
1442 }
1443 else {
1444 return handle.fail({
1445 errMsg: 'data not found'
1446 });
1447 }
1448};
1449const createBufferURL = /* @__PURE__ */ temporarilyNotSupport('createBufferURL');
1450const clearStorageSync = () => {
1451 localStorage.clear();
1452};
1453const clearStorage = ({ success, fail, complete } = {}) => {
1454 const handle = new MethodHandler({ name: 'clearStorage', success, fail, complete });
1455 clearStorageSync();
1456 return handle.success();
1457};
1458const batchSetStorageSync = /* @__PURE__ */ temporarilyNotSupport('batchSetStorageSync');
1459const batchSetStorage = /* @__PURE__ */ temporarilyNotSupport('batchSetStorage');
1460const batchGetStorageSync = /* @__PURE__ */ temporarilyNotSupport('batchGetStorageSync');
1461const batchGetStorage = /* @__PURE__ */ temporarilyNotSupport('batchGetStorage');
1462
1463const noop = function () { };
1464class ActionSheet {
1465 constructor() {
1466 this.options = {
1467 alertText: '',
1468 itemList: [],
1469 itemColor: '#000000',
1470 success: noop,
1471 fail: noop,
1472 complete: noop,
1473 };
1474 this.style = {
1475 maskStyle: {
1476 position: 'fixed',
1477 'z-index': '1000',
1478 top: '0',
1479 right: '0',
1480 left: '0',
1481 bottom: '0',
1482 background: 'rgba(0,0,0,0.6)',
1483 },
1484 actionSheetStyle: {
1485 'z-index': '4999',
1486 position: 'fixed',
1487 left: '0',
1488 bottom: '0',
1489 '-webkit-transform': 'translate(0, 100%)',
1490 transform: 'translate(0, 100%)',
1491 width: '100%',
1492 'line-height': '1.6',
1493 background: '#EFEFF4',
1494 '-webkit-transition': '-webkit-transform .3s',
1495 transition: 'transform .3s',
1496 'border-radius': '15px 15px 0 0',
1497 },
1498 menuStyle: {
1499 'background-color': '#FCFCFD',
1500 'border-radius': '15px 15px 0 0',
1501 },
1502 cellStyle: {
1503 position: 'relative',
1504 padding: '10px 0',
1505 'text-align': 'center',
1506 'font-size': '18px',
1507 },
1508 titleStyle: {
1509 position: 'relative',
1510 padding: '10px 0',
1511 'text-align': 'center',
1512 'font-size': '16px',
1513 color: 'rgba(0,0,0,0.8)',
1514 display: 'none',
1515 },
1516 cancelStyle: {
1517 'margin-top': '6px',
1518 padding: '10px 0',
1519 'text-align': 'center',
1520 'font-size': '18px',
1521 color: '#000000',
1522 'background-color': '#FCFCFD',
1523 },
1524 };
1525 this.lastConfig = {};
1526 }
1527 create(options = {}) {
1528 return new Promise((resolve) => {
1529 // style
1530 const { maskStyle, actionSheetStyle, menuStyle, cellStyle, titleStyle, cancelStyle } = this.style;
1531 // configuration
1532 const config = Object.assign(Object.assign({}, this.options), options);
1533 this.lastConfig = config;
1534 // wrapper
1535 this.el = document.createElement('div');
1536 this.el.className = 'taro__actionSheet';
1537 this.el.style.opacity = '0';
1538 this.el.style.transition = 'opacity 0.2s linear';
1539 // mask
1540 this.mask = document.createElement('div');
1541 this.mask.setAttribute('style', inlineStyle(maskStyle));
1542 // actionSheet
1543 this.actionSheet = document.createElement('div');
1544 this.actionSheet.setAttribute('style', inlineStyle(actionSheetStyle));
1545 // menu
1546 this.menu = document.createElement('div');
1547 this.menu.setAttribute('style', inlineStyle(Object.assign(Object.assign({}, menuStyle), { color: config.itemColor })));
1548 // cells
1549 this.cells = config.itemList.map((item, index) => {
1550 const cell = document.createElement('div');
1551 cell.className = 'taro-actionsheet__cell';
1552 cell.setAttribute('style', inlineStyle(cellStyle));
1553 cell.textContent = item;
1554 cell.dataset.tapIndex = `${index}`;
1555 cell.onclick = (e) => {
1556 this.hide();
1557 const target = e.currentTarget;
1558 const index = Number(target === null || target === void 0 ? void 0 : target.dataset.tapIndex) || 0;
1559 resolve(index);
1560 };
1561 return cell;
1562 });
1563 // title
1564 this.title = document.createElement('div');
1565 this.title.setAttribute('style', inlineStyle(titleStyle));
1566 this.title.className = 'taro-actionsheet__cell';
1567 this.title.textContent = config.alertText;
1568 this.title.style.display = config.alertText ? 'block' : 'none';
1569 // cancel
1570 this.cancel = document.createElement('div');
1571 this.cancel.setAttribute('style', inlineStyle(cancelStyle));
1572 this.cancel.textContent = '取消';
1573 // result
1574 this.menu.appendChild(this.title);
1575 this.cells.forEach((item) => this.menu.appendChild(item));
1576 this.actionSheet.appendChild(this.menu);
1577 this.actionSheet.appendChild(this.cancel);
1578 this.el.appendChild(this.mask);
1579 this.el.appendChild(this.actionSheet);
1580 // callbacks
1581 const cb = () => {
1582 this.hide();
1583 resolve('cancel');
1584 };
1585 this.mask.onclick = cb;
1586 this.cancel.onclick = cb;
1587 // show immediately
1588 document.body.appendChild(this.el);
1589 setTimeout(() => {
1590 this.el.style.opacity = '1';
1591 setTransform(this.actionSheet, 'translate(0, 0)');
1592 }, 0);
1593 });
1594 }
1595 show(options = {}) {
1596 return new Promise((resolve) => {
1597 const config = Object.assign(Object.assign({}, this.options), options);
1598 this.lastConfig = config;
1599 if (this.hideOpacityTimer)
1600 clearTimeout(this.hideOpacityTimer);
1601 if (this.hideDisplayTimer)
1602 clearTimeout(this.hideDisplayTimer);
1603 // itemColor
1604 if (config.itemColor)
1605 this.menu.style.color = config.itemColor;
1606 // cells
1607 const { cellStyle } = this.style;
1608 config.itemList.forEach((item, index) => {
1609 let cell;
1610 if (this.cells[index]) {
1611 // assign new content
1612 cell = this.cells[index];
1613 }
1614 else {
1615 // create new cell
1616 cell = document.createElement('div');
1617 cell.className = 'taro-actionsheet__cell';
1618 cell.setAttribute('style', inlineStyle(cellStyle));
1619 cell.dataset.tapIndex = `${index}`;
1620 this.cells.push(cell);
1621 this.menu.appendChild(cell);
1622 }
1623 cell.textContent = item;
1624 cell.onclick = (e) => {
1625 this.hide();
1626 const target = e.currentTarget;
1627 const index = Number(target === null || target === void 0 ? void 0 : target.dataset.tapIndex) || 0;
1628 resolve(index);
1629 };
1630 });
1631 const cellsLen = this.cells.length;
1632 const itemListLen = config.itemList.length;
1633 if (cellsLen > itemListLen) {
1634 for (let i = itemListLen; i < cellsLen; i++) {
1635 this.menu.removeChild(this.cells[i]);
1636 }
1637 this.cells.splice(itemListLen);
1638 }
1639 this.title.textContent = config.alertText;
1640 this.title.style.display = config.alertText ? 'block' : 'none';
1641 // callbacks
1642 const cb = () => {
1643 this.hide();
1644 resolve('cancel');
1645 };
1646 this.mask.onclick = cb;
1647 this.cancel.onclick = cb;
1648 // show
1649 this.el.style.display = 'block';
1650 setTimeout(() => {
1651 this.el.style.opacity = '1';
1652 setTransform(this.actionSheet, 'translate(0, 0)');
1653 }, 0);
1654 });
1655 }
1656 hide() {
1657 if (this.hideOpacityTimer)
1658 clearTimeout(this.hideOpacityTimer);
1659 if (this.hideDisplayTimer)
1660 clearTimeout(this.hideDisplayTimer);
1661 this.hideOpacityTimer = setTimeout(() => {
1662 this.el.style.opacity = '0';
1663 setTransform(this.actionSheet, 'translate(0, 100%)');
1664 this.hideDisplayTimer = setTimeout(() => {
1665 this.el.style.display = 'none';
1666 }, 200);
1667 }, 0);
1668 }
1669}
1670
1671class Modal {
1672 constructor() {
1673 this.options = {
1674 title: '',
1675 content: '',
1676 showCancel: true,
1677 cancelText: '取消',
1678 cancelColor: '#000000',
1679 confirmText: '确定',
1680 confirmColor: '#3CC51F'
1681 };
1682 this.style = {
1683 maskStyle: {
1684 position: 'fixed',
1685 'z-index': '1000',
1686 top: '0',
1687 right: '0',
1688 left: '0',
1689 bottom: '0',
1690 background: 'rgba(0,0,0,0.6)'
1691 },
1692 modalStyle: {
1693 'z-index': '4999',
1694 position: 'fixed',
1695 top: '50%',
1696 left: '50%',
1697 transform: 'translate(-50%, -50%)',
1698 width: '80%',
1699 'max-width': '300px',
1700 'border-radius': '3px',
1701 'text-align': 'center',
1702 'line-height': '1.6',
1703 overflow: 'hidden',
1704 background: '#FFFFFF'
1705 },
1706 titleStyle: {
1707 padding: '20px 24px 9px',
1708 'font-size': '18px'
1709 },
1710 textStyle: {
1711 padding: '0 24px 12px',
1712 'min-height': '40px',
1713 'font-size': '15px',
1714 'line-height': '1.3',
1715 color: '#808080',
1716 'word-wrap': 'break-word',
1717 'word-break': 'break-all',
1718 },
1719 footStyle: {
1720 position: 'relative',
1721 'line-height': '48px',
1722 'font-size': '18px',
1723 display: 'flex'
1724 },
1725 btnStyle: {
1726 position: 'relative',
1727 '-webkit-box-flex': '1',
1728 '-webkit-flex': '1',
1729 flex: '1'
1730 }
1731 };
1732 }
1733 create(options = {}) {
1734 return new Promise((resolve) => {
1735 var _a, _b;
1736 // style
1737 const { maskStyle, modalStyle, titleStyle, textStyle, footStyle, btnStyle } = this.style;
1738 // configuration
1739 const config = Object.assign(Object.assign({}, this.options), options);
1740 // wrapper
1741 this.el = document.createElement('div');
1742 this.el.className = 'taro__modal';
1743 this.el.style.opacity = '0';
1744 this.el.style.transition = 'opacity 0.2s linear';
1745 const eventHandler = (e) => {
1746 e.stopPropagation();
1747 e.preventDefault();
1748 };
1749 // mask
1750 const mask = document.createElement('div');
1751 mask.className = 'taro-modal__mask';
1752 mask.setAttribute('style', inlineStyle(maskStyle));
1753 mask.ontouchmove = eventHandler;
1754 // modal
1755 const modal = document.createElement('div');
1756 modal.className = 'taro-modal__content';
1757 modal.setAttribute('style', inlineStyle(modalStyle));
1758 modal.ontouchmove = eventHandler;
1759 // title
1760 const titleCSS = config.title ? titleStyle : Object.assign(Object.assign({}, titleStyle), { display: 'none' });
1761 this.title = document.createElement('div');
1762 this.title.className = 'taro-modal__title';
1763 this.title.setAttribute('style', inlineStyle(titleCSS));
1764 this.title.textContent = config.title;
1765 // text
1766 const textCSS = config.title ? textStyle : Object.assign(Object.assign({}, textStyle), { padding: '40px 20px 26px', color: '#353535' });
1767 this.text = document.createElement('div');
1768 this.text.className = 'taro-modal__text';
1769 this.text.setAttribute('style', inlineStyle(textCSS));
1770 this.text.textContent = config.content;
1771 // foot
1772 const foot = document.createElement('div');
1773 foot.className = 'taro-modal__foot';
1774 foot.setAttribute('style', inlineStyle(footStyle));
1775 // cancel button
1776 const cancelCSS = Object.assign(Object.assign({}, btnStyle), { color: config.cancelColor, display: config.showCancel ? 'block' : 'none' });
1777 this.cancel = document.createElement('div');
1778 this.cancel.className = 'taro-model__btn taro-model__cancel';
1779 this.cancel.setAttribute('style', inlineStyle(cancelCSS));
1780 this.cancel.textContent = config.cancelText;
1781 this.cancel.onclick = () => {
1782 this.hide();
1783 resolve('cancel');
1784 };
1785 // confirm button
1786 this.confirm = document.createElement('div');
1787 this.confirm.className = 'taro-model__btn taro-model__confirm';
1788 this.confirm.setAttribute('style', inlineStyle(btnStyle));
1789 this.confirm.style.color = config.confirmColor;
1790 this.confirm.textContent = config.confirmText;
1791 this.confirm.onclick = () => {
1792 this.hide();
1793 resolve('confirm');
1794 };
1795 // result
1796 foot.appendChild(this.cancel);
1797 foot.appendChild(this.confirm);
1798 modal.appendChild(this.title);
1799 modal.appendChild(this.text);
1800 modal.appendChild(foot);
1801 this.el.appendChild(mask);
1802 this.el.appendChild(modal);
1803 // show immediately
1804 document.body.appendChild(this.el);
1805 setTimeout(() => { this.el.style.opacity = '1'; }, 0);
1806 // Current.page不存在时说明路由还未挂载,此时需根据url来分配将要渲染的页面path
1807 this.currentPath = (_b = (_a = Current$1.page) === null || _a === void 0 ? void 0 : _a.path) !== null && _b !== void 0 ? _b : getCurrentPath();
1808 });
1809 }
1810 show(options = {}) {
1811 return new Promise((resolve) => {
1812 var _a, _b;
1813 const config = Object.assign(Object.assign({}, this.options), options);
1814 if (this.hideOpacityTimer)
1815 clearTimeout(this.hideOpacityTimer);
1816 if (this.hideDisplayTimer)
1817 clearTimeout(this.hideDisplayTimer);
1818 // title & text
1819 const { textStyle } = this.style;
1820 if (config.title) {
1821 this.title.textContent = config.title;
1822 // none => block
1823 this.title.style.display = 'block';
1824 this.text.setAttribute('style', inlineStyle(textStyle));
1825 }
1826 else {
1827 this.title.textContent = '';
1828 // block => none
1829 this.title.style.display = 'none';
1830 const textCSS = Object.assign(Object.assign({}, textStyle), { padding: '40px 20px 26px', color: '#353535' });
1831 this.text.setAttribute('style', inlineStyle(textCSS));
1832 }
1833 this.text.textContent = config.content || '';
1834 // showCancel
1835 this.cancel.style.display = config.showCancel ? 'block' : 'none';
1836 // cancelText
1837 this.cancel.textContent = config.cancelText || '';
1838 // cancelColor
1839 this.cancel.style.color = config.cancelColor || '';
1840 // confirmText
1841 this.confirm.textContent = config.confirmText || '';
1842 // confirmColor
1843 this.confirm.style.color = config.confirmColor || '';
1844 // cbs
1845 this.cancel.onclick = () => {
1846 this.hide();
1847 resolve('cancel');
1848 };
1849 this.confirm.onclick = () => {
1850 this.hide();
1851 resolve('confirm');
1852 };
1853 // show
1854 this.el.style.display = 'block';
1855 setTimeout(() => { this.el.style.opacity = '1'; }, 0);
1856 // Current.page不存在时说明路由还未挂载,此时需根据url来分配将要渲染的页面path
1857 this.currentPath = (_b = (_a = Current$1.page) === null || _a === void 0 ? void 0 : _a.path) !== null && _b !== void 0 ? _b : getCurrentPath();
1858 });
1859 }
1860 hide() {
1861 if (this.hideOpacityTimer)
1862 clearTimeout(this.hideOpacityTimer);
1863 if (this.hideDisplayTimer)
1864 clearTimeout(this.hideDisplayTimer);
1865 this.currentPath = null;
1866 this.hideOpacityTimer = setTimeout(() => {
1867 this.el.style.opacity = '0';
1868 this.hideDisplayTimer = setTimeout(() => { this.el.style.display = 'none'; }, 200);
1869 }, 0);
1870 }
1871}
1872
1873class Toast {
1874 constructor() {
1875 this.options = {
1876 title: '',
1877 icon: 'none',
1878 image: '',
1879 duration: 1500,
1880 mask: false
1881 };
1882 this.style = {
1883 maskStyle: {
1884 position: 'fixed',
1885 'z-index': '1000',
1886 top: '0',
1887 right: '0',
1888 left: '0',
1889 bottom: '0'
1890 },
1891 toastStyle: {
1892 'z-index': '5000',
1893 'box-sizing': 'border-box',
1894 display: 'flex',
1895 'flex-direction': 'column',
1896 'justify-content': 'center',
1897 '-webkit-justify-content': 'center',
1898 position: 'fixed',
1899 top: '50%',
1900 left: '50%',
1901 'min-width': '120px',
1902 'max-width': '200px',
1903 'min-height': '120px',
1904 padding: '15px',
1905 transform: 'translate(-50%, -50%)',
1906 'border-radius': '5px',
1907 'text-align': 'center',
1908 'line-height': '1.6',
1909 color: '#FFFFFF',
1910 background: 'rgba(17, 17, 17, 0.7)'
1911 },
1912 successStyle: {
1913 margin: '6px auto',
1914 width: '38px',
1915 height: '38px',
1916 background: 'transparent url(data:image/svg+xml;base64,PHN2ZyB0PSIxNjM5NTQ4OTYzMjA0IiBjbGFzcz0iaWNvbiIgdmlld0JveD0iMCAwIDEwMjQgMTAyNCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHAtaWQ9IjQzNDgiIHdpZHRoPSIyMDAiIGhlaWdodD0iMjAwIj48cGF0aCBkPSJNMjE5Ljk1MiA1MTIuNTc2bDIxMC40MzIgMjEwLjQzMi00NS4yNDggNDUuMjU2LTIxMC40MzItMjEwLjQzMnoiIHAtaWQ9IjQzNDkiIGZpbGw9IiNmZmZmZmYiPjwvcGF0aD48cGF0aCBkPSJNNzk5LjY3MiAyNjIuMjY0bDQ1LjI1NiA0NS4yNTYtNDYwLjQ2NCA0NjAuNDY0LTQ1LjI1Ni00NS4yNTZ6IiBwLWlkPSI0MzUwIiBmaWxsPSIjZmZmZmZmIj48L3BhdGg+PC9zdmc+) no-repeat',
1917 'background-size': '100%'
1918 },
1919 errrorStyle: {
1920 margin: '6px auto',
1921 width: '38px',
1922 height: '38px',
1923 background: 'transparent url(data:image/svg+xml;base64,PHN2ZyB0PSIxNjM5NTUxMDU1MTgzIiBjbGFzcz0iaWNvbiIgdmlld0JveD0iMCAwIDEwMjQgMTAyNCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHAtaWQ9IjE0MDc2IiB3aWR0aD0iMjAwIiBoZWlnaHQ9IjIwMCI+PHBhdGggZD0iTTUxMiA2NEMyNjQuNTggNjQgNjQgMjY0LjU4IDY0IDUxMnMyMDAuNTggNDQ4IDQ0OCA0NDggNDQ4LTIwMC41OCA0NDgtNDQ4Uzc1OS40MiA2NCA1MTIgNjR6IG0wIDc1MmEzNiAzNiAwIDEgMSAzNi0zNiAzNiAzNiAwIDAgMS0zNiAzNnogbTUxLjgzLTU1MS45NUw1NDggNjM2YTM2IDM2IDAgMCAxLTcyIDBsLTE1LjgzLTM3MS45NWMtMC4xLTEuMzMtMC4xNy0yLjY4LTAuMTctNC4wNWE1MiA1MiAwIDAgMSAxMDQgMGMwIDEuMzctMC4wNyAyLjcyLTAuMTcgNC4wNXoiIHAtaWQ9IjE0MDc3IiBmaWxsPSIjZmZmZmZmIj48L3BhdGg+PC9zdmc+) no-repeat',
1924 'background-size': '100%'
1925 },
1926 loadingStyle: {
1927 margin: '6px auto',
1928 width: '38px',
1929 height: '38px',
1930 '-webkit-animation': 'taroLoading 1s steps(12, end) infinite',
1931 animation: 'taroLoading 1s steps(12, end) infinite',
1932 background: 'transparent url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMjAiIGhlaWdodD0iMTIwIiB2aWV3Qm94PSIwIDAgMTAwIDEwMCI+PHBhdGggZmlsbD0ibm9uZSIgZD0iTTAgMGgxMDB2MTAwSDB6Ii8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjRTlFOUU5IiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDAgLTMwKSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41IiB5PSI0MCIgZmlsbD0iIzk4OTY5NyIgcng9IjUiIHJ5PSI1IiB0cmFuc2Zvcm09InJvdGF0ZSgzMCAxMDUuOTggNjUpIi8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjOUI5OTlBIiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0icm90YXRlKDYwIDc1Ljk4IDY1KSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41IiB5PSI0MCIgZmlsbD0iI0EzQTFBMiIgcng9IjUiIHJ5PSI1IiB0cmFuc2Zvcm09InJvdGF0ZSg5MCA2NSA2NSkiLz48cmVjdCB3aWR0aD0iNyIgaGVpZ2h0PSIyMCIgeD0iNDYuNSIgeT0iNDAiIGZpbGw9IiNBQkE5QUEiIHJ4PSI1IiByeT0iNSIgdHJhbnNmb3JtPSJyb3RhdGUoMTIwIDU4LjY2IDY1KSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41IiB5PSI0MCIgZmlsbD0iI0IyQjJCMiIgcng9IjUiIHJ5PSI1IiB0cmFuc2Zvcm09InJvdGF0ZSgxNTAgNTQuMDIgNjUpIi8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjQkFCOEI5IiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0icm90YXRlKDE4MCA1MCA2NSkiLz48cmVjdCB3aWR0aD0iNyIgaGVpZ2h0PSIyMCIgeD0iNDYuNSIgeT0iNDAiIGZpbGw9IiNDMkMwQzEiIHJ4PSI1IiByeT0iNSIgdHJhbnNmb3JtPSJyb3RhdGUoLTE1MCA0NS45OCA2NSkiLz48cmVjdCB3aWR0aD0iNyIgaGVpZ2h0PSIyMCIgeD0iNDYuNSIgeT0iNDAiIGZpbGw9IiNDQkNCQ0IiIHJ4PSI1IiByeT0iNSIgdHJhbnNmb3JtPSJyb3RhdGUoLTEyMCA0MS4zNCA2NSkiLz48cmVjdCB3aWR0aD0iNyIgaGVpZ2h0PSIyMCIgeD0iNDYuNSIgeT0iNDAiIGZpbGw9IiNEMkQyRDIiIHJ4PSI1IiByeT0iNSIgdHJhbnNmb3JtPSJyb3RhdGUoLTkwIDM1IDY1KSIvPjxyZWN0IHdpZHRoPSI3IiBoZWlnaHQ9IjIwIiB4PSI0Ni41IiB5PSI0MCIgZmlsbD0iI0RBREFEQSIgcng9IjUiIHJ5PSI1IiB0cmFuc2Zvcm09InJvdGF0ZSgtNjAgMjQuMDIgNjUpIi8+PHJlY3Qgd2lkdGg9IjciIGhlaWdodD0iMjAiIHg9IjQ2LjUiIHk9IjQwIiBmaWxsPSIjRTJFMkUyIiByeD0iNSIgcnk9IjUiIHRyYW5zZm9ybT0icm90YXRlKC0zMCAtNS45OCA2NSkiLz48L3N2Zz4=) no-repeat',
1933 'background-size': '100%'
1934 },
1935 imageStyle: {
1936 margin: '6px auto',
1937 width: '40px',
1938 height: '40px',
1939 background: 'transparent no-repeat',
1940 'background-size': '100%'
1941 },
1942 textStyle: {
1943 margin: '0',
1944 'font-size': '16px'
1945 }
1946 };
1947 }
1948 create(options = {}, _type = 'toast') {
1949 var _a, _b;
1950 // style
1951 const { maskStyle, toastStyle, successStyle, errrorStyle, loadingStyle, imageStyle, textStyle } = this.style;
1952 // configuration
1953 const config = Object.assign(Object.assign(Object.assign({}, this.options), options), { _type });
1954 // wrapper
1955 this.el = document.createElement('div');
1956 this.el.className = 'taro__toast';
1957 this.el.style.opacity = '0';
1958 this.el.style.transition = 'opacity 0.1s linear';
1959 this.el.ontouchmove = (e) => {
1960 e.stopPropagation();
1961 e.preventDefault();
1962 };
1963 // mask
1964 this.mask = document.createElement('div');
1965 this.mask.setAttribute('style', inlineStyle(maskStyle));
1966 this.mask.style.display = config.mask ? 'block' : 'none';
1967 // icon
1968 this.icon = document.createElement('p');
1969 if (config.image) {
1970 this.icon.setAttribute('style', inlineStyle(Object.assign(Object.assign({}, imageStyle), { 'background-image': `url(${config.image})` })));
1971 }
1972 else {
1973 const iconStyle = config.icon === 'loading' ? loadingStyle : config.icon === 'error' ? errrorStyle : successStyle;
1974 this.icon.setAttribute('style', inlineStyle(Object.assign(Object.assign({}, iconStyle), (config.icon === 'none' ? { display: 'none' } : {}))));
1975 }
1976 // toast
1977 this.toast = document.createElement('div');
1978 this.toast.setAttribute('style', inlineStyle(Object.assign(Object.assign({}, toastStyle), (config.icon === 'none' ? {
1979 'min-height': '0',
1980 padding: '10px 15px'
1981 } : {}))));
1982 // title
1983 this.title = document.createElement('p');
1984 this.title.setAttribute('style', inlineStyle(textStyle));
1985 this.title.textContent = config.title;
1986 // result
1987 this.toast.appendChild(this.icon);
1988 this.toast.appendChild(this.title);
1989 this.el.appendChild(this.mask);
1990 this.el.appendChild(this.toast);
1991 // show immediately
1992 document.body.appendChild(this.el);
1993 setTimeout(() => { this.el.style.opacity = '1'; }, 0);
1994 this.type = config._type;
1995 // disappear after duration
1996 config.duration >= 0 && this.hide(config.duration, this.type);
1997 // Current.page不存在时说明路由还未挂载,此时需根据url来分配将要渲染的页面path
1998 this.currentPath = (_b = (_a = Current$1.page) === null || _a === void 0 ? void 0 : _a.path) !== null && _b !== void 0 ? _b : getCurrentPath();
1999 return '';
2000 }
2001 show(options = {}, _type = 'toast') {
2002 var _a, _b;
2003 const config = Object.assign(Object.assign(Object.assign({}, this.options), options), { _type });
2004 if (this.hideOpacityTimer)
2005 clearTimeout(this.hideOpacityTimer);
2006 if (this.hideDisplayTimer)
2007 clearTimeout(this.hideDisplayTimer);
2008 // title
2009 this.title.textContent = config.title || '';
2010 // mask
2011 this.mask.style.display = config.mask ? 'block' : 'none';
2012 // image
2013 const { toastStyle, successStyle, errrorStyle, loadingStyle, imageStyle } = this.style;
2014 if (config.image) {
2015 this.icon.setAttribute('style', inlineStyle(Object.assign(Object.assign({}, imageStyle), { 'background-image': `url(${config.image})` })));
2016 }
2017 else {
2018 if (!config.image && config.icon) {
2019 const iconStyle = config.icon === 'loading' ? loadingStyle : config.icon === 'error' ? errrorStyle : successStyle;
2020 this.icon.setAttribute('style', inlineStyle(Object.assign(Object.assign({}, iconStyle), (config.icon === 'none' ? { display: 'none' } : {}))));
2021 }
2022 }
2023 // toast
2024 this.toast.setAttribute('style', inlineStyle(Object.assign(Object.assign({}, toastStyle), (config.icon === 'none' ? {
2025 'min-height': '0',
2026 padding: '10px 15px'
2027 } : {}))));
2028 // show
2029 this.el.style.display = 'block';
2030 setTimeout(() => { this.el.style.opacity = '1'; }, 0);
2031 this.type = config._type;
2032 // disappear after duration
2033 config.duration >= 0 && this.hide(config.duration, this.type);
2034 // Current.page不存在时说明路由还未挂载,此时需根据url来分配将要渲染的页面path
2035 this.currentPath = (_b = (_a = Current$1.page) === null || _a === void 0 ? void 0 : _a.path) !== null && _b !== void 0 ? _b : getCurrentPath();
2036 return '';
2037 }
2038 hide(duration = 0, type = '') {
2039 if (type && type !== this.type)
2040 return;
2041 if (this.hideOpacityTimer)
2042 clearTimeout(this.hideOpacityTimer);
2043 if (this.hideDisplayTimer)
2044 clearTimeout(this.hideDisplayTimer);
2045 this.currentPath = null;
2046 this.hideOpacityTimer = setTimeout(() => {
2047 this.el.style.opacity = '0';
2048 this.hideDisplayTimer = setTimeout(() => { this.el.style.display = 'none'; }, 100);
2049 }, duration);
2050 }
2051}
2052
2053// 交互
2054let status = 'default';
2055// inject necessary style
2056function init(doc) {
2057 if (status === 'ready')
2058 return;
2059 const taroStyle = doc.createElement('style');
2060 taroStyle.textContent =
2061 '@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);}';
2062 doc.querySelector('head').appendChild(taroStyle);
2063 status = 'ready';
2064}
2065const toast = new Toast();
2066const modal = new Modal();
2067const actionSheet = new ActionSheet();
2068const showToast = (options = { title: '' }) => {
2069 init(document);
2070 options = Object.assign({
2071 title: '',
2072 icon: 'success',
2073 image: '',
2074 duration: 1500,
2075 mask: false
2076 }, options);
2077 const { success, fail, complete } = options;
2078 const handle = new MethodHandler({ name: 'showToast', success, fail, complete });
2079 if (typeof options.title !== 'string') {
2080 return handle.fail({
2081 errMsg: getParameterError({
2082 para: 'title',
2083 correct: 'String',
2084 wrong: options.title
2085 })
2086 });
2087 }
2088 if (typeof options.duration !== 'number') {
2089 return handle.fail({
2090 errMsg: getParameterError({
2091 para: 'duration',
2092 correct: 'Number',
2093 wrong: options.duration
2094 })
2095 });
2096 }
2097 if (options.image && typeof options.image !== 'string')
2098 options.image = '';
2099 options.mask = !!options.mask;
2100 let errMsg = '';
2101 if (!toast.el) {
2102 errMsg = toast.create(options, 'toast');
2103 }
2104 else {
2105 errMsg = toast.show(options, 'toast');
2106 }
2107 return handle.success({ errMsg });
2108};
2109const hideToast = ({ noConflict = false, success, fail, complete } = {}) => {
2110 const handle = new MethodHandler({ name: 'hideToast', success, fail, complete });
2111 if (!toast.el)
2112 return handle.success();
2113 toast.hide(0, noConflict ? 'toast' : '');
2114 return handle.success();
2115};
2116const showLoading = (options = { title: '' }) => {
2117 init(document);
2118 options = Object.assign({
2119 title: '',
2120 mask: false
2121 }, options);
2122 const { success, fail, complete } = options;
2123 const handle = new MethodHandler({ name: 'showLoading', success, fail, complete });
2124 const config = {
2125 icon: 'loading',
2126 image: '',
2127 duration: -1
2128 };
2129 options = Object.assign({}, options, config);
2130 if (typeof options.title !== 'string') {
2131 return handle.fail({
2132 errMsg: getParameterError({
2133 para: 'title',
2134 correct: 'String',
2135 wrong: options.title
2136 })
2137 });
2138 }
2139 options.mask = !!options.mask;
2140 let errMsg = '';
2141 if (!toast.el) {
2142 errMsg = toast.create(options, 'loading');
2143 }
2144 else {
2145 errMsg = toast.show(options, 'loading');
2146 }
2147 return handle.success({ errMsg });
2148};
2149const hideLoading = ({ noConflict = false, success, fail, complete } = {}) => {
2150 const handle = new MethodHandler({ name: 'hideLoading', success, fail, complete });
2151 if (!toast.el)
2152 return handle.success();
2153 toast.hide(0, noConflict ? 'loading' : '');
2154 return handle.success();
2155};
2156const showModal = (options = {}) => __awaiter(void 0, void 0, void 0, function* () {
2157 init(document);
2158 options = Object.assign({
2159 title: '',
2160 content: '',
2161 showCancel: true,
2162 cancelText: '取消',
2163 cancelColor: '#000000',
2164 confirmText: '确定',
2165 confirmColor: '#3CC51F'
2166 }, options);
2167 const { success, fail, complete } = options;
2168 const handle = new MethodHandler({ name: 'showModal', success, fail, complete });
2169 if (typeof options.title !== 'string') {
2170 return handle.fail({
2171 errMsg: getParameterError({
2172 para: 'title',
2173 correct: 'String',
2174 wrong: options.title
2175 })
2176 });
2177 }
2178 if (typeof options.content !== 'string') {
2179 return handle.fail({
2180 errMsg: getParameterError({
2181 para: 'content',
2182 correct: 'String',
2183 wrong: options.content
2184 })
2185 });
2186 }
2187 if (typeof options.cancelText !== 'string') {
2188 return handle.fail({
2189 errMsg: getParameterError({
2190 para: 'cancelText',
2191 correct: 'String',
2192 wrong: options.cancelText
2193 })
2194 });
2195 }
2196 if (options.cancelText.replace(/[\u0391-\uFFE5]/g, 'aa').length > 8) {
2197 return handle.fail({
2198 errMsg: 'cancelText length should not larger then 4 Chinese characters'
2199 });
2200 }
2201 if (typeof options.confirmText !== 'string') {
2202 return handle.fail({
2203 errMsg: getParameterError({
2204 para: 'confirmText',
2205 correct: 'String',
2206 wrong: options.confirmText
2207 })
2208 });
2209 }
2210 if (options.confirmText.replace(/[\u0391-\uFFE5]/g, 'aa').length > 8) {
2211 return handle.fail({
2212 errMsg: 'confirmText length should not larger then 4 Chinese characters'
2213 });
2214 }
2215 if (typeof options.cancelColor !== 'string') {
2216 return handle.fail({
2217 errMsg: getParameterError({
2218 para: 'cancelColor',
2219 correct: 'String',
2220 wrong: options.cancelColor
2221 })
2222 });
2223 }
2224 if (typeof options.confirmColor !== 'string') {
2225 return handle.fail({
2226 errMsg: getParameterError({
2227 para: 'confirmColor',
2228 correct: 'String',
2229 wrong: options.confirmColor
2230 })
2231 });
2232 }
2233 options.showCancel = !!options.showCancel;
2234 let result = '';
2235 if (!modal.el) {
2236 result = yield modal.create(options);
2237 }
2238 else {
2239 result = yield modal.show(options);
2240 }
2241 const res = { cancel: !1, confirm: !1 };
2242 res[result] = !0;
2243 return handle.success(res);
2244});
2245function hideModal() {
2246 if (!modal.el)
2247 return;
2248 modal.hide();
2249}
2250const showActionSheet = (options = { itemList: [] }, methodName = 'showActionSheet') => __awaiter(void 0, void 0, void 0, function* () {
2251 init(document);
2252 options = Object.assign({
2253 itemColor: '#000000',
2254 itemList: []
2255 }, options);
2256 const { success, fail, complete } = options;
2257 const handle = new MethodHandler({ name: methodName, success, fail, complete });
2258 // list item String
2259 if (!Array.isArray(options.itemList)) {
2260 return handle.fail({
2261 errMsg: getParameterError({
2262 para: 'itemList',
2263 correct: 'Array',
2264 wrong: options.itemList
2265 })
2266 });
2267 }
2268 if (options.itemList.length < 1) {
2269 return handle.fail({ errMsg: 'parameter error: parameter.itemList should have at least 1 item' });
2270 }
2271 if (options.itemList.length > 6) {
2272 return handle.fail({ errMsg: 'parameter error: parameter.itemList should not be large than 6' });
2273 }
2274 for (let i = 0; i < options.itemList.length; i++) {
2275 if (typeof options.itemList[i] !== 'string') {
2276 return handle.fail({
2277 errMsg: getParameterError({
2278 para: `itemList[${i}]`,
2279 correct: 'String',
2280 wrong: options.itemList[i]
2281 })
2282 });
2283 }
2284 }
2285 if (typeof options.itemColor !== 'string') {
2286 return handle.fail({
2287 errMsg: getParameterError({
2288 para: 'itemColor',
2289 correct: 'String',
2290 wrong: options.itemColor
2291 })
2292 });
2293 }
2294 let result = '';
2295 if (!actionSheet.el) {
2296 result = yield actionSheet.create(options);
2297 }
2298 else {
2299 result = yield actionSheet.show(options);
2300 }
2301 if (typeof result === 'string') {
2302 return handle.fail(({ errMsg: result }));
2303 }
2304 else {
2305 return handle.success(({ tapIndex: result }));
2306 }
2307});
2308Taro.eventCenter.on('__afterTaroRouterChange', () => {
2309 var _a, _b;
2310 if (toast.currentPath && toast.currentPath !== ((_a = Current$1.page) === null || _a === void 0 ? void 0 : _a.path)) {
2311 hideToast();
2312 hideLoading();
2313 }
2314 if (modal.currentPath && modal.currentPath !== ((_b = Current$1.page) === null || _b === void 0 ? void 0 : _b.path)) {
2315 hideModal();
2316 }
2317});
2318const enableAlertBeforeUnload = /* @__PURE__ */ temporarilyNotSupport('enableAlertBeforeUnload');
2319const disableAlertBeforeUnload = /* @__PURE__ */ temporarilyNotSupport('disableAlertBeforeUnload');
2320
2321/**
2322 * 剪贴板部分的api参考了Chameleon项目的实现:
2323 *
2324 * setClipboardData: https://github.com/chameleon-team/chameleon-api/tree/master/src/interfaces/setClipBoardData
2325 * getClipboardData: https://github.com/chameleon-team/chameleon-api/tree/master/src/interfaces/getClipBoardData
2326 */
2327const CLIPBOARD_STORAGE_NAME = 'taro_clipboard';
2328document.addEventListener('copy', () => {
2329 var _a;
2330 setStorage({
2331 key: CLIPBOARD_STORAGE_NAME,
2332 data: (_a = window.getSelection()) === null || _a === void 0 ? void 0 : _a.toString()
2333 }).catch(e => {
2334 console.error(e);
2335 });
2336});
2337/**
2338 * 设置系统剪贴板的内容
2339 */
2340const setClipboardData = ({ data, success, fail, complete }) => __awaiter(void 0, void 0, void 0, function* () {
2341 const handle = new MethodHandler({ name: 'setClipboardData', success, fail, complete });
2342 try {
2343 setStorageSync(CLIPBOARD_STORAGE_NAME, data);
2344 /**
2345 * 已于 iPhone 6s Plus iOS 13.1.3 上的 Safari 测试通过
2346 * iOS < 10 的系统可能无法使用编程方式访问剪贴板,参考:
2347 * https://stackoverflow.com/questions/34045777/copy-to-clipboard-using-javascript-in-ios/34046084
2348 */
2349 if (isFunction(document.execCommand)) {
2350 const textarea = document.createElement('textarea');
2351 textarea.readOnly = true;
2352 textarea.value = data;
2353 textarea.style.position = 'absolute';
2354 textarea.style.width = '100px';
2355 textarea.style.left = '-10000px';
2356 document.body.appendChild(textarea);
2357 textarea.select();
2358 textarea.setSelectionRange(0, textarea.value.length);
2359 document.execCommand('copy');
2360 document.body.removeChild(textarea);
2361 }
2362 else {
2363 throw new Error('Unsupported Function: \'document.execCommand\'.');
2364 }
2365 showToast({
2366 title: '内容已复制',
2367 icon: 'none',
2368 duration: 1500
2369 });
2370 return handle.success();
2371 }
2372 catch (e) {
2373 return handle.fail({ errMsg: e.message });
2374 }
2375});
2376/**
2377 * 获取系统剪贴板的内容
2378 */
2379const getClipboardData = ({ success, fail, complete } = {}) => __awaiter(void 0, void 0, void 0, function* () {
2380 const handle = new MethodHandler({ name: 'getClipboardData', success, fail, complete });
2381 try {
2382 const data = getStorageSync(CLIPBOARD_STORAGE_NAME);
2383 return handle.success({ data });
2384 }
2385 catch (e) {
2386 return handle.fail({ errMsg: e.message });
2387 }
2388});
2389
2390const callbackManager$2 = new CallbackManager();
2391let compassListener;
2392/**
2393 * Note: 按系统类型获取对应绝对 orientation 事件名,因为安卓系统中直接监听 deviceorientation 事件得到的不是绝对 orientation
2394 */
2395const deviceorientationEventName = ['absolutedeviceorientation', 'deviceorientationabsolute', 'deviceorientation'].find(item => {
2396 if ('on' + item in window) {
2397 return item;
2398 }
2399}) || '';
2400/**
2401 * 停止监听罗盘数据
2402 */
2403const stopCompass = ({ success, fail, complete } = {}) => {
2404 const handle = new MethodHandler({ name: 'stopCompass', success, fail, complete });
2405 try {
2406 window.removeEventListener(deviceorientationEventName, compassListener, true);
2407 return handle.success();
2408 }
2409 catch (e) {
2410 return handle.fail({ errMsg: e.message });
2411 }
2412};
2413let CompassChangeTrigger = false;
2414/**
2415 * 开始监听罗盘数据
2416 */
2417const startCompass = ({ success, fail, complete } = {}) => {
2418 const handle = new MethodHandler({ name: 'startCompass', success, fail, complete });
2419 try {
2420 if (deviceorientationEventName !== '') {
2421 if (compassListener) {
2422 stopCompass();
2423 }
2424 compassListener = throttle((evt) => {
2425 const isAndroid = getDeviceInfo().system === 'AndroidOS';
2426 if (isAndroid && !evt.absolute && !CompassChangeTrigger) {
2427 CompassChangeTrigger = true;
2428 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 .');
2429 }
2430 const alpha = evt.alpha || 0;
2431 /**
2432 * 由于平台差异,accuracy 在 iOS/Android 的值不同。
2433 * - iOS:accuracy 是一个 number 类型的值,表示相对于磁北极的偏差。0 表示设备指向磁北,90 表示指向东,180 表示指向南,依此类推。
2434 * - Android:accuracy 是一个 string 类型的枚举值。
2435 */
2436 const accuracy = isAndroid ? evt.absolute ? 'high' : 'medium' : alpha;
2437 callbackManager$2.trigger({
2438 direction: 360 - alpha,
2439 accuracy: accuracy
2440 });
2441 }, 5000);
2442 window.addEventListener(deviceorientationEventName, compassListener, true);
2443 }
2444 else {
2445 throw new Error('compass is not supported');
2446 }
2447 return handle.success();
2448 }
2449 catch (e) {
2450 return handle.fail({ errMsg: e.message });
2451 }
2452};
2453/**
2454 * 监听罗盘数据变化事件。频率:5 次/秒,接口调用后会自动开始监听,可使用 wx.stopCompass 停止监听。
2455 */
2456const onCompassChange = callback => {
2457 callbackManager$2.add(callback);
2458};
2459/**
2460 * 取消监听罗盘数据变化事件,参数为空,则取消所有的事件监听。
2461 */
2462const offCompassChange = callback => {
2463 callbackManager$2.remove(callback);
2464};
2465
2466// 联系人
2467const chooseContact = /* @__PURE__ */ temporarilyNotSupport('chooseContact');
2468const addPhoneContact = /* @__PURE__ */ temporarilyNotSupport('addPhoneContact');
2469
2470// 加密
2471const getRandomValues = /* @__PURE__ */ temporarilyNotSupport('getRandomValues');
2472
2473// 陀螺仪
2474const stopGyroscope = /* @__PURE__ */ temporarilyNotSupport('stopGyroscope');
2475const startGyroscope = /* @__PURE__ */ temporarilyNotSupport('startGyroscope');
2476const onGyroscopeChange = /* @__PURE__ */ temporarilyNotSupport('onGyroscopeChange');
2477const offGyroscopeChange = /* @__PURE__ */ temporarilyNotSupport('offGyroscopeChange');
2478
2479// 蓝牙-信标(Beacon)
2480const stopBeaconDiscovery = /* @__PURE__ */ temporarilyNotSupport('stopBeaconDiscovery');
2481const startBeaconDiscovery = /* @__PURE__ */ temporarilyNotSupport('startBeaconDiscovery');
2482const onBeaconUpdate = /* @__PURE__ */ temporarilyNotSupport('onBeaconUpdate');
2483const onBeaconServiceChange = /* @__PURE__ */ temporarilyNotSupport('onBeaconServiceChange');
2484const offBeaconUpdate = /* @__PURE__ */ temporarilyNotSupport('offBeaconUpdate');
2485const offBeaconServiceChange = /* @__PURE__ */ temporarilyNotSupport('offBeaconServiceChange');
2486const getBeacons = /* @__PURE__ */ temporarilyNotSupport('getBeacons');
2487
2488// 键盘
2489const onKeyboardHeightChange = /* @__PURE__ */ temporarilyNotSupport('onKeyboardHeightChange');
2490const offKeyboardHeightChange = /* @__PURE__ */ temporarilyNotSupport('offKeyboardHeightChange');
2491const hideKeyboard = /* @__PURE__ */ temporarilyNotSupport('hideKeyboard');
2492const getSelectedTextRange = /* @__PURE__ */ temporarilyNotSupport('getSelectedTextRange');
2493
2494// 内存
2495const onMemoryWarning = /* @__PURE__ */ temporarilyNotSupport('onMemoryWarning');
2496const offMemoryWarning = /* @__PURE__ */ temporarilyNotSupport('offMemoryWarning');
2497
2498const callbackManager$1 = new CallbackManager();
2499let deviceMotionListener;
2500const INTERVAL_MAP = {
2501 game: {
2502 interval: 20,
2503 frequency: 50
2504 },
2505 ui: {
2506 interval: 60,
2507 frequency: 16.67
2508 },
2509 normal: {
2510 interval: 200,
2511 frequency: 5
2512 }
2513};
2514/**
2515 * 停止监听设备方向的变化。
2516 */
2517const stopDeviceMotionListening = ({ success, fail, complete } = {}) => {
2518 const handle = new MethodHandler({ name: 'stopDeviceMotionListening', success, fail, complete });
2519 try {
2520 window.removeEventListener('deviceorientation', deviceMotionListener, true);
2521 return handle.success();
2522 }
2523 catch (e) {
2524 return handle.fail({ errMsg: e.message });
2525 }
2526};
2527/**
2528 * 开始监听设备方向的变化。
2529 */
2530const startDeviceMotionListening = ({ interval = 'normal', success, fail, complete } = {}) => {
2531 const handle = new MethodHandler({ name: 'startDeviceMotionListening', success, fail, complete });
2532 try {
2533 const intervalObj = INTERVAL_MAP[interval];
2534 if (window.DeviceOrientationEvent) {
2535 if (deviceMotionListener) {
2536 stopDeviceMotionListening();
2537 }
2538 deviceMotionListener = throttle((evt) => {
2539 callbackManager$1.trigger({
2540 alpha: evt.alpha,
2541 beta: evt.beta,
2542 gamma: evt.gamma
2543 });
2544 }, intervalObj.interval);
2545 window.addEventListener('deviceorientation', deviceMotionListener, true);
2546 }
2547 else {
2548 throw new Error('deviceMotion is not supported');
2549 }
2550 return handle.success();
2551 }
2552 catch (e) {
2553 return handle.fail({ errMsg: e.message });
2554 }
2555};
2556/**
2557 * 监听设备方向变化事件。
2558 */
2559const onDeviceMotionChange = callback => {
2560 callbackManager$1.add(callback);
2561};
2562/**
2563 * 取消监听设备方向变化事件,参数为空,则取消所有的事件监听。
2564 */
2565const offDeviceMotionChange = callback => {
2566 callbackManager$1.remove(callback);
2567};
2568
2569function getConnection() {
2570 // @ts-ignore
2571 return navigator.connection || navigator.mozConnection || navigator.webkitConnection || navigator.msConnection;
2572}
2573const getNetworkType = (options = {}) => {
2574 const connection = getConnection();
2575 const { success, fail, complete } = options;
2576 const handle = new MethodHandler({ name: 'getNetworkType', success, fail, complete });
2577 let networkType = 'unknown';
2578 // 浏览器不支持获取网络状态
2579 if (!connection) {
2580 return handle.success({ networkType });
2581 }
2582 // Supports only the navigator.connection.type value which doesn't match the latest spec.
2583 // https://www.davidbcalhoun.com/2010/using-navigator-connection-android/
2584 if (!isNaN(Number(connection.type))) {
2585 switch (connection.type) {
2586 // @ts-ignore
2587 case connection.WIFI:
2588 networkType = 'wifi';
2589 break;
2590 // @ts-ignore
2591 case connection.CELL_3G:
2592 networkType = '3g';
2593 break;
2594 // @ts-ignore
2595 case connection.CELL_2G:
2596 networkType = '2g';
2597 break;
2598 default:
2599 // ETHERNET, UNKNOWN
2600 networkType = 'unknown';
2601 }
2602 }
2603 else if (connection.type) {
2604 // @ts-ignore
2605 networkType = connection.type; // Only supports the type value.
2606 // @ts-ignore
2607 }
2608 else if (connection.effectiveType) {
2609 // @ts-ignore
2610 networkType = connection.effectiveType;
2611 }
2612 return handle.success({ networkType });
2613};
2614const networkStatusManager = new CallbackManager();
2615const networkStatusListener = () => __awaiter(void 0, void 0, void 0, function* () {
2616 const { networkType } = yield getNetworkType();
2617 const isConnected = networkType !== 'none';
2618 const obj = { isConnected, networkType };
2619 networkStatusManager.trigger(obj);
2620});
2621/**
2622 * 在最近的八次网络请求中, 出现下列三个现象之一则判定弱网。
2623 * - 出现三次以上连接超时
2624 * - 出现三次 rtt 超过 400
2625 * - 出现三次以上的丢包
2626 * > 弱网事件通知规则是: 弱网状态变化时立即通知, 状态不变时 30s 内最多通知一次。
2627 */
2628const onNetworkWeakChange = /* @__PURE__ */ temporarilyNotSupport('onNetworkWeakChange');
2629const onNetworkStatusChange = callback => {
2630 networkStatusManager.add(callback);
2631 const connection = getConnection();
2632 if (connection && networkStatusManager.count() === 1) {
2633 connection.addEventListener('change', networkStatusListener);
2634 }
2635};
2636const offNetworkWeakChange = /* @__PURE__ */ temporarilyNotSupport('offNetworkWeakChange');
2637const offNetworkStatusChange = callback => {
2638 networkStatusManager.remove(callback);
2639 const connection = getConnection();
2640 if (connection && networkStatusManager.count() === 0) {
2641 connection.removeEventListener('change', networkStatusListener);
2642 }
2643};
2644const getLocalIPAddress = /* @__PURE__ */ temporarilyNotSupport('getLocalIPAddress');
2645
2646// NFC
2647const stopHCE = /* @__PURE__ */ temporarilyNotSupport('stopHCE');
2648const startHCE = /* @__PURE__ */ temporarilyNotSupport('startHCE');
2649const sendHCEMessage = /* @__PURE__ */ temporarilyNotSupport('sendHCEMessage');
2650const onHCEMessage = /* @__PURE__ */ temporarilyNotSupport('onHCEMessage');
2651const offHCEMessage = /* @__PURE__ */ temporarilyNotSupport('offHCEMessage');
2652const getNFCAdapter = /* @__PURE__ */ temporarilyNotSupport('getNFCAdapter');
2653const getHCEState = /* @__PURE__ */ temporarilyNotSupport('getHCEState');
2654
2655const makePhoneCall = (options) => {
2656 // options must be an Object
2657 const isObject = shouldBeObject(options);
2658 if (!isObject.flag) {
2659 const res = { errMsg: `makePhoneCall:fail ${isObject.msg}` };
2660 console.error(res.errMsg);
2661 return Promise.reject(res);
2662 }
2663 const { phoneNumber, success, fail, complete } = options;
2664 const handle = new MethodHandler({ name: 'makePhoneCall', success, fail, complete });
2665 if (typeof phoneNumber !== 'string') {
2666 return handle.fail({
2667 errMsg: getParameterError({
2668 para: 'phoneNumber',
2669 correct: 'String',
2670 wrong: phoneNumber
2671 })
2672 });
2673 }
2674 window.location.href = `tel:${phoneNumber}`;
2675 return handle.success();
2676};
2677
2678// 扫码
2679const scanCode = /* @__PURE__ */ processOpenApi({
2680 name: 'scanQRCode',
2681 defaultOptions: { needResult: 1 },
2682 formatResult: res => ({
2683 errMsg: res.errMsg === 'scanQRCode:ok' ? 'scanCode:ok' : res.errMsg,
2684 result: res.resultStr
2685 })
2686});
2687
2688// 屏幕
2689const setVisualEffectOnCapture = /* @__PURE__ */ temporarilyNotSupport('setVisualEffectOnCapture');
2690const setScreenBrightness = /* @__PURE__ */ temporarilyNotSupport('setScreenBrightness');
2691const setKeepScreenOn = /* @__PURE__ */ temporarilyNotSupport('setKeepScreenOn');
2692const onUserCaptureScreen = /* @__PURE__ */ temporarilyNotSupport('onUserCaptureScreen');
2693const offUserCaptureScreen = /* @__PURE__ */ temporarilyNotSupport('offUserCaptureScreen');
2694const getScreenBrightness = /* @__PURE__ */ temporarilyNotSupport('getScreenBrightness');
2695const onScreenRecordingStateChanged = /* @__PURE__ */ temporarilyNotSupport('onScreenRecordingStateChanged');
2696const offScreenRecordingStateChanged = /* @__PURE__ */ temporarilyNotSupport('offScreenRecordingStateChanged');
2697const getScreenRecordingState = /* @__PURE__ */ temporarilyNotSupport('getScreenRecordingState');
2698
2699// 短信
2700const sendSms = /* @__PURE__ */ temporarilyNotSupport('sendSms');
2701
2702const vibrator = function vibrator(mm) {
2703 try {
2704 return window.navigator.vibrate(mm);
2705 }
2706 catch (e) {
2707 console.warn('当前浏览器不支持 vibrate。');
2708 }
2709};
2710/**
2711 * 使手机发生较短时间的振动(15 ms)。仅在 iPhone 7 / 7 Plus 以上及 Android 机型生效
2712 */
2713const vibrateShort = ({ success, fail, complete } = {}) => {
2714 const handle = new MethodHandler({ name: 'vibrateShort', success, fail, complete });
2715 if (vibrator(15)) {
2716 return handle.success();
2717 }
2718 else {
2719 return handle.fail({ errMsg: 'style is not support' });
2720 }
2721};
2722/**
2723 * 使手机发生较长时间的振动(400 ms)
2724 */
2725const vibrateLong = ({ success, fail, complete } = {}) => {
2726 const handle = new MethodHandler({ name: 'vibrateLong', success, fail, complete });
2727 if (vibrator(400)) {
2728 return handle.success();
2729 }
2730 else {
2731 return handle.fail({ errMsg: 'style is not support' });
2732 }
2733};
2734
2735// Wi-Fi
2736const stopWifi = /* @__PURE__ */ temporarilyNotSupport('stopWifi');
2737const startWifi = /* @__PURE__ */ temporarilyNotSupport('startWifi');
2738const setWifiList = /* @__PURE__ */ temporarilyNotSupport('setWifiList');
2739const onWifiConnectedWithPartialInfo = /* @__PURE__ */ temporarilyNotSupport('onWifiConnectedWithPartialInfo');
2740const onWifiConnected = /* @__PURE__ */ temporarilyNotSupport('onWifiConnected');
2741const onGetWifiList = /* @__PURE__ */ temporarilyNotSupport('onGetWifiList');
2742const offWifiConnectedWithPartialInfo = /* @__PURE__ */ temporarilyNotSupport('offWifiConnectedWithPartialInfo');
2743const offWifiConnected = /* @__PURE__ */ temporarilyNotSupport('offWifiConnected');
2744const offGetWifiList = /* @__PURE__ */ temporarilyNotSupport('offGetWifiList');
2745const getWifiList = /* @__PURE__ */ temporarilyNotSupport('getWifiList');
2746const getConnectedWifi = /* @__PURE__ */ temporarilyNotSupport('getConnectedWifi');
2747const connectWifi = /* @__PURE__ */ temporarilyNotSupport('connectWifi');
2748
2749// 第三方平台
2750const getExtConfigSync = /* @__PURE__ */ temporarilyNotSupport('getExtConfigSync');
2751const getExtConfig = /* @__PURE__ */ temporarilyNotSupport('getExtConfig');
2752
2753// 文件
2754const saveFileToDisk = /* @__PURE__ */ temporarilyNotSupport('saveFileToDisk');
2755const saveFile = /* @__PURE__ */ temporarilyNotSupport('saveFile');
2756const removeSavedFile = /* @__PURE__ */ temporarilyNotSupport('removeSavedFile');
2757const openDocument = /* @__PURE__ */ temporarilyNotSupport('openDocument');
2758const getSavedFileList = /* @__PURE__ */ temporarilyNotSupport('getSavedFileList');
2759const getSavedFileInfo = /* @__PURE__ */ temporarilyNotSupport('getSavedFileInfo');
2760const getFileSystemManager = /* @__PURE__ */ temporarilyNotSupport('getFileSystemManager');
2761const getFileInfo = /* @__PURE__ */ temporarilyNotSupport('getFileInfo');
2762
2763const getApp = function () {
2764 return Taro.getCurrentInstance().app;
2765};
2766// 自定义组件
2767const getCurrentInstance = Taro.getCurrentInstance;
2768
2769const isGeolocationSupported = () => !!navigator.geolocation;
2770
2771const getLocationByW3CApi = (options) => {
2772 var _a;
2773 // 断言 options 必须是 Object
2774 const isObject = shouldBeObject(options);
2775 if (!isObject.flag) {
2776 const res = { errMsg: `getLocation:fail ${isObject.msg}` };
2777 console.error(res.errMsg);
2778 return Promise.reject(res);
2779 }
2780 // 解构回调函数
2781 const { success, fail, complete } = options;
2782 const handle = new MethodHandler({ name: 'getLocation', success, fail, complete });
2783 // const defaultMaximumAge = 5 * 1000
2784 const positionOptions = {
2785 enableHighAccuracy: options.isHighAccuracy || (options.altitude != null),
2786 // maximumAge: defaultMaximumAge, // 允许取多久以内的缓存位置
2787 timeout: options.highAccuracyExpireTime // 高精度定位超时时间
2788 };
2789 // Web端API实现暂时仅支持GPS坐标系
2790 if (((_a = options.type) === null || _a === void 0 ? void 0 : _a.toUpperCase()) !== 'WGS84') {
2791 return handle.fail({
2792 errMsg: 'This coordinate system type is not temporarily supported'
2793 });
2794 }
2795 // 判断当前浏览器是否支持位置API
2796 if (!isGeolocationSupported()) {
2797 return handle.fail({
2798 errMsg: 'The current browser does not support this feature'
2799 });
2800 }
2801 // 开始获取位置
2802 return new Promise((resolve, reject) => {
2803 navigator.geolocation.getCurrentPosition((position) => {
2804 const result = {
2805 /** 位置的精确度 */
2806 accuracy: position.coords.accuracy,
2807 /** 高度,单位 m */
2808 altitude: position.coords.altitude,
2809 /** 水平精度,单位 m */
2810 horizontalAccuracy: position.coords.accuracy,
2811 /** 纬度,范围为 -90~90,负数表示南纬 */
2812 latitude: position.coords.latitude,
2813 /** 经度,范围为 -180~180,负数表示西经 */
2814 longitude: position.coords.longitude,
2815 /** 速度,单位 m/s */
2816 speed: position.coords.speed,
2817 /** 垂直精度,单位 m(Android 无法获取,返回 0) */
2818 verticalAccuracy: position.coords.altitudeAccuracy || 0,
2819 /** 调用结果,自动补充 */
2820 errMsg: ''
2821 };
2822 handle.success(result, { resolve, reject });
2823 }, (error) => {
2824 handle.fail({ errMsg: error.message }, { resolve, reject });
2825 }, positionOptions);
2826 });
2827};
2828const getLocation = /* @__PURE__ */ processOpenApi({
2829 name: 'getLocation',
2830 standardMethod: getLocationByW3CApi
2831});
2832
2833function styleInject(css, ref) {
2834 if ( ref === void 0 ) ref = {};
2835 var insertAt = ref.insertAt;
2836
2837 if (!css || typeof document === 'undefined') { return; }
2838
2839 var head = document.head || document.getElementsByTagName('head')[0];
2840 var style = document.createElement('style');
2841 style.type = 'text/css';
2842
2843 if (insertAt === 'top') {
2844 if (head.firstChild) {
2845 head.insertBefore(style, head.firstChild);
2846 } else {
2847 head.appendChild(style);
2848 }
2849 } else {
2850 head.appendChild(style);
2851 }
2852
2853 if (style.styleSheet) {
2854 style.styleSheet.cssText = css;
2855 } else {
2856 style.appendChild(document.createTextNode(css));
2857 }
2858}
2859
2860var 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}";
2861var 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}";
2862styleInject(css_248z,{"insertAt":"top"});
2863
2864let container = null;
2865function createLocationChooser(handler, key = LOCATION_APIKEY, mapOpt = {}) {
2866 var _a, _b, _c;
2867 const { latitude, longitude } = mapOpt, opts = __rest(mapOpt, ["latitude", "longitude"]);
2868 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);
2869 if (!container) {
2870 const html = `
2871<div class='taro_choose_location'>
2872 <div class='taro_choose_location_bar'>
2873 <div class='taro_choose_location_back'></div>
2874 <p class='taro_choose_location_title'>位置</p>
2875 <button class='taro_choose_location_submit'>完成</button>
2876 </div>
2877 <iframe class='taro_choose_location_frame' frameborder='0' src="https://apis.map.qq.com/tools/locpicker?${stringify(query, { arrayFormat: 'comma', skipNull: true })}" />
2878</div>
2879`;
2880 container = document.createElement('div');
2881 container.innerHTML = html;
2882 }
2883 const main = container.querySelector('.taro_choose_location');
2884 function show() {
2885 setTimeout(() => {
2886 main.style.top = '0';
2887 });
2888 }
2889 function hide() {
2890 main.style.top = '100%';
2891 }
2892 function back() {
2893 hide();
2894 handler({ errMsg: 'cancel' });
2895 }
2896 function submit() {
2897 hide();
2898 handler();
2899 }
2900 function remove() {
2901 container === null || container === void 0 ? void 0 : container.remove();
2902 container = null;
2903 window.removeEventListener('popstate', back);
2904 }
2905 (_b = container.querySelector('.taro_choose_location_back')) === null || _b === void 0 ? void 0 : _b.addEventListener('click', back);
2906 (_c = container.querySelector('.taro_choose_location_submit')) === null || _c === void 0 ? void 0 : _c.addEventListener('click', submit);
2907 window.addEventListener('popstate', back);
2908 return {
2909 show,
2910 remove,
2911 container,
2912 };
2913}
2914/**
2915 * 打开地图选择位置。
2916 */
2917const chooseLocation = ({ success, fail, complete, mapOpts } = {}) => {
2918 const handle = new MethodHandler({ name: 'chooseLocation', success, fail, complete });
2919 return new Promise((resolve, reject) => {
2920 const chooseLocation = {};
2921 if (typeof LOCATION_APIKEY === 'undefined') {
2922 console.warn('chooseLocation api 依赖腾讯地图定位api,需要在 defineConstants 中配置 LOCATION_APIKEY');
2923 return handle.fail({
2924 errMsg: 'LOCATION_APIKEY needed'
2925 }, { resolve, reject });
2926 }
2927 const key = LOCATION_APIKEY;
2928 const onMessage = event => {
2929 // 接收位置信息,用户选择确认位置点后选点组件会触发该事件,回传用户的位置信息
2930 const loc = event.data;
2931 // 防止其他应用也会向该页面 post 信息,需判断 module 是否为'locationPicker'
2932 if (!loc || loc.module !== 'locationPicker')
2933 return;
2934 chooseLocation.name = loc.poiname;
2935 chooseLocation.address = loc.poiaddress;
2936 chooseLocation.latitude = loc.latlng.lat;
2937 chooseLocation.longitude = loc.latlng.lng;
2938 };
2939 const chooser = createLocationChooser(res => {
2940 window.removeEventListener('message', onMessage, false);
2941 setTimeout(() => {
2942 chooser.remove();
2943 }, 300);
2944 if (res) {
2945 return handle.fail(res, { resolve, reject });
2946 }
2947 else {
2948 if (chooseLocation.latitude && chooseLocation.longitude) {
2949 return handle.success(chooseLocation, { resolve, reject });
2950 }
2951 else {
2952 return handle.fail({}, { resolve, reject });
2953 }
2954 }
2955 }, key, mapOpts);
2956 document.body.appendChild(chooser.container);
2957 window.addEventListener('message', onMessage, false);
2958 chooser.show();
2959 });
2960};
2961
2962const _successCbManager = new CallbackManager();
2963const _errorCbManager = new CallbackManager();
2964let _watchID = -1;
2965function onLocationChange(callback) {
2966 _successCbManager.add(callback);
2967}
2968function offLocationChange(callback) {
2969 if (callback && typeof callback === 'function') {
2970 _successCbManager.remove(callback);
2971 }
2972 else if (callback === undefined) {
2973 _successCbManager.clear();
2974 }
2975 else {
2976 console.warn('offLocationChange failed');
2977 }
2978}
2979function onLocationChangeError(callback) {
2980 _errorCbManager.add(callback);
2981}
2982function offLocationChangeError(callback) {
2983 if (callback && typeof callback === 'function') {
2984 _errorCbManager.remove(callback);
2985 }
2986 else if (callback === undefined) {
2987 _errorCbManager.clear();
2988 }
2989 else {
2990 console.warn('offLocationChangeError failed');
2991 }
2992}
2993/**
2994 * 开始监听位置信息
2995 * @param opts
2996 * @returns
2997 */
2998function startLocationUpdateByW3CApi(opts) {
2999 // 断言 options 必须是 Object
3000 const isObject = shouldBeObject(opts);
3001 if (!isObject.flag) {
3002 const res = { errMsg: `startLocationUpdate:fail ${isObject.msg}` };
3003 console.error(res.errMsg);
3004 return Promise.reject(res);
3005 }
3006 const { success, fail, complete } = opts;
3007 const handle = new MethodHandler({ name: 'startLocationUpdate', success, fail, complete });
3008 // 判断当前浏览器是否支持位置API
3009 if (!isGeolocationSupported()) {
3010 return handle.fail({
3011 errMsg: 'The current browser does not support this feature'
3012 });
3013 }
3014 try {
3015 if (_watchID > -1) {
3016 console.error('startLocationUpdate:fail');
3017 return handle.fail();
3018 }
3019 else {
3020 _watchID = navigator.geolocation.watchPosition(({ coords }) => {
3021 const { latitude, longitude, altitude, accuracy, speed } = coords;
3022 _successCbManager.trigger({
3023 accuracy,
3024 altitude,
3025 horizontalAccuracy: 0,
3026 verticalAccuracy: 0,
3027 latitude,
3028 longitude,
3029 speed,
3030 });
3031 }, err => {
3032 _errorCbManager.trigger({
3033 errMsg: 'Watch Position error',
3034 err
3035 });
3036 }, {
3037 timeout: 10,
3038 maximumAge: 0,
3039 enableHighAccuracy: true,
3040 });
3041 return handle.success();
3042 }
3043 }
3044 catch (error) {
3045 return handle.fail();
3046 }
3047}
3048/**
3049 * 停止监听位置信息
3050 * @param opts
3051 * @returns
3052 */
3053function stopLocationUpdateByW3CApi(opts) {
3054 const isObject = shouldBeObject(opts);
3055 if (!isObject.flag) {
3056 const res = { errMsg: `stopLocationUpdate:fail ${isObject.msg}` };
3057 console.error(res.errMsg);
3058 return Promise.reject(res);
3059 }
3060 const { success, fail, complete } = opts;
3061 const handle = new MethodHandler({ name: 'stopLocationUpdate', success, fail, complete });
3062 // 判断当前浏览器是否支持位置API
3063 if (!isGeolocationSupported()) {
3064 return handle.fail({
3065 errMsg: 'The current browser does not support this feature'
3066 });
3067 }
3068 try {
3069 navigator.geolocation.clearWatch(_watchID);
3070 _watchID = -1;
3071 return handle.success();
3072 }
3073 catch (error) {
3074 return handle.fail();
3075 }
3076}
3077const stopLocationUpdate = /* @__PURE__ */ processOpenApi({
3078 name: 'stopLocationUpdate',
3079 standardMethod: stopLocationUpdateByW3CApi
3080});
3081const startLocationUpdate = /* @__PURE__ */ processOpenApi({
3082 name: 'startLocationUpdate',
3083 standardMethod: startLocationUpdateByW3CApi
3084});
3085
3086const startLocationUpdateBackground = /* @__PURE__ */ temporarilyNotSupport('startLocationUpdateBackground');
3087const openLocation = /* @__PURE__ */ processOpenApi({
3088 name: 'openLocation',
3089 defaultOptions: { scale: 18 }
3090});
3091const choosePoi = /* @__PURE__ */ temporarilyNotSupport('choosePoi');
3092const getFuzzyLocation = /* @__PURE__ */ temporarilyNotSupport('getFuzzyLocation');
3093
3094class InnerAudioContext {
3095 constructor() {
3096 this.__startTime = 0;
3097 this.__isFirstPlay = true;
3098 this.play = () => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.play(); };
3099 this.pause = () => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.pause(); };
3100 this.stop = () => {
3101 this.pause();
3102 this.seek(0);
3103 this.stopStack.trigger();
3104 };
3105 this.seek = (position) => {
3106 if (this.Instance) {
3107 this.Instance.currentTime = position;
3108 }
3109 };
3110 /**
3111 * @TODO destroy得并不干净
3112 */
3113 this.destroy = () => {
3114 this.stop();
3115 if (this.Instance) {
3116 this.Instance = undefined;
3117 }
3118 };
3119 this.onCanplay = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('canplay', callback); };
3120 this.onPlay = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('play', callback); };
3121 this.onPause = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('pause', callback); };
3122 this.onStop = (callback = () => { }) => this.stopStack.add(callback);
3123 this.onEnded = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('ended', callback); };
3124 this.onTimeUpdate = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('timeupdate', callback); };
3125 this.onError = (callback) => this.errorStack.add(callback);
3126 this.onWaiting = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('waiting', callback); };
3127 this.onSeeking = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('seeking', callback); };
3128 this.onSeeked = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('seeked', callback); };
3129 this.offCanplay = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('canplay', callback); };
3130 this.offPlay = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('play', callback); };
3131 this.offPause = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('pause', callback); };
3132 this.offStop = (callback = () => { }) => this.stopStack.remove(callback);
3133 this.offEnded = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('ended', callback); };
3134 this.offTimeUpdate = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('timeupdate', callback); };
3135 this.offError = (callback = () => { }) => this.errorStack.remove(callback);
3136 this.offWaiting = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('waiting', callback); };
3137 this.offSeeking = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('seeking', callback); };
3138 this.offSeeked = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('seeked', callback); };
3139 this.Instance = new Audio();
3140 this.errorStack = new CallbackManager();
3141 this.stopStack = new CallbackManager();
3142 this.Instance.onerror = this.errorStack.trigger;
3143 Taro.eventCenter.on('__taroRouterChange', () => { this.stop(); });
3144 this.onPlay(() => {
3145 if (this.__isFirstPlay) {
3146 this.__isFirstPlay = false;
3147 this.seek(this.startTime);
3148 }
3149 });
3150 }
3151 set autoplay(e) { this.setProperty('autoplay', e); }
3152 get autoplay() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.autoplay) || false; }
3153 get buffered() {
3154 const { currentTime = 0, buffered: timeRange } = this.Instance || {};
3155 if (timeRange) {
3156 for (let i = 0; i < timeRange.length; i++) {
3157 if (timeRange.start(i) <= currentTime && timeRange.end(i) >= currentTime) {
3158 return timeRange.end(i);
3159 }
3160 }
3161 }
3162 return 0;
3163 }
3164 get currentTime() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.currentTime) || 0; }
3165 set currentTime(e) { this.seek(e); }
3166 get duration() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.duration) || 0; }
3167 set loop(e) { this.setProperty('loop', e); }
3168 get loop() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.loop) || false; }
3169 get paused() { var _a, _b; return (_b = (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.paused) !== null && _b !== void 0 ? _b : true; }
3170 set src(e) { this.setProperty('src', e); }
3171 get src() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.src) || ''; }
3172 set volume(e) { this.setProperty('volume', e); }
3173 get volume() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.volume) || 0; }
3174 set playbackRate(e) { this.setProperty('playbackRate', e); }
3175 get playbackRate() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.playbackRate) || 0; }
3176 set obeyMuteSwitch(_e) { permanentlyNotSupport('InnerAudioContext.obeyMuteSwitch')(); }
3177 get obeyMuteSwitch() { return true; }
3178 set startTime(e) { this.__startTime = e; }
3179 get startTime() { return this.__startTime || 0; }
3180 set referrerPolicy(e) { var _a; (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.setAttribute('referrerpolicy', e); }
3181 get referrerPolicy() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.getAttribute('referrerpolicy')) || 'origin'; }
3182 setProperty(key, value) {
3183 if (this.Instance) {
3184 this.Instance[key] = value;
3185 }
3186 }
3187}
3188
3189// 音频
3190const stopVoice = /* @__PURE__ */ temporarilyNotSupport('stopVoice');
3191const setInnerAudioOption = /* @__PURE__ */ temporarilyNotSupport('setInnerAudioOption');
3192const playVoice = /* @__PURE__ */ temporarilyNotSupport('playVoice');
3193const pauseVoice = /* @__PURE__ */ temporarilyNotSupport('pauseVoice');
3194const getAvailableAudioSources = /* @__PURE__ */ temporarilyNotSupport('getAvailableAudioSources');
3195const createWebAudioContext = /* @__PURE__ */ temporarilyNotSupport('createWebAudioContext');
3196const createMediaAudioPlayer = /* @__PURE__ */ temporarilyNotSupport('createMediaAudioPlayer');
3197/**
3198 * 创建内部 audio 上下文 InnerAudioContext 对象。
3199 */
3200const createInnerAudioContext = () => new InnerAudioContext();
3201const createAudioContext = /* @__PURE__ */ temporarilyNotSupport('createAudioContext');
3202
3203class BackgroundAudioManager {
3204 constructor() {
3205 this.__startTime = 0;
3206 this.play = () => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.play(); };
3207 this.pause = () => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.pause(); };
3208 this.seek = (position) => {
3209 if (this.Instance) {
3210 this.Instance.currentTime = position;
3211 }
3212 };
3213 this.stop = () => {
3214 this.pause();
3215 this.seek(0);
3216 this.stopStack.trigger();
3217 };
3218 this.onCanplay = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('canplay', callback); };
3219 this.onWaiting = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('waiting', callback); };
3220 this.onError = (callback) => this.errorStack.add(callback);
3221 this.onPlay = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('play', callback); };
3222 this.onPause = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('pause', callback); };
3223 this.onSeeking = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('seeking', callback); };
3224 this.onSeeked = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('seeked', callback); };
3225 this.onEnded = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('ended', callback); };
3226 this.onStop = (callback = () => { }) => this.stopStack.add(callback);
3227 this.onTimeUpdate = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.addEventListener('timeupdate', callback); };
3228 this.onPrev = permanentlyNotSupport('BackgroundAudioManager.onPrev');
3229 this.onNext = permanentlyNotSupport('BackgroundAudioManager.onNext');
3230 this.offCanplay = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('canplay', callback); };
3231 this.offWaiting = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('waiting', callback); };
3232 this.offError = (callback = () => { }) => this.errorStack.remove(callback);
3233 this.offPlay = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('play', callback); };
3234 this.offPause = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('pause', callback); };
3235 this.offSeeking = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('seeking', callback); };
3236 this.offSeeked = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('seeked', callback); };
3237 this.offEnded = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('ended', callback); };
3238 this.offStop = (callback = () => { }) => this.stopStack.remove(callback);
3239 this.offTimeUpdate = (callback = () => { }) => { var _a; return (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.removeEventListener('timeupdate', callback); };
3240 this.offPrev = permanentlyNotSupport('BackgroundAudioManager.offPrev');
3241 this.offNext = permanentlyNotSupport('BackgroundAudioManager.offNext');
3242 this.Instance = new Audio();
3243 this.errorStack = new CallbackManager();
3244 this.stopStack = new CallbackManager();
3245 this.Instance.onerror = this.errorStack.trigger;
3246 this.Instance.autoplay = true;
3247 this.onPlay(() => {
3248 if (this.currentTime !== this.startTime) {
3249 this.seek(this.startTime);
3250 }
3251 });
3252 }
3253 set src(e) { this.setProperty('src', e); }
3254 get src() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.src) || ''; }
3255 set startTime(e) { this.__startTime = e; }
3256 get startTime() { return this.__startTime || 0; }
3257 set title(e) { this.dataset('title', e); }
3258 get title() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.dataset.title) || ''; }
3259 set epname(e) { this.dataset('epname', e); }
3260 get epname() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.dataset.epname) || ''; }
3261 set singer(e) { this.dataset('singer', e); }
3262 get singer() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.dataset.singer) || ''; }
3263 set coverImgUrl(e) { this.dataset('coverImgUrl', e); }
3264 get coverImgUrl() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.dataset.coverImgUrl) || ''; }
3265 set webUrl(e) { this.dataset('webUrl', e); }
3266 get webUrl() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.dataset.webUrl) || ''; }
3267 set protocol(e) { this.dataset('protocol', e); }
3268 get protocol() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.dataset.protocol) || ''; }
3269 set playbackRate(e) { this.setProperty('playbackRate', e); }
3270 get playbackRate() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.playbackRate) || 0; }
3271 get duration() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.duration) || 0; }
3272 get currentTime() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.currentTime) || 0; }
3273 get paused() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.paused) || false; }
3274 get buffered() {
3275 const { currentTime = 0, buffered: timeRange } = this.Instance || {};
3276 if (timeRange) {
3277 for (let i = 0; i < timeRange.length; i++) {
3278 if (timeRange.start(i) <= currentTime && timeRange.end(i) >= currentTime) {
3279 return timeRange.end(i);
3280 }
3281 }
3282 }
3283 return 0;
3284 }
3285 set referrerPolicy(e) { var _a; (_a = this.Instance) === null || _a === void 0 ? void 0 : _a.setAttribute('referrerpolicy', e); }
3286 get referrerPolicy() { var _a; return ((_a = this.Instance) === null || _a === void 0 ? void 0 : _a.getAttribute('referrerpolicy')) || 'origin'; }
3287 setProperty(key, value) {
3288 if (this.Instance) {
3289 this.Instance[key] = value;
3290 }
3291 }
3292 dataset(key, value) {
3293 if (this.Instance) {
3294 this.Instance.dataset[key] = value;
3295 }
3296 }
3297}
3298
3299// 背景音频
3300const stopBackgroundAudio = /* @__PURE__ */ temporarilyNotSupport('stopBackgroundAudio');
3301const seekBackgroundAudio = /* @__PURE__ */ temporarilyNotSupport('seekBackgroundAudio');
3302const playBackgroundAudio = /* @__PURE__ */ temporarilyNotSupport('playBackgroundAudio');
3303const pauseBackgroundAudio = /* @__PURE__ */ temporarilyNotSupport('pauseBackgroundAudio');
3304const onBackgroundAudioStop = /* @__PURE__ */ temporarilyNotSupport('onBackgroundAudioStop');
3305const onBackgroundAudioPlay = /* @__PURE__ */ temporarilyNotSupport('onBackgroundAudioPlay');
3306const onBackgroundAudioPause = /* @__PURE__ */ temporarilyNotSupport('onBackgroundAudioPause');
3307const getBackgroundAudioPlayerState = /* @__PURE__ */ temporarilyNotSupport('getBackgroundAudioPlayerState');
3308/**
3309 * 获取全局唯一的背景音频管理器
3310 */
3311const getBackgroundAudioManager = () => new BackgroundAudioManager();
3312
3313// 相机
3314const createCameraContext = /* @__PURE__ */ temporarilyNotSupport('createCameraContext');
3315
3316const saveImageToPhotosAlbum = (options) => {
3317 const methodName = 'saveImageToPhotosAlbum';
3318 // options must be an Object
3319 const isObject = shouldBeObject(options);
3320 if (!isObject.flag) {
3321 const res = { errMsg: `${methodName}:fail ${isObject.msg}` };
3322 console.error(res.errMsg);
3323 return Promise.reject(res);
3324 }
3325 const { filePath, success, fail, complete, } = options;
3326 const handle = new MethodHandler({ name: methodName, success, fail, complete });
3327 if (typeof filePath !== 'string') {
3328 return handle.fail({
3329 errMsg: getParameterError({
3330 para: 'filePath',
3331 correct: 'String',
3332 wrong: filePath
3333 })
3334 });
3335 }
3336 createDownload(filePath);
3337 return handle.success();
3338};
3339
3340/**
3341 * 获取图片信息。网络图片需先配置download域名才能生效。
3342 */
3343const getImageInfo = (options) => {
3344 // options must be an Object
3345 const isObject = shouldBeObject(options);
3346 if (!isObject.flag) {
3347 const res = { errMsg: `getImageInfo:fail ${isObject.msg}` };
3348 console.error(res.errMsg);
3349 return Promise.reject(res);
3350 }
3351 const getBase64Image = (image) => {
3352 try {
3353 const canvas = document.createElement('canvas');
3354 canvas.width = image.width;
3355 canvas.height = image.height;
3356 const ctx = canvas.getContext('2d');
3357 ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(image, 0, 0, image.width, image.height);
3358 return canvas.toDataURL('image/png');
3359 }
3360 catch (e) {
3361 console.error('getImageInfo:get base64 fail', e);
3362 }
3363 };
3364 const { src, success, fail, complete } = options;
3365 const handle = new MethodHandler({ name: 'getImageInfo', success, fail, complete });
3366 return new Promise((resolve, reject) => {
3367 const image = new Image();
3368 image.crossOrigin = '';
3369 image.onload = () => {
3370 handle.success({
3371 width: image.naturalWidth,
3372 height: image.naturalHeight,
3373 path: getBase64Image(image) || src
3374 }, { resolve, reject });
3375 };
3376 image.onerror = (e) => {
3377 handle.fail({
3378 errMsg: e.message
3379 }, { resolve, reject });
3380 };
3381 image.src = src;
3382 });
3383};
3384
3385/**
3386 * previewImage api基于开源的React组件[react-wx-images-viewer](https://github.com/react-ld/react-wx-images-viewer)开发,感谢!
3387 */
3388/**
3389 * 在新页面中全屏预览图片。预览的过程中用户可以进行保存图片、发送给朋友等操作。
3390 */
3391const previewImage = (options) => __awaiter(void 0, void 0, void 0, function* () {
3392 // TODO 改为通过 window.__taroAppConfig 获取配置的 Swiper 插件创建节点
3393 defineCustomElementTaroSwiperCore();
3394 defineCustomElementTaroSwiperItemCore();
3395 function loadImage(url, loadFail) {
3396 return new Promise((resolve) => {
3397 const item = document.createElement('taro-swiper-item-core');
3398 item.style.cssText = 'display:flex;align-items:start;justify-content:center;overflow-y:scroll;';
3399 const image = new Image();
3400 image.style.maxWidth = '100%';
3401 image.src = url;
3402 const div = document.createElement('div');
3403 div.classList.add('swiper-zoom-container');
3404 div.style.cssText = 'display:flex;align-items:center;justify-content:center;max-width:100%;min-height:100%;';
3405 div.appendChild(image);
3406 item.appendChild(div);
3407 // Note: 等待图片加载完后返回,会导致轮播被卡住
3408 resolve(item);
3409 if (isFunction(loadFail)) {
3410 image.addEventListener('error', (err) => {
3411 loadFail({ errMsg: err.message });
3412 });
3413 }
3414 });
3415 }
3416 // options must be an Object
3417 const isObject = shouldBeObject(options);
3418 if (!isObject.flag) {
3419 const res = { errMsg: `previewImage:fail ${isObject.msg}` };
3420 console.error(res.errMsg);
3421 return Promise.reject(res);
3422 }
3423 const { urls = [], current = '', success, fail, complete } = options;
3424 const handle = new MethodHandler({ name: 'previewImage', success, fail, complete });
3425 const container = document.createElement('div');
3426 const removeHandler = () => {
3427 eventCenter$1.off('__taroRouterChange', removeHandler);
3428 container.remove();
3429 };
3430 // 路由改变后应该关闭预览框
3431 eventCenter$1.on('__taroRouterChange', removeHandler);
3432 container.classList.add('preview-image');
3433 container.style.cssText =
3434 'position:fixed;top:0;left:0;z-index:1050;width:100%;height:100%;overflow:hidden;outline:0;background-color:#111;';
3435 container.addEventListener('click', removeHandler);
3436 const swiper = document.createElement('taro-swiper-core');
3437 // @ts-ignore
3438 swiper.full = true;
3439 // @ts-ignore
3440 swiper.zoom = true;
3441 let children = [];
3442 try {
3443 children = yield Promise.all(urls.map((e) => loadImage(e, fail)));
3444 }
3445 catch (error) {
3446 return handle.fail({
3447 errMsg: error,
3448 });
3449 }
3450 for (let i = 0; i < children.length; i++) {
3451 const child = children[i];
3452 swiper.appendChild(child);
3453 }
3454 const currentIndex = typeof current === 'number' ? current : urls.indexOf(current);
3455 swiper.current = currentIndex;
3456 container.appendChild(swiper);
3457 document.body.appendChild(container);
3458 return handle.success();
3459});
3460
3461/**
3462 * H5 下的 styleSheet 操作
3463 * @author leeenx
3464 */
3465class StyleSheet {
3466 constructor() {
3467 this.$style = null;
3468 this.sheet = null;
3469 this.appendStyleSheet = () => {
3470 if (this.$style) {
3471 const head = document.getElementsByTagName('head')[0];
3472 this.$style.setAttribute('type', 'text/css');
3473 this.$style.setAttribute('data-type', 'Taro');
3474 head.appendChild(this.$style);
3475 this.sheet = this.$style.sheet;
3476 }
3477 if (this.sheet && !('insertRule' in this.sheet)) {
3478 console.warn('当前浏览器不支持 stylesheet.insertRule 接口');
3479 }
3480 };
3481 // 添加样式命令
3482 this.add = (cssText, index = 0) => {
3483 var _a;
3484 if (this.sheet === null) {
3485 // $style 未插入到 DOM
3486 this.appendStyleSheet();
3487 }
3488 (_a = this.sheet) === null || _a === void 0 ? void 0 : _a.insertRule(cssText, index);
3489 };
3490 this.$style = document.createElement('style');
3491 }
3492}
3493const styleSheet = new StyleSheet();
3494// 监听事件
3495let TRANSITION_END = 'transitionend';
3496let TRANSFORM = 'transform';
3497const $detect = document.createElement('div');
3498$detect.style.cssText = '-webkit-animation-name:webkit;-moz-animation-name:moz;-ms-animation-name:ms;animation-name:standard;';
3499if ($detect.style['animation-name'] === 'standard') {
3500 // 支持标准写法
3501 TRANSITION_END = 'transitionend';
3502 TRANSFORM = 'transform';
3503}
3504else if ($detect.style['-webkit-animation-name'] === 'webkit') {
3505 // webkit 前缀
3506 TRANSITION_END = 'webkitTransitionEnd';
3507 TRANSFORM = '-webkit-transform';
3508}
3509else if ($detect.style['-moz-animation-name'] === 'moz') {
3510 // moz 前缀
3511 TRANSITION_END = 'mozTransitionEnd';
3512 TRANSFORM = '-moz-transform';
3513}
3514else if ($detect.style['-ms-animation-name'] === 'ms') {
3515 // ms 前缀
3516 TRANSITION_END = 'msTransitionEnd';
3517 TRANSFORM = '-ms-transform';
3518}
3519let animId = 0;
3520class Animation {
3521 constructor({ duration = 400, delay = 0, timingFunction = 'linear', transformOrigin = '50% 50% 0', unit = 'px' } = {}) {
3522 // 属性组合
3523 this.rules = [];
3524 // transform 对象
3525 this.transform = [];
3526 // 组合动画
3527 this.steps = [];
3528 // 动画 map ----- 永久保留
3529 this.animationMap = {};
3530 // animationMap 的长度
3531 this.animationMapCount = 0;
3532 // 历史动画
3533 this.historyAnimations = [];
3534 // 历史规则
3535 this.historyRules = [];
3536 // 默认值
3537 this.setDefault(duration, delay, timingFunction, transformOrigin);
3538 this.unit = unit;
3539 // atom 环境下,animation 属性不会显示,所以要改成 data-animation
3540 let animAttr = 'animation';
3541 // 动画 id
3542 this.id = ++animId;
3543 // 监听事件
3544 document.body.addEventListener(TRANSITION_END, (e) => {
3545 const target = e.target;
3546 if (target.getAttribute(animAttr) === null) {
3547 animAttr = 'data-animation';
3548 }
3549 const animData = target.getAttribute(animAttr);
3550 // 没有动画存在
3551 if (animData === null)
3552 return;
3553 const [animName, animPath] = animData.split('__');
3554 if (animName === `taro-h5-poly-fill/${this.id}/create-animation`) {
3555 const [animIndex, __stepIndex = 0] = animPath.split('--');
3556 const stepIndex = Number(__stepIndex);
3557 // 动画总的关键帧
3558 const animStepsCount = this.animationMap[`${animName}__${animIndex}`];
3559 const animStepsMaxIndex = animStepsCount - 1;
3560 if (stepIndex < animStepsMaxIndex) {
3561 // 播放下一个关键帧(因为 nerv 和 react 有差异所以 animation & data-animation 都需要写)
3562 target.setAttribute(animAttr, `${animName}__${animIndex}--${stepIndex + 1}`);
3563 if (animAttr === 'data-animation') {
3564 // Nerv 环境,animation & data-animation 双重保险
3565 target.setAttribute('animation', `${animName}__${animIndex}--${stepIndex + 1}`);
3566 }
3567 }
3568 }
3569 });
3570 }
3571 transformUnit(...args) {
3572 const ret = [];
3573 args.forEach(each => {
3574 ret.push(isNaN(each) ? each : `${each}${this.unit}`);
3575 });
3576 return ret;
3577 }
3578 // 设置默认值
3579 setDefault(duration, delay, timingFunction, transformOrigin) {
3580 this.DEFAULT = { duration, delay, timingFunction, transformOrigin };
3581 }
3582 matrix(a, b, c, d, tx, ty) {
3583 this.transform.push({ key: 'matrix', transform: `matrix(${a}, ${b}, ${c}, ${d}, ${tx}, ${ty})` });
3584 return this;
3585 }
3586 matrix3d(a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3, a4, b4, c4, d4) {
3587 this.transform.push({
3588 key: 'matrix3d',
3589 transform: `matrix3d(${a1}, ${b1}, ${c1}, ${d1}, ${a2}, ${b2}, ${c2}, ${d2}, ${a3}, ${b3}, ${c3}, ${d3}, ${a4}, ${b4}, ${c4}, ${d4})`,
3590 });
3591 return this;
3592 }
3593 rotate(angle) {
3594 this.transform.push({ key: 'rotate', transform: `rotate(${angle}deg)` });
3595 return this;
3596 }
3597 rotate3d(x, y, z, angle) {
3598 if (typeof y !== 'number') {
3599 this.transform.push({ key: 'rotate3d', transform: `rotate3d(${x})` });
3600 }
3601 else {
3602 this.transform.push({ key: 'rotate3d', transform: `rotate3d(${x}, ${y || 0}, ${z || 0}, ${angle || 0}deg)` });
3603 }
3604 return this;
3605 }
3606 rotateX(angle) {
3607 this.transform.push({ key: 'rotateX', transform: `rotateX(${angle}deg)` });
3608 return this;
3609 }
3610 rotateY(angle) {
3611 this.transform.push({ key: 'rotateY', transform: `rotateY(${angle}deg)` });
3612 return this;
3613 }
3614 rotateZ(angle) {
3615 this.transform.push({ key: 'rotateZ', transform: `rotateZ(${angle}deg)` });
3616 return this;
3617 }
3618 scale(x, y) {
3619 const scaleY = (typeof y !== 'undefined' && y !== null) ? y : x;
3620 this.transform.push({ key: 'scale', transform: `scale(${x}, ${scaleY})` });
3621 return this;
3622 }
3623 scale3d(x, y, z) {
3624 this.transform.push({ key: 'scale3d', transform: `scale3d(${x}, ${y}, ${z})` });
3625 return this;
3626 }
3627 scaleX(scale) {
3628 this.transform.push({ key: 'scaleX', transform: `scaleX(${scale})` });
3629 return this;
3630 }
3631 scaleY(scale) {
3632 this.transform.push({ key: 'scaleY', transform: `scaleY(${scale})` });
3633 return this;
3634 }
3635 scaleZ(scale) {
3636 this.transform.push({ key: 'scaleZ', transform: `scaleZ(${scale})` });
3637 return this;
3638 }
3639 skew(x, y) {
3640 this.transform.push({ key: 'skew', transform: `skew(${x}deg, ${y}deg)` });
3641 return this;
3642 }
3643 skewX(angle) {
3644 this.transform.push({ key: 'skewX', transform: `skewX(${angle}deg)` });
3645 return this;
3646 }
3647 skewY(angle) {
3648 this.transform.push({ key: 'skewY', transform: `skewY(${angle}deg)` });
3649 return this;
3650 }
3651 translate(x, y) {
3652 [x, y] = this.transformUnit(x, y);
3653 this.transform.push({ key: 'translate', transform: `translate(${x}, ${y})` });
3654 return this;
3655 }
3656 translate3d(x, y, z) {
3657 [x, y, z] = this.transformUnit(x, y, z);
3658 this.transform.push({ key: 'translate3d', transform: `translate3d(${x}, ${y}, ${z})` });
3659 return this;
3660 }
3661 translateX(translate) {
3662 [translate] = this.transformUnit(translate);
3663 this.transform.push({ key: 'translateX', transform: `translateX(${translate})` });
3664 return this;
3665 }
3666 translateY(translate) {
3667 [translate] = this.transformUnit(translate);
3668 this.transform.push({ key: 'translateY', transform: `translateY(${translate})` });
3669 return this;
3670 }
3671 translateZ(translate) {
3672 [translate] = this.transformUnit(translate);
3673 this.transform.push({ key: 'translateZ', transform: `translateZ(${translate})` });
3674 return this;
3675 }
3676 opacity(value) {
3677 this.rules.push({ key: 'opacity', rule: `opacity: ${value}` });
3678 return this;
3679 }
3680 backgroundColor(value) {
3681 this.rules.push({ key: 'backgroundColor', rule: `background-color: ${value}` });
3682 return this;
3683 }
3684 width(value) {
3685 [value] = this.transformUnit(value);
3686 this.rules.push({ key: 'width', rule: `width: ${value}` });
3687 return this;
3688 }
3689 height(value) {
3690 [value] = this.transformUnit(value);
3691 this.rules.push({ key: 'height', rule: `height: ${value}` });
3692 return this;
3693 }
3694 top(value) {
3695 [value] = this.transformUnit(value);
3696 this.rules.push({ key: 'top', rule: `top: ${value}` });
3697 return this;
3698 }
3699 right(value) {
3700 [value] = this.transformUnit(value);
3701 this.rules.push({ key: 'right', rule: `right: ${value}` });
3702 return this;
3703 }
3704 bottom(value) {
3705 [value] = this.transformUnit(value);
3706 this.rules.push({ key: 'bottom', rule: `bottom: ${value}` });
3707 return this;
3708 }
3709 left(value) {
3710 [value] = this.transformUnit(value);
3711 this.rules.push({ key: 'left', rule: `left: ${value}` });
3712 return this;
3713 }
3714 // 关键帧载入
3715 step(arg = {}) {
3716 const { DEFAULT } = this;
3717 const { duration = DEFAULT.duration, delay = DEFAULT.delay, timingFunction = DEFAULT.timingFunction, transformOrigin = DEFAULT.transformOrigin, } = arg;
3718 // 生成一条 transition 动画
3719 this.transform.map((t0) => {
3720 const index = this.historyAnimations.findIndex((t1) => t1.key === t0.key);
3721 if (index === -1) {
3722 this.historyAnimations.push(t0);
3723 }
3724 else {
3725 this.historyAnimations[index] = t0;
3726 }
3727 });
3728 const transforms = this.historyAnimations.map((t) => t.transform);
3729 const transformSequence = transforms.length > 0 ? `${TRANSFORM}:${transforms.join(' ')}!important` : '';
3730 this.rules.map((r0) => {
3731 const index = this.historyRules.findIndex((r1) => r1.key === r0.key);
3732 if (index === -1) {
3733 this.historyRules.push(r0);
3734 }
3735 else {
3736 this.historyRules[index] = r0;
3737 }
3738 });
3739 const rules = this.historyRules.map((t) => t.rule);
3740 const ruleSequence = rules.length > 0 ? rules.map((rule) => `${rule}!important`).join(';') : '';
3741 this.steps.push([
3742 ruleSequence,
3743 transformSequence,
3744 `${TRANSFORM}-origin: ${transformOrigin}`,
3745 `transition: all ${duration}ms ${timingFunction} ${delay}ms`,
3746 ]
3747 .filter((item) => item !== '')
3748 .join(';'));
3749 // 清空 rules 和 transform
3750 this.rules = [];
3751 this.transform = [];
3752 return this;
3753 }
3754 // 创建底层数据
3755 createAnimationData() {
3756 const animIndex = `taro-h5-poly-fill/${this.id}/create-animation__${this.animationMapCount++}`;
3757 // 记录动画分几个 step
3758 this.animationMap[animIndex] = this.steps.length;
3759 // 吐出 step
3760 this.steps.forEach((step, index) => {
3761 const selector = index === 0
3762 ? `[animation="${animIndex}"], [data-animation="${animIndex}"]`
3763 : `[animation="${animIndex}--${index}"], [data-animation="${animIndex}--${index}"]`;
3764 styleSheet.add(`${selector} { ${step} }`);
3765 });
3766 // 清空 steps
3767 this.steps = [];
3768 return animIndex;
3769 }
3770 // 动画数据产出
3771 export() {
3772 return this.createAnimationData();
3773 }
3774}
3775// h5 的 createAnimation
3776const createAnimation = (option) => {
3777 return new Animation(option);
3778};
3779
3780// 背景
3781const setBackgroundTextStyle = /* @__PURE__ */ temporarilyNotSupport('setBackgroundTextStyle');
3782const setBackgroundColor = /* @__PURE__ */ temporarilyNotSupport('setBackgroundColor');
3783
3784// 自定义组件
3785const nextTick = Taro.nextTick;
3786
3787// 字体
3788const loadFontFace = (options) => __awaiter(void 0, void 0, void 0, function* () {
3789 options = Object.assign({ global: false }, options);
3790 const { success, fail, complete, family, source, desc = {} } = options;
3791 const handle = new MethodHandler({ name: 'loadFontFace', success, fail, complete });
3792 // @ts-ignore
3793 const fonts = document.fonts;
3794 if (fonts) {
3795 // @ts-ignore
3796 const fontFace = new FontFace(family, source, desc);
3797 try {
3798 yield fontFace.load();
3799 fonts.add(fontFace);
3800 return handle.success({ status: 'loaded' });
3801 }
3802 catch (error) {
3803 return handle.fail({
3804 status: 'error',
3805 errMsg: error.message || error,
3806 });
3807 }
3808 }
3809 else {
3810 const style = document.createElement('style');
3811 let innerText = `font-family:"${family}";src:${source};font-style:${desc.style || 'normal'};font-weight:${desc.weight || 'normal'};font-variant:${desc.variant || 'normal'};`;
3812 if (desc.ascentOverride) {
3813 innerText += `ascent-override:${desc.ascentOverride};`;
3814 }
3815 if (desc.descentOverride) {
3816 innerText += `descent-override:${desc.descentOverride};`;
3817 }
3818 if (desc.featureSettings) {
3819 innerText += `font-feature-settings:${desc.featureSettings};`;
3820 }
3821 if (desc.lineGapOverride) {
3822 innerText += `line-gap-override:${desc.lineGapOverride};`;
3823 }
3824 if (desc.stretch) {
3825 innerText += `font-stretch:${desc.stretch};`;
3826 }
3827 if (desc.unicodeRange) {
3828 innerText += `unicode-range:${desc.unicodeRange};`;
3829 }
3830 if (desc.variationSettings) {
3831 innerText += `font-variation-settings:${desc.variationSettings};`;
3832 }
3833 style.innerText = `@font-face{${innerText}}`;
3834 document.head.appendChild(style);
3835 return handle.success({ status: 'loaded' });
3836 }
3837});
3838
3839// 菜单
3840const getMenuButtonBoundingClientRect = /* @__PURE__ */ temporarilyNotSupport('getMenuButtonBoundingClientRect');
3841
3842// 导航栏
3843/**
3844 * 展示导航栏 loading 状态
3845*/
3846function showNavigationBarLoading(options = {}) {
3847 const { success, fail, complete } = options;
3848 const handle = new MethodHandler({ name: 'showNavigationBarLoading', success, fail, complete });
3849 setNavigationBarLoading(true);
3850 return handle.success();
3851}
3852function setNavigationBarTitle(options) {
3853 // options must be an Object
3854 const isObject = shouldBeObject(options);
3855 if (!isObject.flag) {
3856 const res = { errMsg: `setNavigationBarTitle:fail ${isObject.msg}` };
3857 console.error(res.errMsg);
3858 return Promise.reject(res);
3859 }
3860 const { title, success, fail, complete } = options;
3861 const handle = new MethodHandler({ name: 'setNavigationBarTitle', success, fail, complete });
3862 if (!title || typeof title !== 'string') {
3863 return handle.fail({
3864 errMsg: getParameterError({
3865 para: 'title',
3866 correct: 'String',
3867 wrong: title
3868 })
3869 });
3870 }
3871 setTitle(title);
3872 return handle.success();
3873}
3874/**
3875 * 设置页面导航条颜色
3876 */
3877const setNavigationBarColor = (options) => {
3878 const { backgroundColor, frontColor, success, fail, complete } = options;
3879 const handle = new MethodHandler({ name: 'setNavigationBarColor', success, fail, complete });
3880 const meta = document.createElement('meta');
3881 meta.setAttribute('name', 'theme-color');
3882 meta.setAttribute('content', backgroundColor);
3883 document.head.appendChild(meta);
3884 setNavigationBarStyle({ frontColor, backgroundColor });
3885 return handle.success();
3886};
3887/**
3888 * 隐藏导航栏 loading 状态
3889*/
3890function hideNavigationBarLoading(options = {}) {
3891 const { success, fail, complete } = options;
3892 const handle = new MethodHandler({ name: 'hideNavigationBarLoading', success, fail, complete });
3893 setNavigationBarLoading(false);
3894 return handle.success();
3895}
3896const hideHomeButton = /* @__PURE__ */ temporarilyNotSupport('hideHomeButton');
3897
3898/**
3899 * 开始下拉刷新。调用后触发下拉刷新动画,效果与用户手动下拉刷新一致。
3900 */
3901const startPullDownRefresh = function ({ success, fail, complete } = {}) {
3902 const handle = new MethodHandler({ name: 'startPullDownRefresh', success, fail, complete });
3903 return new Promise((resolve, reject) => {
3904 Taro.eventCenter.trigger('__taroStartPullDownRefresh', {
3905 successHandler: (res = {}) => handle.success(res, { resolve, reject }),
3906 errorHandler: (res = {}) => handle.fail(res, { resolve, reject })
3907 });
3908 });
3909};
3910/**
3911 * 停止当前页面下拉刷新。
3912 */
3913const stopPullDownRefresh = function ({ success, fail, complete } = {}) {
3914 const handle = new MethodHandler({ name: 'stopPullDownRefresh', success, fail, complete });
3915 return new Promise((resolve, reject) => {
3916 Taro.eventCenter.trigger('__taroStopPullDownRefresh', {
3917 successHandler: (res = {}) => handle.success(res, { resolve, reject }),
3918 errorHandler: (res = {}) => handle.fail(res, { resolve, reject })
3919 });
3920 });
3921};
3922
3923let timer;
3924const FRAME_DURATION = 17;
3925/**
3926 * 将页面滚动到目标位置
3927 */
3928const pageScrollTo = ({ scrollTop, selector = '', offsetTop = 0, duration = 300, success, fail, complete }) => {
3929 let scrollFunc;
3930 const handle = new MethodHandler({ name: 'pageScrollTo', success, fail, complete });
3931 return new Promise((resolve, reject) => {
3932 var _a, _b, _c;
3933 try {
3934 if (scrollTop === undefined && !selector) {
3935 return handle.fail({
3936 errMsg: 'scrollTop" 或 "selector" 需要其之一'
3937 }, { resolve, reject });
3938 }
3939 const usingWindowScroll = (_a = window.__taroAppConfig) === null || _a === void 0 ? void 0 : _a.usingWindowScroll;
3940 const id = (_c = (_b = Current$1.page) === null || _b === void 0 ? void 0 : _b.path) === null || _c === void 0 ? void 0 : _c.replace(/([^a-z0-9\u00a0-\uffff_-])/ig, '\\$1');
3941 const el = (id
3942 ? document.querySelector(`.taro_page#${id}`)
3943 : document.querySelector('.taro_page') ||
3944 document.querySelector('.taro_router'));
3945 if (!scrollFunc) {
3946 if (usingWindowScroll) {
3947 scrollFunc = pos => {
3948 if (pos === undefined) {
3949 return window.pageYOffset;
3950 }
3951 else {
3952 window.scrollTo(0, pos);
3953 }
3954 };
3955 }
3956 else {
3957 scrollFunc = pos => {
3958 if (pos === undefined) {
3959 return el.scrollTop;
3960 }
3961 else {
3962 el.scrollTop = pos;
3963 }
3964 };
3965 }
3966 }
3967 if (scrollTop && selector) {
3968 console.warn('"scrollTop" 或 "selector" 建议只设一个值,全部设置会忽略selector');
3969 }
3970 const from = scrollFunc();
3971 let to;
3972 if (selector) {
3973 const el = document.querySelector(selector);
3974 to = ((el === null || el === void 0 ? void 0 : el.offsetTop) || 0) + offsetTop;
3975 }
3976 else {
3977 to = typeof scrollTop === 'number' ? scrollTop : 0;
3978 }
3979 const delta = to - from;
3980 const frameCnt = duration / FRAME_DURATION;
3981 const easeFunc = getTimingFunc(easeInOut, frameCnt);
3982 const scroll = (frame = 0) => {
3983 const dest = from + delta * easeFunc(frame);
3984 scrollFunc(dest);
3985 if (frame < frameCnt) {
3986 timer && clearTimeout(timer);
3987 timer = setTimeout(() => {
3988 scroll(frame + 1);
3989 }, FRAME_DURATION);
3990 }
3991 else {
3992 return handle.success({}, { resolve, reject });
3993 }
3994 };
3995 scroll();
3996 }
3997 catch (e) {
3998 return handle.fail({
3999 errMsg: e.message
4000 }, { resolve, reject });
4001 }
4002 });
4003};
4004
4005// 置顶
4006const setTopBarText = /* @__PURE__ */ temporarilyNotSupport('setTopBarText');
4007
4008let tabConf;
4009function initTabBarApis(config = {}) {
4010 tabConf = config.tabBar;
4011}
4012/**
4013 * 显示 tabBar 某一项的右上角的红点
4014 */
4015const showTabBarRedDot = (options) => {
4016 // options must be an Object
4017 const isObject = shouldBeObject(options);
4018 if (!isObject.flag) {
4019 const res = { errMsg: `showTabBarRedDot:fail ${isObject.msg}` };
4020 console.error(res.errMsg);
4021 return Promise.reject(res);
4022 }
4023 const { index, success, fail, complete } = options;
4024 const handle = new MethodHandler({ name: 'showTabBarRedDot', success, fail, complete });
4025 if (typeof index !== 'number') {
4026 return handle.fail({
4027 errMsg: getParameterError({
4028 para: 'index',
4029 correct: 'Number',
4030 wrong: index
4031 })
4032 });
4033 }
4034 return new Promise((resolve, reject) => {
4035 Taro.eventCenter.trigger('__taroShowTabBarRedDotHandler', {
4036 index,
4037 successHandler: (res = {}) => handle.success(res, { resolve, reject }),
4038 errorHandler: (res = {}) => handle.fail(res, { resolve, reject })
4039 });
4040 });
4041};
4042/**
4043 * 显示 tabBar
4044 */
4045const showTabBar = (options = {}) => {
4046 // options must be an Object
4047 const isObject = shouldBeObject(options);
4048 if (!isObject.flag) {
4049 const res = { errMsg: `showTabBar:fail ${isObject.msg}` };
4050 console.error(res.errMsg);
4051 return Promise.reject(res);
4052 }
4053 const { animation, success, fail, complete } = options;
4054 const handle = new MethodHandler({ name: 'showTabBar', success, fail, complete });
4055 if (options.hasOwnProperty('animation') && typeof animation !== 'boolean') {
4056 return handle.fail({
4057 errMsg: getParameterError({
4058 para: 'animation',
4059 correct: 'Boolean',
4060 wrong: animation
4061 })
4062 });
4063 }
4064 return new Promise((resolve, reject) => {
4065 Taro.eventCenter.trigger('__taroShowTabBar', {
4066 animation,
4067 successHandler: (res = {}) => handle.success(res, { resolve, reject }),
4068 errorHandler: (res = {}) => handle.fail(res, { resolve, reject })
4069 });
4070 });
4071};
4072/**
4073 * 动态设置 tabBar 的整体样式
4074 */
4075const setTabBarStyle = (options = {}) => {
4076 // options must be an Object
4077 const isObject = shouldBeObject(options);
4078 if (!isObject.flag) {
4079 const res = { errMsg: `setTabBarStyle:fail ${isObject.msg}` };
4080 console.error(res.errMsg);
4081 return Promise.reject(res);
4082 }
4083 const { color, selectedColor, backgroundColor, borderStyle, success, fail, complete } = options;
4084 const handle = new MethodHandler({ name: 'setTabBarStyle', success, fail, complete });
4085 let errMsg;
4086 if (color && !isValidColor(color)) {
4087 errMsg = 'color';
4088 }
4089 else if (selectedColor && !isValidColor(selectedColor)) {
4090 errMsg = 'selectedColor';
4091 }
4092 else if (backgroundColor && !isValidColor(backgroundColor)) {
4093 errMsg = 'backgroundColor';
4094 }
4095 else if (borderStyle && !/^(black|white)$/.test(borderStyle)) {
4096 errMsg = 'borderStyle';
4097 }
4098 if (errMsg) {
4099 return handle.fail({ errMsg: `invalid ${errMsg}` });
4100 }
4101 if (!tabConf) {
4102 return handle.fail();
4103 }
4104 const obj = {};
4105 if (color)
4106 obj.color = color;
4107 if (selectedColor)
4108 obj.selectedColor = selectedColor;
4109 if (backgroundColor)
4110 obj.backgroundColor = backgroundColor;
4111 if (borderStyle)
4112 obj.borderStyle = borderStyle;
4113 return new Promise((resolve, reject) => {
4114 Taro.eventCenter.trigger('__taroSetTabBarStyle', {
4115 color,
4116 selectedColor,
4117 backgroundColor,
4118 borderStyle,
4119 successHandler: (res = {}) => handle.success(res, { resolve, reject }),
4120 errorHandler: (res = {}) => handle.fail(res, { resolve, reject })
4121 });
4122 });
4123};
4124/**
4125 * 动态设置 tabBar 某一项的内容
4126 */
4127const setTabBarItem = (options) => {
4128 // options must be an Object
4129 const isObject = shouldBeObject(options);
4130 if (!isObject.flag) {
4131 const res = { errMsg: `setTabBarItem:fail ${isObject.msg}` };
4132 console.error(res.errMsg);
4133 return Promise.reject(res);
4134 }
4135 const { index, text, iconPath, selectedIconPath, success, fail, complete } = options;
4136 const handle = new MethodHandler({ name: 'setTabBarItem', success, fail, complete });
4137 if (typeof index !== 'number') {
4138 return handle.fail({
4139 errMsg: getParameterError({
4140 para: 'index',
4141 correct: 'Number',
4142 wrong: index
4143 })
4144 });
4145 }
4146 return new Promise((resolve, reject) => {
4147 Taro.eventCenter.trigger('__taroSetTabBarItem', {
4148 index,
4149 text,
4150 iconPath,
4151 selectedIconPath,
4152 successHandler: (res = {}) => handle.success(res, { resolve, reject }),
4153 errorHandler: (res = {}) => handle.fail(res, { resolve, reject })
4154 });
4155 });
4156};
4157/**
4158 * 为 tabBar 某一项的右上角添加文本
4159 */
4160const setTabBarBadge = (options) => {
4161 // options must be an Object
4162 const isObject = shouldBeObject(options);
4163 if (!isObject.flag) {
4164 const res = { errMsg: `setTabBarBadge:fail ${isObject.msg}` };
4165 console.error(res.errMsg);
4166 return Promise.reject(res);
4167 }
4168 const { index, text, success, fail, complete } = options;
4169 const handle = new MethodHandler({ name: 'setTabBarBadge', success, fail, complete });
4170 if (typeof index !== 'number') {
4171 return handle.fail({
4172 errMsg: getParameterError({
4173 para: 'index',
4174 correct: 'Number',
4175 wrong: index
4176 })
4177 });
4178 }
4179 if (typeof text !== 'string') {
4180 return handle.fail({
4181 errMsg: getParameterError({
4182 para: 'text',
4183 correct: 'String',
4184 wrong: text
4185 })
4186 });
4187 }
4188 return new Promise((resolve, reject) => {
4189 Taro.eventCenter.trigger('__taroSetTabBarBadge', {
4190 index,
4191 text: text.replace(/[\u0391-\uFFE5]/g, 'aa').length > 4 ? '...' : text,
4192 successHandler: (res = {}) => handle.success(res, { resolve, reject }),
4193 errorHandler: (res = {}) => handle.fail(res, { resolve, reject })
4194 });
4195 });
4196};
4197/**
4198 * 移除 tabBar 某一项右上角的文本
4199 */
4200const removeTabBarBadge = (options) => {
4201 // options must be an Object
4202 const isObject = shouldBeObject(options);
4203 if (!isObject.flag) {
4204 const res = { errMsg: `removeTabBarBadge:fail ${isObject.msg}` };
4205 console.error(res.errMsg);
4206 return Promise.reject(res);
4207 }
4208 const { index, success, fail, complete } = options;
4209 const handle = new MethodHandler({ name: 'removeTabBarBadge', success, fail, complete });
4210 if (typeof index !== 'number') {
4211 return handle.fail({
4212 errMsg: getParameterError({
4213 para: 'index',
4214 correct: 'Number',
4215 wrong: index
4216 })
4217 });
4218 }
4219 return new Promise((resolve, reject) => {
4220 Taro.eventCenter.trigger('__taroRemoveTabBarBadge', {
4221 index,
4222 successHandler: (res = {}) => handle.success(res, { resolve, reject }),
4223 errorHandler: (res = {}) => handle.fail(res, { resolve, reject })
4224 });
4225 });
4226};
4227/**
4228 * 隐藏 tabBar 某一项的右上角的红点
4229 */
4230const hideTabBarRedDot = (options) => {
4231 // options must be an Object
4232 const isObject = shouldBeObject(options);
4233 if (!isObject.flag) {
4234 const res = { errMsg: `hideTabBarRedDot:fail ${isObject.msg}` };
4235 console.error(res.errMsg);
4236 return Promise.reject(res);
4237 }
4238 const { index, success, fail, complete } = options;
4239 const handle = new MethodHandler({ name: 'hideTabBarRedDot', success, fail, complete });
4240 if (typeof index !== 'number') {
4241 return handle.fail({
4242 errMsg: getParameterError({
4243 para: 'index',
4244 correct: 'Number',
4245 wrong: index
4246 })
4247 });
4248 }
4249 return new Promise((resolve, reject) => {
4250 Taro.eventCenter.trigger('__taroHideTabBarRedDotHandler', {
4251 index,
4252 successHandler: (res = {}) => handle.success(res, { resolve, reject }),
4253 errorHandler: (res = {}) => handle.fail(res, { resolve, reject })
4254 });
4255 });
4256};
4257/**
4258 * 隐藏 tabBar
4259 */
4260const hideTabBar = (options = {}) => {
4261 // options must be an Object
4262 const isObject = shouldBeObject(options);
4263 if (!isObject.flag) {
4264 const res = { errMsg: `hideTabBar:fail ${isObject.msg}` };
4265 console.error(res.errMsg);
4266 return Promise.reject(res);
4267 }
4268 const { animation, success, fail, complete } = options;
4269 const handle = new MethodHandler({ name: 'hideTabBar', success, fail, complete });
4270 if (options.hasOwnProperty('animation') && typeof animation !== 'boolean') {
4271 return handle.fail({
4272 errMsg: getParameterError({
4273 para: 'animation',
4274 correct: 'Boolean',
4275 wrong: animation
4276 })
4277 });
4278 }
4279 return new Promise((resolve, reject) => {
4280 Taro.eventCenter.trigger('__taroHideTabBar', {
4281 animation,
4282 successHandler: (res = {}) => handle.success(res, { resolve, reject }),
4283 errorHandler: (res = {}) => handle.fail(res, { resolve, reject })
4284 });
4285 });
4286};
4287
4288const callbackManager = new CallbackManager();
4289const resizeListener = () => {
4290 callbackManager.trigger({
4291 windowWidth: window.screen.width,
4292 windowHeight: window.screen.height
4293 });
4294};
4295/**
4296 * 设置窗口大小,该接口仅适用于 PC 平台,使用细则请参见指南
4297 */
4298const setWindowSize = /* @__PURE__ */ temporarilyNotSupport('setWindowSize');
4299/**
4300 * 监听窗口尺寸变化事件
4301 */
4302const onWindowResize = callback => {
4303 callbackManager.add(callback);
4304 if (callbackManager.count() === 1) {
4305 window.addEventListener('resize', resizeListener);
4306 }
4307};
4308/**
4309 * 取消监听窗口尺寸变化事件
4310 */
4311const offWindowResize = callback => {
4312 callbackManager.remove(callback);
4313 if (callbackManager.count() === 0) {
4314 window.removeEventListener('resize', resizeListener);
4315 }
4316};
4317const checkIsPictureInPictureActive = /* @__PURE__ */ temporarilyNotSupport('checkIsPictureInPictureActive');
4318
4319/**
4320 * 拍摄或从手机相册中选择图片或视频。
4321 */
4322const chooseMedia = function (options, methodName = 'chooseMedia') {
4323 var _a;
4324 return __awaiter(this, void 0, void 0, function* () {
4325 // options must be an Object
4326 const isObject = shouldBeObject(options);
4327 if (!isObject.flag) {
4328 const res = { errMsg: `${methodName}:fail ${isObject.msg}` };
4329 console.error(res.errMsg);
4330 return Promise.reject(res);
4331 }
4332 const { count = 9, mediaId = 'taroChooseMedia', mediaType = ['image', 'video'], sourceType = ['album', 'camera'],
4333 // sizeType = ['original', 'compressed'], // TODO 考虑通过 ffmpeg 支持压缩
4334 // maxDuration = 10, // TODO 考虑通过 ffmpeg 剪裁视频
4335 camera = 'back', success, fail, complete, } = options;
4336 const handle = new MethodHandler({ name: methodName, success, fail, complete });
4337 const withImage = mediaType.length < 1 || mediaType.indexOf('image') > -1;
4338 const withVideo = mediaType.length < 1 || mediaType.indexOf('video') > -1;
4339 const res = {
4340 tempFiles: [],
4341 type: withImage && withVideo ? 'mix' : withImage ? 'image' : 'video',
4342 };
4343 if (count && typeof count !== 'number') {
4344 res.errMsg = getParameterError({
4345 para: 'count',
4346 correct: 'Number',
4347 wrong: count
4348 });
4349 return handle.fail(res);
4350 }
4351 let el = document.getElementById(mediaId);
4352 if (!el) {
4353 el = document.createElement('input');
4354 el.setAttribute('type', 'file');
4355 el.setAttribute('id', mediaId);
4356 el.setAttribute('style', 'position: fixed; top: -4000px; left: -3000px; z-index: -300;');
4357 }
4358 if (count > 1) {
4359 el.setAttribute('multiple', 'multiple');
4360 }
4361 else {
4362 el.removeAttribute('multiple');
4363 }
4364 // Note: Input 仅在移动端支持 capture 属性,可以使用 getUserMedia 替代(暂不考虑)
4365 if (isMobile()) {
4366 if (sourceType.length > 1 || sourceType.length < 1) {
4367 try {
4368 const { tapIndex } = yield showActionSheet({
4369 itemList: ['拍摄', '从相册选择'],
4370 }, methodName);
4371 sourceType.splice(0, sourceType.length, tapIndex === 0 ? 'camera' : 'album');
4372 }
4373 catch (e) {
4374 return handle.fail({
4375 errMsg: (_a = e.errMsg) === null || _a === void 0 ? void 0 : _a.replace('^.*:fail ', '')
4376 });
4377 }
4378 }
4379 }
4380 if (sourceType.includes('camera')) {
4381 el.setAttribute('capture', camera === 'front' ? 'user' : 'environment');
4382 }
4383 else {
4384 el.removeAttribute('capture');
4385 }
4386 if (res.type === 'image') {
4387 el.setAttribute('accept', 'image/*');
4388 }
4389 else if (res.type === 'video') {
4390 el.setAttribute('accept', 'video/*');
4391 }
4392 else {
4393 el.setAttribute('accept', 'image/*, video/*');
4394 }
4395 return new Promise((resolve, reject) => {
4396 if (!el)
4397 return;
4398 document.body.appendChild(el);
4399 el.onchange = function (e) {
4400 return __awaiter(this, void 0, void 0, function* () {
4401 const target = e.target;
4402 if (target) {
4403 const files = target.files || [];
4404 const arr = [...files];
4405 yield Promise.all(arr.map((item) => __awaiter(this, void 0, void 0, function* () {
4406 var _a;
4407 try {
4408 (_a = res.tempFiles) === null || _a === void 0 ? void 0 : _a.push(yield loadMedia(item));
4409 }
4410 catch (error) {
4411 console.error(error);
4412 }
4413 })));
4414 }
4415 handle.success(res, { resolve, reject });
4416 target.value = '';
4417 });
4418 };
4419 el.onabort = () => handle.fail({ errMsg: 'abort' }, { resolve, reject });
4420 el.oncancel = () => handle.fail({ errMsg: 'cancel' }, { resolve, reject });
4421 el.onerror = e => handle.fail({ errMsg: e.toString() }, { resolve, reject });
4422 el.click();
4423 }).finally(() => {
4424 if (!el)
4425 return;
4426 document.body.removeChild(el);
4427 });
4428 function loadMedia(file) {
4429 const dataUrl = URL.createObjectURL(file);
4430 const res = {
4431 tempFilePath: dataUrl,
4432 size: file.size,
4433 duration: 0,
4434 height: 0,
4435 width: 0,
4436 thumbTempFilePath: '',
4437 fileType: file.type,
4438 originalFileObj: file
4439 };
4440 if (/^video\//.test(res.fileType)) {
4441 // Video
4442 const video = document.createElement('video');
4443 const reader = new FileReader();
4444 video.crossOrigin = 'Anonymous';
4445 video.preload = 'metadata';
4446 video.src = res.tempFilePath;
4447 return new Promise((resolve, reject) => {
4448 // 对齐旧版本实现
4449 reader.onload = (event) => {
4450 var _a;
4451 res.tempFilePath = (_a = event.target) === null || _a === void 0 ? void 0 : _a.result;
4452 };
4453 reader.onerror = e => reject(e);
4454 reader.readAsDataURL(res.originalFileObj);
4455 video.onloadedmetadata = () => {
4456 res.duration = video.duration;
4457 res.height = video.videoHeight;
4458 res.width = video.videoWidth;
4459 };
4460 video.oncanplay = () => {
4461 res.thumbTempFilePath = getThumbTempFilePath(video, res.height, res.width, 0.8);
4462 resolve(res);
4463 };
4464 video.onerror = e => reject(e);
4465 });
4466 }
4467 else {
4468 // Image
4469 const img = new Image();
4470 /** 允许图片和 canvas 跨源使用
4471 * https://developer.mozilla.org/zh-CN/docs/Web/HTML/CORS_enabled_image
4472 */
4473 img.crossOrigin = 'Anonymous';
4474 img.src = res.tempFilePath;
4475 return new Promise((resolve, reject) => {
4476 if (img.complete) {
4477 res.height = img.height;
4478 res.width = img.width;
4479 res.thumbTempFilePath = getThumbTempFilePath(img, res.height, res.width, 0.8);
4480 resolve(res);
4481 }
4482 else {
4483 img.onload = () => {
4484 res.height = img.height;
4485 res.width = img.width;
4486 res.thumbTempFilePath = getThumbTempFilePath(img, res.height, res.width, 0.8);
4487 resolve(res);
4488 };
4489 img.onerror = e => reject(e);
4490 }
4491 });
4492 }
4493 }
4494 function getThumbTempFilePath(el, height = 0, width = height, quality = 0.8) {
4495 const max = 256;
4496 const canvas = document.createElement('canvas');
4497 if (height > max || width > max) {
4498 const radio = height / width;
4499 if (radio > 1) {
4500 height = max;
4501 width = height / radio;
4502 }
4503 else {
4504 width = max;
4505 height = width * radio;
4506 }
4507 }
4508 canvas.height = height;
4509 canvas.width = width;
4510 const ctx = canvas.getContext('2d');
4511 ctx === null || ctx === void 0 ? void 0 : ctx.drawImage(el, 0, 0, canvas.width, canvas.height);
4512 return canvas.toDataURL('image/jpeg', quality);
4513 }
4514 });
4515};
4516
4517/**
4518 * 从本地相册选择图片或使用相机拍照。
4519 * @deprecated 请使用 chooseMedia 接口
4520 */
4521const chooseImage = function (options) {
4522 // options must be an Object
4523 const isObject = shouldBeObject(options);
4524 if (!isObject.flag) {
4525 const res = { errMsg: `chooseImage:fail ${isObject.msg}` };
4526 console.error(res.errMsg);
4527 return Promise.reject(res);
4528 }
4529 let camera = 'back';
4530 const { sourceType = ['album', 'camera'], success, complete, fail } = options, args = __rest(options, ["sourceType", "success", "complete", "fail"]);
4531 if (sourceType.includes('camera') && sourceType.indexOf('user') > -1) {
4532 camera = 'front';
4533 }
4534 function parseRes(res) {
4535 const { tempFiles = [], errMsg } = res;
4536 return {
4537 tempFilePaths: tempFiles.map(item => item.tempFilePath),
4538 tempFiles: tempFiles.map(item => ({
4539 path: item.tempFilePath,
4540 size: item.size,
4541 type: item.fileType,
4542 originalFileObj: item.originalFileObj,
4543 })),
4544 errMsg,
4545 };
4546 }
4547 return chooseMedia(Object.assign(Object.assign({ mediaId: 'taroChooseImage' }, args), { sourceType: sourceType, mediaType: ['image'], camera, success: (res) => {
4548 const param = parseRes(res);
4549 success === null || success === void 0 ? void 0 : success(param);
4550 complete === null || complete === void 0 ? void 0 : complete(param);
4551 }, fail: (err) => {
4552 fail === null || fail === void 0 ? void 0 : fail(err);
4553 complete === null || complete === void 0 ? void 0 : complete(err);
4554 } }), 'chooseImage').then(parseRes);
4555};
4556
4557const previewMedia = /* @__PURE__ */ temporarilyNotSupport('previewMedia');
4558const compressImage = /* @__PURE__ */ temporarilyNotSupport('compressImage');
4559const chooseMessageFile = /* @__PURE__ */ permanentlyNotSupport('chooseMessageFile');
4560const editImage = /* @__PURE__ */ temporarilyNotSupport('editImage');
4561const cropImage = /* @__PURE__ */ temporarilyNotSupport('cropImage');
4562
4563// 实时音视频
4564const createLivePusherContext = /* @__PURE__ */ temporarilyNotSupport('createLivePusherContext');
4565const createLivePlayerContext = /* @__PURE__ */ temporarilyNotSupport('createLivePlayerContext');
4566
4567// 地图
4568const createMapContext = /* @__PURE__ */ temporarilyNotSupport('createMapContext');
4569
4570// 画面录制器
4571const createMediaRecorder = /* @__PURE__ */ temporarilyNotSupport('createMediaRecorder');
4572
4573// 录音
4574const stopRecord = /* @__PURE__ */ temporarilyNotSupport('stopRecord');
4575const startRecord = /* @__PURE__ */ temporarilyNotSupport('startRecord');
4576const getRecorderManager = /* @__PURE__ */ temporarilyNotSupport('getRecorderManager');
4577
4578const saveVideoToPhotosAlbum = (options) => {
4579 const methodName = 'saveVideoToPhotosAlbum';
4580 // options must be an Object
4581 const isObject = shouldBeObject(options);
4582 if (!isObject.flag) {
4583 const res = { errMsg: `${methodName}:fail ${isObject.msg}` };
4584 console.error(res.errMsg);
4585 return Promise.reject(res);
4586 }
4587 const { filePath, success, fail, complete, } = options;
4588 const handle = new MethodHandler({ name: methodName, success, fail, complete });
4589 if (typeof filePath !== 'string') {
4590 return handle.fail({
4591 errMsg: getParameterError({
4592 para: 'filePath',
4593 correct: 'String',
4594 wrong: filePath
4595 })
4596 });
4597 }
4598 createDownload(filePath);
4599 return handle.success();
4600};
4601
4602const getVideoInfo = function (options) {
4603 return __awaiter(this, void 0, void 0, function* () {
4604 // options must be an Object
4605 const isObject = shouldBeObject(options);
4606 if (!isObject.flag) {
4607 const res = { errMsg: `getVideoInfo:fail ${isObject.msg}` };
4608 console.error(res.errMsg);
4609 return Promise.reject(res);
4610 }
4611 const res = {
4612 orientation: 'up',
4613 type: '',
4614 duration: 0,
4615 size: 0,
4616 height: 0,
4617 width: 0,
4618 fps: 30,
4619 bitrate: 0,
4620 };
4621 const { src, success, fail, complete, } = options;
4622 const handle = new MethodHandler({ name: 'getVideoInfo', success, fail, complete });
4623 if (typeof src !== 'string') {
4624 res.errMsg = getParameterError({
4625 para: 'src',
4626 correct: 'String',
4627 wrong: src
4628 });
4629 return handle.fail(res);
4630 }
4631 const video = document.createElement('video');
4632 video.crossOrigin = 'Anonymous';
4633 video.preload = 'metadata';
4634 video.src = src;
4635 return new Promise((resolve, reject) => {
4636 video.onloadedmetadata = () => {
4637 res.duration = video.duration;
4638 res.height = video.videoHeight;
4639 res.width = video.videoWidth;
4640 fetch(src)
4641 .then((e) => __awaiter(this, void 0, void 0, function* () {
4642 const blob = yield e.blob();
4643 res.type = blob.type;
4644 res.size = blob.size;
4645 res.bitrate = blob.size / video.duration;
4646 handle.success(res, { resolve, reject });
4647 }))
4648 .catch(e => {
4649 handle.fail({
4650 errMsg: e.toString()
4651 }, { resolve, reject });
4652 });
4653 };
4654 });
4655 });
4656};
4657
4658/**
4659 * 拍摄视频或从手机相册中选视频。
4660 * @deprecated 请使用 chooseMedia 接口
4661 */
4662const chooseVideo = (options) => {
4663 // options must be an Object
4664 const isObject = shouldBeObject(options);
4665 if (!isObject.flag) {
4666 const res = { errMsg: `chooseVideo:fail ${isObject.msg}` };
4667 console.error(res.errMsg);
4668 return Promise.reject(res);
4669 }
4670 const { sourceType = ['album', 'camera'],
4671 // TODO 考虑通过 ffmpeg 支持压缩
4672 // compressed = true,
4673 maxDuration = 60, camera = 'back', success, fail, complete, } = options;
4674 function parseRes(res) {
4675 const { tempFiles = [], errMsg } = res;
4676 const [video] = tempFiles;
4677 return Object.assign(Object.assign({}, video), { errMsg });
4678 }
4679 return chooseMedia({
4680 mediaId: 'taroChooseVideo',
4681 sourceType,
4682 mediaType: ['video'],
4683 maxDuration,
4684 camera,
4685 success: (res) => {
4686 const param = parseRes(res);
4687 success === null || success === void 0 ? void 0 : success(param);
4688 complete === null || complete === void 0 ? void 0 : complete(param);
4689 },
4690 fail: (err) => {
4691 fail === null || fail === void 0 ? void 0 : fail(err);
4692 complete === null || complete === void 0 ? void 0 : complete(err);
4693 },
4694 }, 'chooseVideo').then(parseRes);
4695};
4696
4697const openVideoEditor = /* @__PURE__ */ temporarilyNotSupport('openVideoEditor');
4698/**
4699 * 创建 video 上下文 VideoContext 对象。
4700 */
4701const createVideoContext = (id, inst) => {
4702 const el = findDOM(inst);
4703 // TODO HTMLVideoElement to VideoContext
4704 return el === null || el === void 0 ? void 0 : el.querySelector(`taro-video-core[id=${id}]`);
4705};
4706const compressVideo = /* @__PURE__ */ temporarilyNotSupport('compressVideo');
4707
4708// 视频解码器
4709const createVideoDecoder = /* @__PURE__ */ temporarilyNotSupport('createVideoDecoder');
4710
4711// 音视频合成
4712const createMediaContainer = /* @__PURE__ */ temporarilyNotSupport('createMediaContainer');
4713
4714// 实时语音
4715const updateVoIPChatMuteConfig = /* @__PURE__ */ temporarilyNotSupport('updateVoIPChatMuteConfig');
4716const subscribeVoIPVideoMembers = /* @__PURE__ */ temporarilyNotSupport('subscribeVoIPVideoMembers');
4717const setEnable1v1Chat = /* @__PURE__ */ temporarilyNotSupport('setEnable1v1Chat');
4718const onVoIPVideoMembersChanged = /* @__PURE__ */ temporarilyNotSupport('onVoIPVideoMembersChanged');
4719const onVoIPChatStateChanged = /* @__PURE__ */ temporarilyNotSupport('onVoIPChatStateChanged');
4720const onVoIPChatSpeakersChanged = /* @__PURE__ */ temporarilyNotSupport('onVoIPChatSpeakersChanged');
4721const onVoIPChatMembersChanged = /* @__PURE__ */ temporarilyNotSupport('onVoIPChatMembersChanged');
4722const onVoIPChatInterrupted = /* @__PURE__ */ temporarilyNotSupport('onVoIPChatInterrupted');
4723const offVoIPChatSpeakersChanged = /* @__PURE__ */ temporarilyNotSupport('offVoIPChatSpeakersChanged');
4724const offVoIPVideoMembersChanged = /* @__PURE__ */ temporarilyNotSupport('offVoIPVideoMembersChanged');
4725const offVoIPChatStateChanged = /* @__PURE__ */ temporarilyNotSupport('offVoIPChatStateChanged');
4726const offVoIPChatMembersChanged = /* @__PURE__ */ temporarilyNotSupport('offVoIPChatMembersChanged');
4727const offVoIPChatInterrupted = /* @__PURE__ */ temporarilyNotSupport('offVoIPChatInterrupted');
4728const joinVoIPChat = /* @__PURE__ */ temporarilyNotSupport('joinVoIPChat');
4729const join1v1Chat = /* @__PURE__ */ temporarilyNotSupport('join1v1Chat');
4730const exitVoIPChat = /* @__PURE__ */ temporarilyNotSupport('exitVoIPChat');
4731
4732// 跳转
4733const openEmbeddedMiniProgram = /* @__PURE__ */ temporarilyNotSupport('openEmbeddedMiniProgram');
4734const navigateToMiniProgram = /* @__PURE__ */ temporarilyNotSupport('navigateToMiniProgram');
4735const navigateBackMiniProgram = /* @__PURE__ */ temporarilyNotSupport('navigateBackMiniProgram');
4736const exitMiniProgram = /* @__PURE__ */ temporarilyNotSupport('exitMiniProgram');
4737const openBusinessView = /* @__PURE__ */ temporarilyNotSupport('openBusinessView');
4738
4739/**
4740 * HTTP Response Header 事件回调函数的参数
4741 * @typedef {Object} HeadersReceivedParam
4742 * @property {Object} header 开发者服务器返回的 HTTP Response Header
4743 */
4744/**
4745 * HTTP Response Header 事件的回调函数
4746 * @callback HeadersReceivedCallback
4747 * @param {HeadersReceivedParam} res 参数
4748 */
4749/**
4750 * 进度变化回调函数的参数
4751 * @typedef {Object} ProgressUpdateParam
4752 * @property {number} progress 进度百分比
4753 * @property {number} [totalBytesWritten] 已经下载的数据长度,单位 Bytes
4754 * @property {number} [totalBytesSent] 已经上传的数据长度,单位 Bytes
4755 * @property {number} [totalBytesExpectedToWrite] 预期需要下载的数据总长度,单位 Bytes
4756 * @property {number} [totalBytesExpectedToSend] 预期需要上传的数据总长度,单位 Bytes
4757 */
4758/**
4759 * 进度变化事件的回调函数
4760 * @callback ProgressUpdateCallback
4761 * @param {ProgressUpdateParam} res 参数
4762 */
4763const NETWORK_TIMEOUT = 60000;
4764const XHR_STATS = {
4765 UNSENT: 0,
4766 OPENED: 1,
4767 HEADERS_RECEIVED: 2,
4768 LOADING: 3,
4769 DONE: 4 // The operation is complete.
4770};
4771/**
4772 * 设置xhr的header
4773 * @param {XMLHttpRequest} xhr
4774 * @param {Object} header
4775 */
4776const setHeader = (xhr, header) => {
4777 let headerKey;
4778 for (headerKey in header) {
4779 xhr.setRequestHeader(headerKey, header[headerKey]);
4780 }
4781};
4782/**
4783 * 将 blob url 转化为文件
4784 * @param {string} url 要转换的 blob url
4785 * @returns {Promise<File>}
4786 */
4787const convertObjectUrlToBlob = url => {
4788 return new Promise((resolve, reject) => {
4789 const xhr = new XMLHttpRequest();
4790 xhr.open('GET', url, true);
4791 xhr.responseType = 'blob';
4792 xhr.withCredentials = true;
4793 xhr.onload = function () {
4794 if (this.status === 200) {
4795 resolve(this.response);
4796 }
4797 else {
4798 /* eslint-disable prefer-promise-reject-errors */
4799 reject({ status: this.status });
4800 }
4801 };
4802 xhr.send();
4803 });
4804};
4805
4806const createDownloadTask = ({ url, header, withCredentials = true, timeout, success, error }) => {
4807 let timeoutInter;
4808 const apiName = 'downloadFile';
4809 const xhr = new XMLHttpRequest();
4810 const callbackManager = {
4811 headersReceived: new CallbackManager(),
4812 progressUpdate: new CallbackManager()
4813 };
4814 xhr.open('GET', url, true);
4815 xhr.withCredentials = !!withCredentials;
4816 xhr.responseType = 'blob';
4817 setHeader(xhr, header);
4818 xhr.onprogress = e => {
4819 const { loaded, total } = e;
4820 callbackManager.progressUpdate.trigger({
4821 progress: Math.round(loaded / total * 100),
4822 totalBytesWritten: loaded,
4823 totalBytesExpectedToWrite: total
4824 });
4825 };
4826 xhr.onreadystatechange = () => {
4827 if (xhr.readyState !== XHR_STATS.HEADERS_RECEIVED)
4828 return;
4829 callbackManager.headersReceived.trigger({
4830 header: xhr.getAllResponseHeaders()
4831 });
4832 };
4833 xhr.onload = () => {
4834 const response = xhr.response;
4835 const status = xhr.status;
4836 success({
4837 errMsg: `${apiName}:ok`,
4838 statusCode: status,
4839 tempFilePath: window.URL.createObjectURL(response)
4840 });
4841 };
4842 xhr.onabort = () => {
4843 clearTimeout(timeoutInter);
4844 error({
4845 errMsg: `${apiName}:fail abort`
4846 });
4847 };
4848 xhr.onerror = (e) => {
4849 error({
4850 errMsg: `${apiName}:fail ${e.message}`
4851 });
4852 };
4853 /**
4854 * 中断任务
4855 */
4856 const abort = () => {
4857 xhr.abort();
4858 };
4859 const send = () => {
4860 xhr.send();
4861 timeoutInter = setTimeout(() => {
4862 xhr.onabort = null;
4863 xhr.onload = null;
4864 xhr.onprogress = null;
4865 xhr.onreadystatechange = null;
4866 xhr.onerror = null;
4867 abort();
4868 error({
4869 errMsg: `${apiName}:fail timeout`
4870 });
4871 }, timeout || NETWORK_TIMEOUT);
4872 };
4873 send();
4874 /**
4875 * 监听 HTTP Response Header 事件。会比请求完成事件更早
4876 * @param {HeadersReceivedCallback} callback HTTP Response Header 事件的回调函数
4877 */
4878 const onHeadersReceived = callbackManager.headersReceived.add;
4879 /**
4880 * 取消监听 HTTP Response Header 事件
4881 * @param {HeadersReceivedCallback} callback HTTP Response Header 事件的回调函数
4882 */
4883 const offHeadersReceived = callbackManager.headersReceived.remove;
4884 /**
4885 * 监听进度变化事件
4886 * @param {ProgressUpdateCallback} callback HTTP Response Header 事件的回调函数
4887 */
4888 const onProgressUpdate = callbackManager.progressUpdate.add;
4889 /**
4890 * 取消监听进度变化事件
4891 * @param {ProgressUpdateCallback} callback HTTP Response Header 事件的回调函数
4892 */
4893 const offProgressUpdate = callbackManager.progressUpdate.remove;
4894 return {
4895 abort,
4896 onHeadersReceived,
4897 offHeadersReceived,
4898 onProgressUpdate,
4899 offProgressUpdate
4900 };
4901};
4902/**
4903 * 下载文件资源到本地。客户端直接发起一个 HTTPS GET 请求,返回文件的本地临时路径。使用前请注意阅读相关说明。
4904 * 注意:请在服务端响应的 header 中指定合理的 Content-Type 字段,以保证客户端正确处理文件类型。
4905 */
4906const downloadFile = ({ url, header, withCredentials, timeout, success, fail, complete }) => {
4907 let task;
4908 const result = new Promise((resolve, reject) => {
4909 task = createDownloadTask({
4910 url,
4911 header,
4912 withCredentials,
4913 timeout,
4914 success: res => {
4915 success && success(res);
4916 complete && complete(res);
4917 resolve(res);
4918 },
4919 error: res => {
4920 fail && fail(res);
4921 complete && complete(res);
4922 reject(res);
4923 }
4924 });
4925 });
4926 result.headersReceive = task.onHeadersReceived.bind(task);
4927 result.progress = task.onProgressUpdate.bind(task);
4928 const properties = {};
4929 Object.keys(task).forEach(key => {
4930 properties[key] = {
4931 get() {
4932 return typeof task[key] === 'function' ? task[key].bind(task) : task[key];
4933 }
4934 };
4935 });
4936 return Object.defineProperties(result, properties);
4937};
4938
4939// mDNS
4940const stopLocalServiceDiscovery = /* @__PURE__ */ temporarilyNotSupport('stopLocalServiceDiscovery');
4941const startLocalServiceDiscovery = /* @__PURE__ */ temporarilyNotSupport('startLocalServiceDiscovery');
4942const onLocalServiceResolveFail = /* @__PURE__ */ temporarilyNotSupport('onLocalServiceResolveFail');
4943const onLocalServiceLost = /* @__PURE__ */ temporarilyNotSupport('onLocalServiceLost');
4944const onLocalServiceFound = /* @__PURE__ */ temporarilyNotSupport('onLocalServiceFound');
4945const onLocalServiceDiscoveryStop = /* @__PURE__ */ temporarilyNotSupport('onLocalServiceDiscoveryStop');
4946const offLocalServiceResolveFail = /* @__PURE__ */ temporarilyNotSupport('offLocalServiceResolveFail');
4947const offLocalServiceLost = /* @__PURE__ */ temporarilyNotSupport('offLocalServiceLost');
4948const offLocalServiceFound = /* @__PURE__ */ temporarilyNotSupport('offLocalServiceFound');
4949const offLocalServiceDiscoveryStop = /* @__PURE__ */ temporarilyNotSupport('offLocalServiceDiscoveryStop');
4950
4951// @ts-ignore
4952const { Link: Link$1 } = Taro;
4953function generateRequestUrlWithParams(url = '', params) {
4954 params = typeof params === 'string' ? params : serializeParams(params);
4955 if (params) {
4956 url += (~url.indexOf('?') ? '&' : '?') + params;
4957 }
4958 url = url.replace('?&', '?');
4959 return url;
4960}
4961function _request(options = {}) {
4962 const { success, complete, fail } = options;
4963 const params = {};
4964 const res = {};
4965 let { cache = 'default', credentials, data, dataType, header = {}, jsonp, method = 'GET', mode, responseType, signal, timeout, url = '' } = options, opts = __rest(options, ["cache", "credentials", "data", "dataType", "header", "jsonp", "method", "mode", "responseType", "signal", "timeout", "url"]);
4966 if (typeof timeout !== 'number') {
4967 timeout = NETWORK_TIMEOUT;
4968 }
4969 Object.assign(params, opts);
4970 if (jsonp) {
4971 // @ts-ignore
4972 params.params = data;
4973 params.cache = opts.jsonpCache;
4974 // @ts-ignore
4975 params.timeout = timeout;
4976 if (typeof jsonp === 'string') {
4977 // @ts-ignore
4978 params.name = jsonp;
4979 }
4980 // Note: https://github.com/luckyadam/jsonp-retry
4981 return jsonpRetry(url, params)
4982 .then(data => {
4983 res.statusCode = 200;
4984 res.data = data;
4985 isFunction(success) && success(res);
4986 isFunction(complete) && complete(res);
4987 return res;
4988 })
4989 .catch(err => {
4990 isFunction(fail) && fail(err);
4991 isFunction(complete) && complete(res);
4992 return Promise.reject(err);
4993 });
4994 }
4995 params.method = method;
4996 const methodUpper = params.method.toUpperCase();
4997 params.cache = cache;
4998 if (methodUpper === 'GET' || methodUpper === 'HEAD') {
4999 url = generateRequestUrlWithParams(url, data);
5000 }
5001 else if (['[object Array]', '[object Object]'].indexOf(Object.prototype.toString.call(data)) >= 0) {
5002 const keyOfContentType = Object.keys(header).find(item => item.toLowerCase() === 'content-type');
5003 if (!keyOfContentType) {
5004 header['Content-Type'] = 'application/json';
5005 }
5006 const contentType = header[keyOfContentType || 'Content-Type'];
5007 if (contentType.indexOf('application/json') >= 0) {
5008 params.body = JSON.stringify(data);
5009 }
5010 else if (contentType.indexOf('application/x-www-form-urlencoded') >= 0) {
5011 params.body = serializeParams(data);
5012 }
5013 else {
5014 params.body = data;
5015 }
5016 }
5017 else {
5018 params.body = data;
5019 }
5020 if (header) {
5021 params.headers = header;
5022 }
5023 if (mode) {
5024 params.mode = mode;
5025 }
5026 let timeoutTimer = null;
5027 let controller = null;
5028 if (signal) {
5029 params.signal = signal;
5030 }
5031 else {
5032 controller = new window.AbortController();
5033 params.signal = controller.signal;
5034 timeoutTimer = setTimeout(function () {
5035 if (controller)
5036 controller.abort();
5037 }, timeout);
5038 }
5039 params.credentials = credentials;
5040 const p = fetch(url, params)
5041 .then(response => {
5042 if (timeoutTimer) {
5043 clearTimeout(timeoutTimer);
5044 timeoutTimer = null;
5045 }
5046 if (controller) {
5047 controller = null;
5048 }
5049 if (!response) {
5050 const errorResponse = { ok: false };
5051 throw errorResponse;
5052 }
5053 res.statusCode = response.status;
5054 res.header = {};
5055 for (const key of response.headers.keys()) {
5056 res.header[key] = response.headers.get(key);
5057 }
5058 if (responseType === 'arraybuffer') {
5059 return response.arrayBuffer();
5060 }
5061 if (res.statusCode !== 204) {
5062 if (dataType === 'json' || typeof dataType === 'undefined') {
5063 return response.json().catch(() => {
5064 return null;
5065 });
5066 }
5067 }
5068 if (responseType === 'text' || dataType === 'text') {
5069 return response.text();
5070 }
5071 return Promise.resolve(null);
5072 })
5073 .then(data => {
5074 res.data = data;
5075 isFunction(success) && success(res);
5076 isFunction(complete) && complete(res);
5077 return res;
5078 })
5079 .catch(err => {
5080 if (timeoutTimer) {
5081 clearTimeout(timeoutTimer);
5082 timeoutTimer = null;
5083 }
5084 if (controller) {
5085 controller = null;
5086 }
5087 isFunction(fail) && fail(err);
5088 isFunction(complete) && complete(res);
5089 err.statusCode = res.statusCode;
5090 err.errMsg = err.message;
5091 return Promise.reject(err);
5092 });
5093 if (!p.abort && controller) {
5094 p.abort = cb => {
5095 if (controller) {
5096 cb && cb();
5097 controller.abort();
5098 if (timeoutTimer) {
5099 clearTimeout(timeoutTimer);
5100 timeoutTimer = null;
5101 }
5102 }
5103 };
5104 }
5105 return p;
5106}
5107function taroInterceptor(chain) {
5108 return _request(chain.requestParams);
5109}
5110const link = new Link$1(taroInterceptor);
5111const request = ((...args) => {
5112 const [url = '', options = {}] = args;
5113 if (typeof url === 'string') {
5114 options.url = url;
5115 }
5116 else {
5117 Object.assign(options, url);
5118 }
5119 return link.request(options);
5120});
5121const addInterceptor = link.addInterceptor.bind(link);
5122const cleanInterceptors = link.cleanInterceptors.bind(link);
5123
5124// TCP 通信
5125const createTCPSocket = /* @__PURE__ */ temporarilyNotSupport('createTCPSocket');
5126
5127// UDP 通信
5128const createUDPSocket = /* @__PURE__ */ temporarilyNotSupport('createUDPSocket');
5129
5130const createUploadTask = ({ url, filePath, formData = {}, name, header, timeout, fileName, withCredentials = true, success, error }) => {
5131 let timeoutInter;
5132 let formKey;
5133 const apiName = 'uploadFile';
5134 const xhr = new XMLHttpRequest();
5135 const form = new FormData();
5136 const callbackManager = {
5137 headersReceived: new CallbackManager(),
5138 progressUpdate: new CallbackManager()
5139 };
5140 xhr.open('POST', url);
5141 xhr.withCredentials = !!withCredentials;
5142 setHeader(xhr, header);
5143 for (formKey in formData) {
5144 form.append(formKey, formData[formKey]);
5145 }
5146 xhr.upload.onprogress = e => {
5147 const { loaded, total } = e;
5148 callbackManager.progressUpdate.trigger({
5149 progress: Math.round(loaded / total * 100),
5150 totalBytesSent: loaded,
5151 totalBytesExpectedToSend: total
5152 });
5153 };
5154 xhr.onreadystatechange = () => {
5155 if (xhr.readyState !== XHR_STATS.HEADERS_RECEIVED)
5156 return;
5157 callbackManager.headersReceived.trigger({
5158 header: xhr.getAllResponseHeaders()
5159 });
5160 };
5161 xhr.onload = () => {
5162 const status = xhr.status;
5163 clearTimeout(timeoutInter);
5164 success({
5165 errMsg: `${apiName}:ok`,
5166 statusCode: status,
5167 data: xhr.responseText || xhr.response
5168 });
5169 };
5170 xhr.onabort = () => {
5171 clearTimeout(timeoutInter);
5172 error({
5173 errMsg: `${apiName}:fail abort`
5174 });
5175 };
5176 xhr.onerror = (e) => {
5177 clearTimeout(timeoutInter);
5178 error({
5179 errMsg: `${apiName}:fail ${e.message}`
5180 });
5181 };
5182 /**
5183 * 中断任务
5184 */
5185 const abort = () => {
5186 clearTimeout(timeoutInter);
5187 xhr.abort();
5188 };
5189 const send = () => {
5190 xhr.send(form);
5191 timeoutInter = setTimeout(() => {
5192 xhr.onabort = null;
5193 xhr.onload = null;
5194 xhr.upload.onprogress = null;
5195 xhr.onreadystatechange = null;
5196 xhr.onerror = null;
5197 abort();
5198 error({
5199 errMsg: `${apiName}:fail timeout`
5200 });
5201 }, timeout || NETWORK_TIMEOUT);
5202 };
5203 convertObjectUrlToBlob(filePath)
5204 .then((fileObj) => {
5205 if (!fileName) {
5206 fileName = typeof fileObj !== 'string' && fileObj.name;
5207 }
5208 form.append(name, fileObj, fileName || `file-${Date.now()}`);
5209 send();
5210 })
5211 .catch(e => {
5212 error({
5213 errMsg: `${apiName}:fail ${e.message}`
5214 });
5215 });
5216 /**
5217 * 监听 HTTP Response Header 事件。会比请求完成事件更早
5218 * @param {HeadersReceivedCallback} callback HTTP Response Header 事件的回调函数
5219 */
5220 const onHeadersReceived = callbackManager.headersReceived.add;
5221 /**
5222 * 取消监听 HTTP Response Header 事件
5223 * @param {HeadersReceivedCallback} callback HTTP Response Header 事件的回调函数
5224 */
5225 const offHeadersReceived = callbackManager.headersReceived.remove;
5226 /**
5227 * 监听进度变化事件
5228 * @param {ProgressUpdateCallback} callback HTTP Response Header 事件的回调函数
5229 */
5230 const onProgressUpdate = callbackManager.progressUpdate.add;
5231 /**
5232 * 取消监听进度变化事件
5233 * @param {ProgressUpdateCallback} callback HTTP Response Header 事件的回调函数
5234 */
5235 const offProgressUpdate = callbackManager.progressUpdate.remove;
5236 return {
5237 abort,
5238 onHeadersReceived,
5239 offHeadersReceived,
5240 onProgressUpdate,
5241 offProgressUpdate
5242 };
5243};
5244/**
5245 * 将本地资源上传到服务器。客户端发起一个 HTTPS POST 请求,其中 content-type 为 multipart/form-data。使用前请注意阅读相关说明。
5246 */
5247const uploadFile = ({ url, filePath, name, header, formData, timeout, fileName, withCredentials, success, fail, complete }) => {
5248 let task;
5249 const result = new Promise((resolve, reject) => {
5250 task = createUploadTask({
5251 url,
5252 header,
5253 name,
5254 filePath,
5255 formData,
5256 timeout,
5257 fileName,
5258 withCredentials,
5259 success: res => {
5260 success && success(res);
5261 complete && complete(res);
5262 resolve(res);
5263 },
5264 error: res => {
5265 fail && fail(res);
5266 complete && complete(res);
5267 reject(res);
5268 }
5269 });
5270 });
5271 result.headersReceive = task.onHeadersReceived.bind(task);
5272 result.progress = task.onProgressUpdate.bind(task);
5273 const properties = {};
5274 Object.keys(task).forEach(key => {
5275 properties[key] = {
5276 get() {
5277 return typeof task[key] === 'function' ? task[key].bind(task) : task[key];
5278 }
5279 };
5280 });
5281 return Object.defineProperties(result, properties);
5282};
5283
5284class SocketTask {
5285 constructor(url, protocols) {
5286 if (protocols && protocols.length) {
5287 this.ws = new WebSocket(url, protocols);
5288 }
5289 else {
5290 this.ws = new WebSocket(url);
5291 }
5292 this.CONNECTING = 0;
5293 this.OPEN = 1;
5294 this.CLOSING = 2;
5295 this.CLOSED = 3;
5296 }
5297 get readyState() {
5298 return this.ws.readyState;
5299 }
5300 send(opts = {}) {
5301 if (typeof opts !== 'object' || !opts)
5302 opts = {};
5303 const { data = '', success, fail, complete } = opts;
5304 if (this.readyState !== 1) {
5305 const res = { errMsg: 'SocketTask.send:fail SocketTask.readState is not OPEN' };
5306 console.error(res.errMsg);
5307 isFunction(fail) && fail(res);
5308 isFunction(complete) && complete(res);
5309 return Promise.reject(res);
5310 }
5311 this.ws.send(data);
5312 const res = { errMsg: 'sendSocketMessage:ok' };
5313 isFunction(success) && success(res);
5314 isFunction(complete) && complete(res);
5315 return Promise.resolve(res);
5316 }
5317 close(opts = {}) {
5318 if (typeof opts !== 'object' || !opts)
5319 opts = {};
5320 const { code = 1000, reason = 'server complete,close', success, complete } = opts;
5321 this.closeDetail = { code, reason };
5322 // 主动断开时需要重置链接数
5323 this._destroyWhenClose && this._destroyWhenClose();
5324 this.ws.close();
5325 const res = { errMsg: 'closeSocket:ok' };
5326 isFunction(success) && success(res);
5327 isFunction(complete) && complete(res);
5328 return Promise.resolve(res);
5329 }
5330 onOpen(func) {
5331 this.ws.onopen = func;
5332 }
5333 onMessage(func) {
5334 this.ws.onmessage = func;
5335 }
5336 onClose(func) {
5337 this.ws.onclose = () => {
5338 // 若服务器方断掉也需要重置链接数
5339 this._destroyWhenClose && this._destroyWhenClose();
5340 func(this.closeDetail || { code: 1006, reason: 'abnormal closure' });
5341 };
5342 }
5343 onError(func) {
5344 this.ws.onerror = func;
5345 }
5346}
5347
5348let socketTasks = [];
5349let socketsCounter = 1;
5350function sendSocketMessage() {
5351 console.warn('Deprecated.Please use socketTask.send instead.');
5352}
5353function onSocketOpen() {
5354 console.warn('Deprecated.Please use socketTask.onOpen instead.');
5355}
5356function onSocketMessage() {
5357 console.warn('Deprecated.Please use socketTask.onMessage instead.');
5358}
5359function onSocketError() {
5360 console.warn('Deprecated.Please use socketTask.onError instead.');
5361}
5362function onSocketClose() {
5363 console.warn('Deprecated.Please use socketTask.onClose instead.');
5364}
5365function connectSocket(options) {
5366 const name = 'connectSocket';
5367 return new Promise((resolve, reject) => {
5368 // options must be an Object
5369 const isObject = shouldBeObject(options);
5370 if (!isObject.flag) {
5371 const res = { errMsg: `${name}:fail ${isObject.msg}` };
5372 console.error(res.errMsg);
5373 return reject(res);
5374 }
5375 const { url, protocols, success, fail, complete } = options;
5376 const handle = new MethodHandler({ name, success, fail, complete });
5377 // options.url must be String
5378 if (typeof url !== 'string') {
5379 return handle.fail({
5380 errMsg: getParameterError({
5381 para: 'url',
5382 correct: 'String',
5383 wrong: url
5384 })
5385 }, { resolve, reject });
5386 }
5387 // options.url must be invalid
5388 if (!url.startsWith('ws://') && !url.startsWith('wss://')) {
5389 return handle.fail({
5390 errMsg: `request:fail invalid url "${url}"`
5391 }, { resolve, reject });
5392 }
5393 // protocols must be array
5394 const _protocols = Array.isArray(protocols) ? protocols : null;
5395 // 2 connection at most
5396 if (socketTasks.length >= 5) {
5397 return handle.fail({
5398 errMsg: '同时最多发起 5 个 socket 请求,更多请参考文档。'
5399 }, { resolve, reject });
5400 }
5401 const task = new SocketTask(url, _protocols);
5402 task._destroyWhenClose = function () {
5403 socketTasks = socketTasks.filter(socketTask => socketTask !== this);
5404 };
5405 socketTasks.push(task);
5406 handle.success({
5407 socketTaskId: socketsCounter++
5408 });
5409 return resolve(task);
5410 });
5411}
5412function closeSocket() {
5413 console.warn('Deprecated.Please use socketTask.close instead.');
5414}
5415
5416// 帐号信息
5417const getAccountInfoSync = /* @__PURE__ */ temporarilyNotSupport('getAccountInfoSync');
5418
5419// 收货地址
5420const chooseAddress = /* @__PURE__ */ temporarilyNotSupport('chooseAddress');
5421
5422// 授权
5423const authorizeForMiniProgram = /* @__PURE__ */ temporarilyNotSupport('authorizeForMiniProgram');
5424const authorize = /* @__PURE__ */ temporarilyNotSupport('authorize');
5425
5426// 卡券
5427const openCard = /* @__PURE__ */ temporarilyNotSupport('openCard');
5428const addCard = /* @__PURE__ */ temporarilyNotSupport('addCard');
5429
5430// 视频号
5431const reserveChannelsLive = /* @__PURE__ */ temporarilyNotSupport('reserveChannelsLive');
5432const openChannelsUserProfile = /* @__PURE__ */ temporarilyNotSupport('openChannelsUserProfile');
5433const openChannelsLive = /* @__PURE__ */ temporarilyNotSupport('openChannelsLive');
5434const openChannelsEvent = /* @__PURE__ */ temporarilyNotSupport('openChannelsEvent');
5435const openChannelsActivity = /* @__PURE__ */ temporarilyNotSupport('openChannelsActivity');
5436const getChannelsShareKey = /* @__PURE__ */ temporarilyNotSupport('getChannelsShareKey');
5437const getChannelsLiveNoticeInfo = /* @__PURE__ */ temporarilyNotSupport('getChannelsLiveNoticeInfo');
5438const getChannelsLiveInfo = /* @__PURE__ */ temporarilyNotSupport('getChannelsLiveInfo');
5439
5440// 微信客服
5441const openCustomerServiceChat = /* @__PURE__ */ temporarilyNotSupport('openCustomerServiceChat');
5442
5443// 设备(组)音视频通话
5444const requestDeviceVoIP = /* @__PURE__ */ temporarilyNotSupport('requestDeviceVoIP');
5445const getDeviceVoIPList = /* @__PURE__ */ temporarilyNotSupport('getDeviceVoIPList');
5446
5447// 过往接口
5448const checkIsSupportFacialRecognition = /* @__PURE__ */ temporarilyNotSupport('checkIsSupportFacialRecognition');
5449const startFacialRecognitionVerify = /* @__PURE__ */ temporarilyNotSupport('startFacialRecognitionVerify');
5450const startFacialRecognitionVerifyAndUploadVideo = /* @__PURE__ */ temporarilyNotSupport('startFacialRecognitionVerifyAndUploadVideo');
5451const faceVerifyForPay = /* @__PURE__ */ temporarilyNotSupport('faceVerifyForPay');
5452
5453// 收藏
5454const addVideoToFavorites = /* @__PURE__ */ temporarilyNotSupport('addVideoToFavorites');
5455const addFileToFavorites = /* @__PURE__ */ temporarilyNotSupport('addFileToFavorites');
5456
5457// 微信群
5458const getGroupEnterInfo = /* @__PURE__ */ temporarilyNotSupport('getGroupEnterInfo');
5459
5460// 发票
5461const chooseInvoiceTitle = /* @__PURE__ */ temporarilyNotSupport('chooseInvoiceTitle');
5462const chooseInvoice = /* @__PURE__ */ temporarilyNotSupport('chooseInvoice');
5463
5464// 车牌
5465const chooseLicensePlate = /* @__PURE__ */ temporarilyNotSupport('chooseLicensePlate');
5466
5467// 帐号信息
5468const pluginLogin = /* @__PURE__ */ temporarilyNotSupport('pluginLogin');
5469const login = /* @__PURE__ */ temporarilyNotSupport('login');
5470const checkSession = /* @__PURE__ */ temporarilyNotSupport('checkSession');
5471
5472// 我的小程序
5473const checkIsAddedToMyMiniProgram = /* @__PURE__ */ temporarilyNotSupport('checkIsAddedToMyMiniProgram');
5474
5475// 隐私信息授权
5476const requirePrivacyAuthorize = /* @__PURE__ */ temporarilyNotSupport('requirePrivacyAuthorize');
5477const openPrivacyContract = /* @__PURE__ */ temporarilyNotSupport('openPrivacyContract');
5478const onNeedPrivacyAuthorization = /* @__PURE__ */ temporarilyNotSupport('onNeedPrivacyAuthorization');
5479const getPrivacySetting = /* @__PURE__ */ temporarilyNotSupport('getPrivacySetting');
5480
5481// 微信红包
5482const showRedPackage = /* @__PURE__ */ temporarilyNotSupport('showRedPackage');
5483
5484// 设置
5485const openSetting = /* @__PURE__ */ temporarilyNotSupport('openSetting');
5486const getSetting = /* @__PURE__ */ temporarilyNotSupport('getSetting');
5487
5488// 生物认证
5489const startSoterAuthentication = /* @__PURE__ */ temporarilyNotSupport('startSoterAuthentication');
5490const checkIsSupportSoterAuthentication = /* @__PURE__ */ temporarilyNotSupport('checkIsSupportSoterAuthentication');
5491const checkIsSoterEnrolledInDevice = /* @__PURE__ */ temporarilyNotSupport('checkIsSoterEnrolledInDevice');
5492
5493// 订阅消息
5494const requestSubscribeMessage = /* @__PURE__ */ temporarilyNotSupport('requestSubscribeMessage');
5495// 订阅设备消息
5496const requestSubscribeDeviceMessage = /* @__PURE__ */ temporarilyNotSupport('requestSubscribeDeviceMessage');
5497
5498// 用户信息
5499const getUserProfile = /* @__PURE__ */ temporarilyNotSupport('getUserProfile');
5500const getUserInfo = /* @__PURE__ */ temporarilyNotSupport('getUserInfo');
5501
5502// 微信运动
5503const shareToWeRun = /* @__PURE__ */ temporarilyNotSupport('shareToWeRun');
5504const getWeRunData = /* @__PURE__ */ temporarilyNotSupport('getWeRunData');
5505
5506// 支付
5507const requestPayment = /* @__PURE__ */ temporarilyNotSupport('requestPayment');
5508const requestPluginPayment = /* @__PURE__ */ temporarilyNotSupport('requestPluginPayment');
5509const requestOrderPayment = /* @__PURE__ */ temporarilyNotSupport('requestOrderPayment');
5510
5511// 打开手Q说说发表界面
5512const openQzonePublish = /* @__PURE__ */ temporarilyNotSupport('openQzonePublish');
5513const getQQRunData = /* @__PURE__ */ temporarilyNotSupport('getQQRunData');
5514const setOfficialDress = /* @__PURE__ */ temporarilyNotSupport('setOfficialDress');
5515const setCustomDress = /* @__PURE__ */ temporarilyNotSupport('setCustomDress');
5516const updateQQApp = /* @__PURE__ */ temporarilyNotSupport('updateQQApp');
5517const addRecentColorSign = /* @__PURE__ */ temporarilyNotSupport('addRecentColorSign');
5518const getGuildInfo = /* @__PURE__ */ temporarilyNotSupport('getGuildInfo');
5519const applyAddToMyApps = /* @__PURE__ */ temporarilyNotSupport('applyAddToMyApps');
5520const isAddedToMyApps = /* @__PURE__ */ temporarilyNotSupport('isAddedToMyApps');
5521
5522// 路由
5523// FIXME 方法导出类型未对齐,后续修复
5524
5525// 转发
5526/** 更新转发属性 */
5527const updateShareMenu = /* @__PURE__ */ temporarilyNotSupport('updateShareMenu');
5528/** 显示当前页面的转发按钮 */
5529const showShareMenu = /* @__PURE__ */ temporarilyNotSupport('showShareMenu');
5530/** 打开分享图片弹窗,可以将图片发送给朋友、收藏或下载 */
5531const showShareImageMenu = /* @__PURE__ */ temporarilyNotSupport('showShareImageMenu');
5532/** 转发视频到聊天 */
5533const shareVideoMessage = /* @__PURE__ */ temporarilyNotSupport('shareVideoMessage');
5534/** 转发文件到聊天 */
5535const shareFileMessage = /* @__PURE__ */ temporarilyNotSupport('shareFileMessage');
5536/** 监听用户点击右上角菜单的「复制链接」按钮时触发的事件 */
5537const onCopyUrl = /* @__PURE__ */ temporarilyNotSupport('onCopyUrl');
5538/** 移除用户点击右上角菜单的「复制链接」按钮时触发的事件的监听函数 */
5539const offCopyUrl = /* @__PURE__ */ temporarilyNotSupport('offCopyUrl');
5540/** 隐藏当前页面的转发按钮 */
5541const hideShareMenu = /* @__PURE__ */ temporarilyNotSupport('hideShareMenu');
5542/** 获取转发详细信息 */
5543const getShareInfo = /* @__PURE__ */ temporarilyNotSupport('getShareInfo');
5544/** 验证私密消息。 */
5545const authPrivateMessage = /* @__PURE__ */ permanentlyNotSupport('authPrivateMessage');
5546
5547const setPageInfo = /* @__PURE__ */ temporarilyNotSupport('setPageInfo');
5548// 百度小程序 AI 相关
5549const ocrIdCard = /* @__PURE__ */ temporarilyNotSupport('ocrIdCard');
5550const ocrBankCard = /* @__PURE__ */ temporarilyNotSupport('ocrBankCard');
5551const ocrDrivingLicense = /* @__PURE__ */ temporarilyNotSupport('ocrDrivingLicense');
5552const ocrVehicleLicense = /* @__PURE__ */ temporarilyNotSupport('ocrVehicleLicense');
5553const textReview = /* @__PURE__ */ temporarilyNotSupport('textReview');
5554const textToAudio = /* @__PURE__ */ temporarilyNotSupport('textToAudio');
5555const imageAudit = /* @__PURE__ */ temporarilyNotSupport('imageAudit');
5556const advancedGeneralIdentify = /* @__PURE__ */ temporarilyNotSupport('advancedGeneralIdentify');
5557const objectDetectIdentify = /* @__PURE__ */ temporarilyNotSupport('objectDetectIdentify');
5558const carClassify = /* @__PURE__ */ temporarilyNotSupport('carClassify');
5559const dishClassify = /* @__PURE__ */ temporarilyNotSupport('dishClassify');
5560const logoClassify = /* @__PURE__ */ temporarilyNotSupport('logoClassify');
5561const animalClassify = /* @__PURE__ */ temporarilyNotSupport('animalClassify');
5562const plantClassify = /* @__PURE__ */ temporarilyNotSupport('plantClassify');
5563// 用户信息
5564const getSwanId = /* @__PURE__ */ temporarilyNotSupport('getSwanId');
5565// 百度收银台支付
5566const requestPolymerPayment = /* @__PURE__ */ temporarilyNotSupport('requestPolymerPayment');
5567// 打开小程序
5568const navigateToSmartGameProgram = /* @__PURE__ */ temporarilyNotSupport('navigateToSmartGameProgram');
5569const navigateToSmartProgram = /* @__PURE__ */ temporarilyNotSupport('navigateToSmartProgram');
5570const navigateBackSmartProgram = /* @__PURE__ */ temporarilyNotSupport('navigateBackSmartProgram');
5571const preloadSubPackage = /* @__PURE__ */ temporarilyNotSupport('preloadSubPackage');
5572
5573// Worker
5574const createWorker = /* @__PURE__ */ temporarilyNotSupport('createWorker');
5575
5576class TaroH5IntersectionObserver {
5577 // selector 的容器节点
5578 get container() {
5579 const container = (this._component !== null
5580 ? (findDOM(this._component) || document)
5581 : document);
5582 return container;
5583 }
5584 constructor(component, options = {}) {
5585 // 选项
5586 this._options = {
5587 thresholds: [0],
5588 initialRatio: 0,
5589 observeAll: false
5590 };
5591 // 监控中的选择器
5592 this._listeners = [];
5593 // 用来扩展(或收缩)参照节点布局区域的边界
5594 this._rootMargin = {};
5595 // 是否已初始化
5596 this._isInited = false;
5597 this._component = component;
5598 Object.assign(this._options, options);
5599 }
5600 createInst() {
5601 // 去除原本的实例
5602 this.disconnect();
5603 const { left = 0, top = 0, bottom = 0, right = 0 } = this._rootMargin;
5604 return new IntersectionObserver(entries => {
5605 entries.forEach(entry => {
5606 const _callback = this._getCallbackByElement(entry.target);
5607 const result = {
5608 boundingClientRect: entry.boundingClientRect,
5609 intersectionRatio: entry.intersectionRatio,
5610 intersectionRect: entry.intersectionRect,
5611 relativeRect: entry.rootBounds || { left: 0, right: 0, top: 0, bottom: 0 },
5612 // 使用时间戳而不是entry.time,跟微信小程序一致
5613 time: Date.now(),
5614 };
5615 // web端会默认首次触发
5616 if (!this._isInited && this._options.initialRatio <= Math.min.apply(Math, this._options.thresholds)) {
5617 // 初始的相交比例,如果调用时检测到的相交比例与这个值不相等且达到阈值,则会触发一次监听器的回调函数。
5618 return;
5619 }
5620 _callback && _callback.call(this, result);
5621 });
5622 this._isInited = true;
5623 }, {
5624 root: this._root,
5625 rootMargin: [`${top}px`, `${right}px`, `${bottom}px`, `${left}px`].join(' '),
5626 threshold: this._options.thresholds
5627 });
5628 }
5629 disconnect() {
5630 if (this._observerInst) {
5631 let listener;
5632 while ((listener = this._listeners.pop())) {
5633 this._observerInst.unobserve(listener.element);
5634 }
5635 this._observerInst.disconnect();
5636 }
5637 }
5638 observe(targetSelector, callback) {
5639 // 同wx小程序效果一致,每个实例监听一个Selector
5640 if (this._listeners.length)
5641 return;
5642 // 监听前没有设置关联的节点
5643 if (!this._observerInst) {
5644 console.warn('Intersection observer will be ignored because no relative nodes are found.');
5645 return;
5646 }
5647 const nodeList = this._options.observeAll
5648 ? this.container.querySelectorAll(targetSelector)
5649 : [this.container.querySelector(targetSelector)];
5650 Taro.nextTick(() => {
5651 nodeList.forEach(element => {
5652 if (!element)
5653 return;
5654 this._observerInst.observe(element);
5655 this._listeners.push({ element, callback });
5656 });
5657 });
5658 }
5659 relativeTo(selector, margins) {
5660 // 已设置observe监听后,重新关联节点
5661 if (this._listeners.length) {
5662 console.error('Relative nodes cannot be added after "observe" call in IntersectionObserver');
5663 return this;
5664 }
5665 this._root = this.container.querySelector(selector) || null;
5666 if (margins) {
5667 this._rootMargin = margins;
5668 }
5669 this._observerInst = this.createInst();
5670 return this;
5671 }
5672 relativeToViewport(margins) {
5673 return this.relativeTo('.taro_page', margins);
5674 }
5675 _getCallbackByElement(element) {
5676 const listener = this._listeners.find(listener => listener.element === element);
5677 return listener ? listener.callback : null;
5678 }
5679}
5680
5681function generateMediaQueryStr(descriptor) {
5682 const mediaQueryArr = [];
5683 const descriptorMenu = ['width', 'minWidth', 'maxWidth', 'height', 'minHeight', 'maxHeight', 'orientation'];
5684 for (const item of descriptorMenu) {
5685 if (item !== 'orientation' &&
5686 descriptor[item] &&
5687 Number(descriptor[item]) >= 0) {
5688 mediaQueryArr.push(`(${(toKebabCase(item))}: ${Number(descriptor[item])}px)`);
5689 }
5690 if (item === 'orientation' && descriptor[item]) {
5691 mediaQueryArr.push(`(${toKebabCase(item)}: ${descriptor[item]})`);
5692 }
5693 }
5694 return mediaQueryArr.join(' and ');
5695}
5696class MediaQueryObserver {
5697 // 监听页面媒体查询变化情况
5698 observe(descriptor, callback) {
5699 if (isFunction(callback)) {
5700 // 创建媒体查询对象
5701 this._mediaQueryObserver = window.matchMedia(generateMediaQueryStr(descriptor));
5702 // 监听器
5703 this._listener = (ev) => {
5704 callback({ matches: ev.matches });
5705 };
5706 callback({ matches: this._mediaQueryObserver.matches });
5707 // 兼容旧浏览器中 MediaQueryList 尚未继承于 EventTarget 导致不存在 'addEventListener'
5708 if ('addEventListener' in this._mediaQueryObserver) {
5709 this._mediaQueryObserver.addEventListener('change', this._listener);
5710 }
5711 else {
5712 // @ts-ignore
5713 this._mediaQueryObserver.addListener(this._listener);
5714 }
5715 }
5716 }
5717 // 停止监听,销毁媒体查询对象
5718 disconnect() {
5719 if (this._mediaQueryObserver && this._listener) {
5720 // 兼容旧浏览器中 MediaQueryList 尚未继承于 EventTarget 导致不存在 'removeEventListener'
5721 if ('removeEventListener' in this._mediaQueryObserver) {
5722 this._mediaQueryObserver.removeEventListener('change', this._listener);
5723 }
5724 else {
5725 // @ts-ignore
5726 this._mediaQueryObserver.removeListener(this._listener);
5727 }
5728 }
5729 }
5730}
5731
5732class NodesRef {
5733 constructor(selector, querySelectorQuery, single) {
5734 this._component = querySelectorQuery._component;
5735 this._selector = selector;
5736 this._selectorQuery = querySelectorQuery;
5737 this._single = single;
5738 }
5739 context(cb) {
5740 const { _selector, _component, _single, _selectorQuery } = this;
5741 _selectorQuery._push(_selector, _component, _single, { context: !0 }, cb);
5742 return _selectorQuery;
5743 }
5744 node(cb) {
5745 const { _selector, _component, _single, _selectorQuery } = this;
5746 _selectorQuery._push(_selector, _component, _single, { nodeCanvasType: !0, node: !0 }, cb);
5747 return _selectorQuery;
5748 }
5749 boundingClientRect(cb) {
5750 const { _selector, _component, _single, _selectorQuery } = this;
5751 _selectorQuery._push(_selector, _component, _single, { id: !0, dataset: !0, rect: !0, size: !0 }, cb);
5752 return _selectorQuery;
5753 }
5754 scrollOffset(cb) {
5755 const { _selector, _component, _single, _selectorQuery } = this;
5756 _selectorQuery._push(_selector, _component, _single, { id: !0, dataset: !0, scrollOffset: !0 }, cb);
5757 return _selectorQuery;
5758 }
5759 fields(fields, cb) {
5760 const { _selector, _component, _single, _selectorQuery } = this;
5761 const { id, dataset, rect, size, scrollOffset, context, node, properties = [], computedStyle = [] } = fields;
5762 _selectorQuery._push(_selector, _component, _single, {
5763 id,
5764 dataset,
5765 rect,
5766 size,
5767 scrollOffset,
5768 context,
5769 node,
5770 nodeCanvasType: node,
5771 properties,
5772 computedStyle,
5773 }, cb);
5774 return _selectorQuery;
5775 }
5776}
5777
5778function filter(fields, dom, selector) {
5779 if (!dom)
5780 return null;
5781 const isViewport = selector === '.taro_page';
5782 const { id, dataset, rect, size, scrollOffset, properties = [], computedStyle = [], nodeCanvasType, node, context } = fields;
5783 const res = {};
5784 if (nodeCanvasType && node) {
5785 const tagName = dom.tagName;
5786 res.node = {
5787 id: dom.id,
5788 $taroElement: dom
5789 };
5790 if (/^taro-canvas-core/i.test(tagName)) {
5791 const type = dom.type || '';
5792 res.nodeCanvasType = type;
5793 const canvas = dom.getElementsByTagName('canvas')[0];
5794 if (/^(2d|webgl)/i.test(type) && canvas) {
5795 res.node = canvas;
5796 }
5797 else {
5798 res.node = null;
5799 }
5800 }
5801 else if (/^taro-scroll-view-core/i.test(tagName)) {
5802 // Note https://developers.weixin.qq.com/miniprogram/dev/api/ui/scroll/ScrollViewContext.html
5803 res.nodeCanvasType = '';
5804 res.node = dom;
5805 dom.scrollTo = dom.mpScrollToMethod;
5806 dom.scrollIntoView = dom.mpScrollIntoViewMethod;
5807 }
5808 else {
5809 res.nodeCanvasType = '';
5810 res.node = dom;
5811 }
5812 return res;
5813 }
5814 if (context) {
5815 const tagName = dom.tagName;
5816 if (/^taro-video-core/i.test(tagName)) {
5817 // TODO HTMLVideoElement to VideoContext
5818 return { context: dom };
5819 }
5820 else if (/^taro-canvas-core/i.test(tagName)) {
5821 const type = dom.type || '2d';
5822 const canvas = dom === null || dom === void 0 ? void 0 : dom.querySelector('canvas');
5823 const ctx = canvas === null || canvas === void 0 ? void 0 : canvas.getContext(type);
5824 return { context: new CanvasContext(canvas, ctx) };
5825 }
5826 else if (/^taro-live-player-core/i.test(tagName)) {
5827 console.error('暂时不支持通过 NodesRef.context 获取 LivePlayerContext');
5828 }
5829 else if (/^taro-editor-core/i.test(tagName)) {
5830 console.error('暂时不支持通过 NodesRef.context 获取 EditorContext');
5831 }
5832 else if (/^taro-map-core/i.test(tagName)) {
5833 console.error('暂时不支持通过 NodesRef.context 获取 MapContext');
5834 }
5835 return;
5836 }
5837 if (id)
5838 res.id = dom.id;
5839 if (dataset)
5840 res.dataset = Object.assign({}, dom.dataset);
5841 if (rect || size) {
5842 const { left, right, top, bottom, width, height } = dom.getBoundingClientRect();
5843 if (rect) {
5844 if (!isViewport) {
5845 res.left = left;
5846 res.right = right;
5847 res.top = top;
5848 res.bottom = bottom;
5849 }
5850 else {
5851 res.left = 0;
5852 res.right = 0;
5853 res.top = 0;
5854 res.bottom = 0;
5855 }
5856 }
5857 if (size) {
5858 if (!isViewport) {
5859 res.width = width;
5860 res.height = height;
5861 }
5862 else {
5863 res.width = dom.clientWidth;
5864 res.height = dom.clientHeight;
5865 }
5866 }
5867 }
5868 if (scrollOffset) {
5869 res.scrollLeft = dom.scrollLeft;
5870 res.scrollTop = dom.scrollTop;
5871 }
5872 if (properties.length) {
5873 properties.forEach(prop => {
5874 const attr = dom.getAttribute(prop);
5875 if (attr)
5876 res[prop] = attr;
5877 });
5878 }
5879 if (computedStyle.length) {
5880 const styles = window.getComputedStyle(dom);
5881 computedStyle.forEach(key => {
5882 const value = styles.getPropertyValue(key) || styles[key];
5883 if (value)
5884 res[key] = value;
5885 });
5886 }
5887 return res;
5888}
5889/**
5890 * WXML节点信息API
5891 * @return {Object} SelectorQuery 对象实例
5892 */
5893function queryBat(queue, cb) {
5894 const result = [];
5895 queue.forEach(item => {
5896 var _a;
5897 const { selector, single, fields, component } = item;
5898 // selector 的容器节点
5899 /* eslint-disable */
5900 const container = (component !== null ?
5901 (findDOM(component) || document) :
5902 document);
5903 /* eslint-enable */
5904 // 特殊处理 ---- 选自己
5905 let selectSelf = false;
5906 if (container !== document) {
5907 const $nodeList = (_a = container.parentNode) === null || _a === void 0 ? void 0 : _a.querySelectorAll(selector);
5908 if ($nodeList) {
5909 for (let i = 0, len = $nodeList.length; i < len; ++i) {
5910 if (container === $nodeList[i]) {
5911 selectSelf = true;
5912 break;
5913 }
5914 }
5915 }
5916 }
5917 if (single) {
5918 const el = selectSelf === true ? container : container.querySelector(selector);
5919 result.push(filter(fields, el, selector));
5920 }
5921 else {
5922 const $children = container.querySelectorAll(selector);
5923 const children = [];
5924 selectSelf === true && children.push(container);
5925 for (let i = 0, len = $children.length; i < len; ++i) {
5926 children.push($children[i]);
5927 }
5928 result.push(children.map(dom => filter(fields, dom)));
5929 }
5930 });
5931 cb(result);
5932}
5933class SelectorQuery {
5934 constructor() {
5935 this._defaultWebviewId = null;
5936 this._webviewId = null;
5937 this._queue = [];
5938 this._queueCb = [];
5939 this._component;
5940 }
5941 in(component) {
5942 this._component = component;
5943 return this;
5944 }
5945 select(selector) {
5946 // 小程序里跨自定义组件的后代选择器 '>>>' 在 h5 替换为普通后代选择器 '>'
5947 if (typeof selector === 'string')
5948 selector = selector.replace('>>>', '>');
5949 return new NodesRef(selector, this, true);
5950 }
5951 selectAll(selector) {
5952 // 小程序里跨自定义组件的后代选择器 '>>>' 在 h5 替换为普通后代选择器 '>'
5953 if (typeof selector === 'string')
5954 selector = selector.replace('>>>', '>');
5955 return new NodesRef(selector, this, false);
5956 }
5957 selectViewport() {
5958 return new NodesRef('.taro_page', this, true);
5959 }
5960 exec(cb) {
5961 Taro.nextTick(() => {
5962 queryBat(this._queue, res => {
5963 const _queueCb = this._queueCb;
5964 res.forEach((item, index) => {
5965 const cb = _queueCb[index];
5966 isFunction(cb) && cb.call(this, item);
5967 });
5968 isFunction(cb) && cb.call(this, res);
5969 });
5970 });
5971 return this;
5972 }
5973 _push(selector, component, single, fields, callback = null) {
5974 this._queue.push({
5975 component,
5976 selector,
5977 single,
5978 fields
5979 });
5980 this._queueCb.push(callback);
5981 }
5982}
5983
5984const createSelectorQuery = () => {
5985 return new SelectorQuery();
5986};
5987const createIntersectionObserver = (component, options) => {
5988 return new TaroH5IntersectionObserver(component, options);
5989};
5990const createMediaQueryObserver = () => {
5991 return new MediaQueryObserver();
5992};
5993
5994const { Behavior, getEnv, ENV_TYPE, Link, interceptors, interceptorify, Current, options, eventCenter, Events, preload } = Taro;
5995const taro = {
5996 // @ts-ignore
5997 Behavior,
5998 getEnv,
5999 ENV_TYPE,
6000 Link,
6001 interceptors,
6002 interceptorify,
6003 Current,
6004 getCurrentInstance,
6005 options,
6006 nextTick,
6007 eventCenter,
6008 Events,
6009 preload,
6010 history,
6011 navigateBack,
6012 navigateTo,
6013 reLaunch,
6014 redirectTo,
6015 getCurrentPages,
6016 switchTab
6017};
6018const requirePlugin = /* @__PURE__ */ permanentlyNotSupport('requirePlugin');
6019function getConfig() {
6020 var _a;
6021 if (this === null || this === void 0 ? void 0 : this.pxTransformConfig)
6022 return this.pxTransformConfig;
6023 return ((_a = taro).config || (_a.config = {}));
6024}
6025const defaultDesignWidth = 750;
6026const defaultDesignRatio = {
6027 640: 2.34 / 2,
6028 750: 1,
6029 828: 1.81 / 2
6030};
6031const defaultBaseFontSize = 20;
6032const defaultUnitPrecision = 5;
6033const defaultTargetUnit = 'rem';
6034const initPxTransform = function ({ designWidth = defaultDesignWidth, deviceRatio = defaultDesignRatio, baseFontSize = defaultBaseFontSize, unitPrecision = defaultUnitPrecision, targetUnit = defaultTargetUnit }) {
6035 const config = getConfig.call(this);
6036 config.designWidth = designWidth;
6037 config.deviceRatio = deviceRatio;
6038 config.baseFontSize = baseFontSize;
6039 config.targetUnit = targetUnit;
6040 config.unitPrecision = unitPrecision;
6041};
6042const pxTransform = function (size = 0) {
6043 const config = getConfig.call(this);
6044 const baseFontSize = config.baseFontSize || defaultBaseFontSize;
6045 const deviceRatio = config.deviceRatio || defaultDesignRatio;
6046 const designWidth = (((input = 0) => isFunction(config.designWidth)
6047 ? config.designWidth(input)
6048 : config.designWidth))(size);
6049 if (!(designWidth in config.deviceRatio)) {
6050 throw new Error(`deviceRatio 配置中不存在 ${designWidth} 的设置!`);
6051 }
6052 const targetUnit = config.targetUnit || defaultTargetUnit;
6053 const unitPrecision = config.unitPrecision || defaultUnitPrecision;
6054 const formatSize = ~~size;
6055 let rootValue = 1 / deviceRatio[designWidth];
6056 switch (targetUnit) {
6057 case 'vw':
6058 rootValue = designWidth / 100;
6059 break;
6060 case 'px':
6061 rootValue *= 2;
6062 break;
6063 default:
6064 // rem
6065 rootValue *= baseFontSize * 2;
6066 }
6067 let val = formatSize / rootValue;
6068 if (unitPrecision >= 0 && unitPrecision <= 100) {
6069 // Number(val): 0.50000 => 0.5
6070 val = Number(val.toFixed(unitPrecision));
6071 }
6072 return val + targetUnit;
6073};
6074const canIUseWebp = function () {
6075 const canvas = document.createElement('canvas');
6076 return canvas.toDataURL('image/webp').indexOf('data:image/webp') === 0;
6077};
6078const getAppInfo = function () {
6079 const config = getConfig.call(this);
6080 return {
6081 platform: process.env.TARO_PLATFORM || PLATFORM_TYPE.WEB,
6082 taroVersion: process.env.TARO_VERSION || 'unknown',
6083 designWidth: config.designWidth,
6084 };
6085};
6086taro.requirePlugin = requirePlugin;
6087taro.getApp = getApp;
6088taro.pxTransform = pxTransform;
6089taro.initPxTransform = initPxTransform;
6090taro.canIUseWebp = canIUseWebp;
6091
6092export { Behavior, Current, ENV_TYPE, Events, Link, NodesRef, SocketTask, addCard, addFileToFavorites, addInterceptor, addPhoneCalendar, addPhoneContact, addPhoneRepeatCalendar, addRecentColorSign, addVideoToFavorites, advancedGeneralIdentify, animalClassify, applyAddToMyApps, arrayBufferToBase64, authPrivateMessage, authorize, authorizeForMiniProgram, base64ToArrayBuffer, batchGetStorage, batchGetStorageSync, batchSetStorage, batchSetStorageSync, canIUseWebp, canvasGetImageData, canvasPutImageData, canvasToTempFilePath, carClassify, checkIsAddedToMyMiniProgram, checkIsOpenAccessibility, checkIsPictureInPictureActive, checkIsSoterEnrolledInDevice, checkIsSupportFacialRecognition, checkIsSupportSoterAuthentication, checkSession, chooseAddress, chooseContact, chooseImage, chooseInvoice, chooseInvoiceTitle, chooseLicensePlate, chooseLocation, chooseMedia, chooseMessageFile, choosePoi, chooseVideo, cleanInterceptors, clearStorage, clearStorageSync, closeBLEConnection, closeBluetoothAdapter, closeSocket, cloud, compressImage, compressVideo, connectSocket, connectWifi, createAnimation, createAudioContext, createBLEConnection, createBLEPeripheralServer, createBufferURL, createCacheManager, createCameraContext, createCanvasContext, createInferenceSession, createInnerAudioContext, createIntersectionObserver, createInterstitialAd, createLivePlayerContext, createLivePusherContext, createMapContext, createMediaAudioPlayer, createMediaContainer, createMediaQueryObserver, createMediaRecorder, createOffscreenCanvas, createRewardedVideoAd, createSelectorQuery, createTCPSocket, createUDPSocket, createVKSession, createVideoContext, createVideoDecoder, createWebAudioContext, createWorker, cropImage, taro as default, disableAlertBeforeUnload, dishClassify, downloadFile, editImage, enableAlertBeforeUnload, env, eventCenter, exitMiniProgram, exitVoIPChat, faceDetect, faceVerifyForPay, getAccountInfoSync, getApp, getAppAuthorizeSetting, getAppBaseInfo, getAppInfo, getAvailableAudioSources, getBLEDeviceCharacteristics, getBLEDeviceRSSI, getBLEDeviceServices, getBLEMTU, getBackgroundAudioManager, getBackgroundAudioPlayerState, getBackgroundFetchData, getBackgroundFetchToken, getBatteryInfo, getBatteryInfoSync, getBeacons, getBluetoothAdapterState, getBluetoothDevices, getChannelsLiveInfo, getChannelsLiveNoticeInfo, getChannelsShareKey, getClipboardData, getConnectedBluetoothDevices, getConnectedWifi, getCurrentInstance, getDeviceInfo, getDeviceVoIPList, getEnterOptionsSync, getEnv, getExptInfoSync, getExtConfig, getExtConfigSync, getFileInfo, getFileSystemManager, getFuzzyLocation, getGroupEnterInfo, getGuildInfo, getHCEState, getImageInfo, getInferenceEnvInfo, getLaunchOptionsSync, getLocalIPAddress, getLocation, getLogManager, getMenuButtonBoundingClientRect, getNFCAdapter, getNetworkType, getOpenUserInfo, getPerformance, getPrivacySetting, getQQRunData, getRandomValues, getRealtimeLogManager, getRecorderManager, getRendererUserAgent, getSavedFileInfo, getSavedFileList, getScreenBrightness, getScreenRecordingState, getSelectedTextRange, getSetting, getShareInfo, getSkylineInfo, getSkylineInfoSync, getStorage, getStorageInfo, getStorageInfoSync, getStorageSync, getSwanId, getSystemInfo, getSystemInfoAsync, getSystemInfoSync, getSystemSetting, getUpdateManager, getUserCryptoManager, getUserInfo, getUserProfile, getVideoInfo, getWeRunData, getWifiList, getWindowInfo, hideHomeButton, hideKeyboard, hideLoading, hideNavigationBarLoading, hideShareMenu, hideTabBar, hideTabBarRedDot, hideToast, imageAudit, initFaceDetect, initPxTransform, initTabBarApis, interceptorify, interceptors, isAddedToMyApps, isBluetoothDevicePaired, isVKSupport, join1v1Chat, joinVoIPChat, loadFontFace, login, logoClassify, makeBluetoothPair, makePhoneCall, navigateBackMiniProgram, navigateBackSmartProgram, navigateToMiniProgram, navigateToSmartGameProgram, navigateToSmartProgram, nextTick, notifyBLECharacteristicValueChange, objectDetectIdentify, ocrBankCard, ocrDrivingLicense, ocrIdCard, ocrVehicleLicense, offAccelerometerChange, offAppHide, offAppShow, offAudioInterruptionBegin, offAudioInterruptionEnd, offBLECharacteristicValueChange, offBLEConnectionStateChange, offBLEMTUChange, offBLEPeripheralConnectionStateChanged, offBeaconServiceChange, offBeaconUpdate, offBluetoothAdapterStateChange, offBluetoothDeviceFound, offCompassChange, offCopyUrl, offDeviceMotionChange, offError, offGetWifiList, offGyroscopeChange, offHCEMessage, offKeyboardHeightChange, offLazyLoadError, offLocalServiceDiscoveryStop, offLocalServiceFound, offLocalServiceLost, offLocalServiceResolveFail, offLocationChange, offLocationChangeError, offMemoryWarning, offNetworkStatusChange, offNetworkWeakChange, offPageNotFound, offScreenRecordingStateChanged, offThemeChange, offUnhandledRejection, offUserCaptureScreen, offVoIPChatInterrupted, offVoIPChatMembersChanged, offVoIPChatSpeakersChanged, offVoIPChatStateChanged, offVoIPVideoMembersChanged, offWifiConnected, offWifiConnectedWithPartialInfo, offWindowResize, onAccelerometerChange, onAppHide, onAppShow, onAudioInterruptionBegin, onAudioInterruptionEnd, onBLECharacteristicValueChange, onBLEConnectionStateChange, onBLEMTUChange, onBLEPeripheralConnectionStateChanged, onBackgroundAudioPause, onBackgroundAudioPlay, onBackgroundAudioStop, onBackgroundFetchData, onBeaconServiceChange, onBeaconUpdate, onBluetoothAdapterStateChange, onBluetoothDeviceFound, onCompassChange, onCopyUrl, onDeviceMotionChange, onError, onGetWifiList, onGyroscopeChange, onHCEMessage, onKeyboardHeightChange, onLazyLoadError, onLocalServiceDiscoveryStop, onLocalServiceFound, onLocalServiceLost, onLocalServiceResolveFail, onLocationChange, onLocationChangeError, onMemoryWarning, onNeedPrivacyAuthorization, onNetworkStatusChange, onNetworkWeakChange, onPageNotFound, onScreenRecordingStateChanged, onSocketClose, onSocketError, onSocketMessage, onSocketOpen, onThemeChange, onUnhandledRejection, onUserCaptureScreen, onVoIPChatInterrupted, onVoIPChatMembersChanged, onVoIPChatSpeakersChanged, onVoIPChatStateChanged, onVoIPVideoMembersChanged, onWifiConnected, onWifiConnectedWithPartialInfo, onWindowResize, openAppAuthorizeSetting, openBluetoothAdapter, openBusinessView, openCard, openChannelsActivity, openChannelsEvent, openChannelsLive, openChannelsUserProfile, openCustomerServiceChat, openDocument, openEmbeddedMiniProgram, openLocation, openPrivacyContract, openQzonePublish, openSetting, openSystemBluetoothSetting, openVideoEditor, options, pageScrollTo, pauseBackgroundAudio, pauseVoice, plantClassify, playBackgroundAudio, playVoice, pluginLogin, preload, preloadAssets, preloadSkylineView, preloadSubPackage, preloadWebview, previewImage, previewMedia, pxTransform, readBLECharacteristicValue, removeSavedFile, removeStorage, removeStorageSync, removeTabBarBadge, reportAnalytics, reportEvent, reportMonitor, reportPerformance, request, requestDeviceVoIP, requestOrderPayment, requestPayment, requestPluginPayment, requestPolymerPayment, requestSubscribeDeviceMessage, requestSubscribeMessage, requirePlugin, requirePrivacyAuthorize, reserveChannelsLive, revokeBufferURL, saveFile, saveFileToDisk, saveImageToPhotosAlbum, saveVideoToPhotosAlbum, scanCode, seekBackgroundAudio, sendHCEMessage, sendSms, sendSocketMessage, setBLEMTU, setBackgroundColor, setBackgroundFetchToken, setBackgroundTextStyle, setClipboardData, setCustomDress, setEnable1v1Chat, setEnableDebug, setInnerAudioOption, setKeepScreenOn, setNavigationBarColor, setNavigationBarTitle, setOfficialDress, setPageInfo, setScreenBrightness, setStorage, setStorageSync, setTabBarBadge, setTabBarItem, setTabBarStyle, setTopBarText, setVisualEffectOnCapture, setWifiList, setWindowSize, shareFileMessage, shareToWeRun, shareVideoMessage, showActionSheet, showLoading, showModal, showNavigationBarLoading, showRedPackage, showShareImageMenu, showShareMenu, showTabBar, showTabBarRedDot, showToast, startAccelerometer, startBeaconDiscovery, startBluetoothDevicesDiscovery, startCompass, startDeviceMotionListening, startFacialRecognitionVerify, startFacialRecognitionVerifyAndUploadVideo, startGyroscope, startHCE, startLocalServiceDiscovery, startLocationUpdate, startLocationUpdateBackground, startPullDownRefresh, startRecord, startSoterAuthentication, startWifi, stopAccelerometer, stopBackgroundAudio, stopBeaconDiscovery, stopBluetoothDevicesDiscovery, stopCompass, stopDeviceMotionListening, stopFaceDetect, stopGyroscope, stopHCE, stopLocalServiceDiscovery, stopLocationUpdate, stopPullDownRefresh, stopRecord, stopVoice, stopWifi, subscribeVoIPVideoMembers, textReview, textToAudio, tradePay, updateQQApp, updateShareMenu, updateVoIPChatMuteConfig, updateWeChatApp, uploadFile, vibrateLong, vibrateShort, writeBLECharacteristicValue };
6093//# sourceMappingURL=index.esm.js.map