UNPKG

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