@tarojs/taro-h5 3.4.5 → 3.4.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,4 @@
1
+ import { throttle } from '../utils';
1
2
  import { CallbackManager, MethodHandler } from '../utils/handler';
2
3
  const callbackManager = new CallbackManager();
3
4
  let devicemotionListener;
@@ -30,22 +31,6 @@ const INTERVAL_MAP = {
30
31
  frequency: 5
31
32
  }
32
33
  };
33
- const getDevicemotionListener = interval => {
34
- let lock;
35
- let timer;
36
- return evt => {
37
- if (lock)
38
- return;
39
- lock = true;
40
- timer && clearTimeout(timer);
41
- callbackManager.trigger({
42
- x: evt.acceleration.x || 0,
43
- y: evt.acceleration.y || 0,
44
- z: evt.acceleration.z || 0
45
- });
46
- timer = setTimeout(() => { lock = false; }, interval);
47
- };
48
- };
49
34
  /**
50
35
  * 开始监听加速度数据。
51
36
  */
@@ -57,7 +42,14 @@ export const startAccelerometer = ({ interval = 'normal', success, fail, complet
57
42
  if (devicemotionListener) {
58
43
  stopAccelerometer();
59
44
  }
60
- devicemotionListener = getDevicemotionListener(intervalObj.interval);
45
+ devicemotionListener = throttle((evt) => {
46
+ var _a, _b, _c;
47
+ callbackManager.trigger({
48
+ x: ((_a = evt.acceleration) === null || _a === void 0 ? void 0 : _a.x) || 0,
49
+ y: ((_b = evt.acceleration) === null || _b === void 0 ? void 0 : _b.y) || 0,
50
+ z: ((_c = evt.acceleration) === null || _c === void 0 ? void 0 : _c.z) || 0
51
+ });
52
+ }, intervalObj.interval);
61
53
  window.addEventListener('devicemotion', devicemotionListener, true);
62
54
  }
63
55
  else {
@@ -1,45 +1,59 @@
1
+ import { getDeviceInfo } from '../base/system';
2
+ import { throttle } from '../utils';
1
3
  import { CallbackManager, MethodHandler } from '../utils/handler';
2
4
  const callbackManager = new CallbackManager();
3
5
  let compassListener;
6
+ /**
7
+ * Note: 按系统类型获取对应绝对 orientation 事件名,因为安卓系统中直接监听 deviceorientation 事件得到的不是绝对 orientation
8
+ */
9
+ const deviceorientationEventName = ['absolutedeviceorientation', 'deviceorientationabsolute', 'deviceorientation'].find(item => {
10
+ if ('on' + item in window) {
11
+ return item;
12
+ }
13
+ }) || '';
4
14
  /**
5
15
  * 停止监听罗盘数据
6
16
  */
7
17
  export const stopCompass = ({ success, fail, complete } = {}) => {
8
18
  const handle = new MethodHandler({ name: 'stopCompass', success, fail, complete });
9
19
  try {
10
- window.removeEventListener('deviceorientation', compassListener, true);
20
+ window.removeEventListener(deviceorientationEventName, compassListener, true);
11
21
  return handle.success();
12
22
  }
13
23
  catch (e) {
14
24
  return handle.fail({ errMsg: e.message });
15
25
  }
16
26
  };
17
- const getDeviceOrientationListener = interval => {
18
- let lock;
19
- let timer;
20
- return evt => {
21
- if (lock)
22
- return;
23
- lock = true;
24
- timer && clearTimeout(timer);
25
- callbackManager.trigger({
26
- direction: 360 - evt.alpha
27
- });
28
- timer = setTimeout(() => { lock = false; }, interval);
29
- };
30
- };
27
+ let CompassChangeTrigger = false;
31
28
  /**
32
29
  * 开始监听罗盘数据
33
30
  */
34
31
  export const startCompass = ({ success, fail, complete } = {}) => {
35
32
  const handle = new MethodHandler({ name: 'startCompass', success, fail, complete });
36
33
  try {
37
- if (window.DeviceOrientationEvent) {
34
+ if (deviceorientationEventName !== '') {
38
35
  if (compassListener) {
39
36
  stopCompass();
40
37
  }
41
- compassListener = getDeviceOrientationListener(200);
42
- window.addEventListener('deviceorientation', compassListener, true);
38
+ compassListener = throttle((evt) => {
39
+ const isAndroid = getDeviceInfo().system === 'AndroidOS';
40
+ if (isAndroid && !evt.absolute && !CompassChangeTrigger) {
41
+ CompassChangeTrigger = true;
42
+ 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 .');
43
+ }
44
+ const alpha = evt.alpha || 0;
45
+ /**
46
+ * 由于平台差异,accuracy 在 iOS/Android 的值不同。
47
+ * - iOS:accuracy 是一个 number 类型的值,表示相对于磁北极的偏差。0 表示设备指向磁北,90 表示指向东,180 表示指向南,依此类推。
48
+ * - Android:accuracy 是一个 string 类型的枚举值。
49
+ */
50
+ const accuracy = isAndroid ? evt.absolute ? 'high' : 'medium' : alpha;
51
+ callbackManager.trigger({
52
+ direction: 360 - alpha,
53
+ accuracy: accuracy
54
+ });
55
+ }, 5000);
56
+ window.addEventListener(deviceorientationEventName, compassListener, true);
43
57
  }
44
58
  else {
45
59
  throw new Error('compass is not supported');
@@ -1,3 +1,4 @@
1
+ import { throttle } from '../utils';
1
2
  import { CallbackManager, MethodHandler } from '../utils/handler';
2
3
  const callbackManager = new CallbackManager();
3
4
  let deviceMotionListener;
@@ -28,22 +29,6 @@ export const stopDeviceMotionListening = ({ success, fail, complete } = {}) => {
28
29
  return handle.fail({ errMsg: e.message });
29
30
  }
30
31
  };
31
- const getDeviceOrientationListener = interval => {
32
- let lock;
33
- let timer;
34
- return evt => {
35
- if (lock)
36
- return;
37
- lock = true;
38
- timer && clearTimeout(timer);
39
- callbackManager.trigger({
40
- alpha: evt.alpha,
41
- beta: evt.beta,
42
- gamma: evt.gamma
43
- });
44
- timer = setTimeout(() => { lock = false; }, interval);
45
- };
46
- };
47
32
  /**
48
33
  * 开始监听设备方向的变化。
49
34
  */
@@ -55,7 +40,13 @@ export const startDeviceMotionListening = ({ interval = 'normal', success, fail,
55
40
  if (deviceMotionListener) {
56
41
  stopDeviceMotionListening();
57
42
  }
58
- deviceMotionListener = getDeviceOrientationListener(intervalObj.interval);
43
+ deviceMotionListener = throttle((evt) => {
44
+ callbackManager.trigger({
45
+ alpha: evt.alpha,
46
+ beta: evt.beta,
47
+ gamma: evt.gamma
48
+ });
49
+ }, intervalObj.interval);
59
50
  window.addEventListener('deviceorientation', deviceMotionListener, true);
60
51
  }
61
52
  else {
@@ -1,6 +1,10 @@
1
1
  import { processOpenApi } from '../utils';
2
2
  // 扫码
3
- export const scanCode = processOpenApi('scanQRCode', { needResult: 1 }, res => ({
4
- errMsg: res.errMsg === 'scanQRCode:ok' ? 'scanCode:ok' : res.errMsg,
5
- result: res.resultStr
6
- }));
3
+ export const scanCode = processOpenApi({
4
+ name: 'scanQRCode',
5
+ defaultOptions: { needResult: 1 },
6
+ formatResult: res => ({
7
+ errMsg: res.errMsg === 'scanQRCode:ok' ? 'scanCode:ok' : res.errMsg,
8
+ result: res.resultStr
9
+ })
10
+ });
@@ -0,0 +1,64 @@
1
+ import { processOpenApi, shouldBeObject } from '../utils';
2
+ import { MethodHandler } from '../utils/handler';
3
+ const getLocationByW3CApi = (options) => {
4
+ var _a;
5
+ // 断言 options 必须是 Object
6
+ const isObject = shouldBeObject(options);
7
+ if (!isObject.flag) {
8
+ const res = { errMsg: `getLocation:fail ${isObject.msg}` };
9
+ console.error(res.errMsg);
10
+ return Promise.reject(res);
11
+ }
12
+ // 解构回调函数
13
+ const { success, fail, complete } = options;
14
+ const handle = new MethodHandler({ name: 'getLocation', success, fail, complete });
15
+ // const defaultMaximumAge = 5 * 1000
16
+ const positionOptions = {
17
+ enableHighAccuracy: options.isHighAccuracy || (options.altitude != null),
18
+ // maximumAge: defaultMaximumAge, // 允许取多久以内的缓存位置
19
+ timeout: options.highAccuracyExpireTime // 高精度定位超时时间
20
+ };
21
+ // Web端API实现暂时仅支持GPS坐标系
22
+ if (((_a = options.type) === null || _a === void 0 ? void 0 : _a.toUpperCase()) !== 'WGS84') {
23
+ return handle.fail({
24
+ errMsg: 'This coordinate system type is not temporarily supported'
25
+ });
26
+ }
27
+ // 判断当前浏览器是否支持位置API
28
+ const geolocationSupported = navigator.geolocation;
29
+ if (!geolocationSupported) {
30
+ return handle.fail({
31
+ errMsg: 'The current browser does not support this feature'
32
+ });
33
+ }
34
+ // 开始获取位置
35
+ return new Promise((resolve, reject) => {
36
+ navigator.geolocation.getCurrentPosition((position) => {
37
+ const result = {
38
+ /** 位置的精确度 */
39
+ accuracy: position.coords.accuracy,
40
+ /** 高度,单位 m */
41
+ altitude: position.coords.altitude,
42
+ /** 水平精度,单位 m */
43
+ horizontalAccuracy: position.coords.accuracy,
44
+ /** 纬度,范围为 -90~90,负数表示南纬 */
45
+ latitude: position.coords.latitude,
46
+ /** 经度,范围为 -180~180,负数表示西经 */
47
+ longitude: position.coords.longitude,
48
+ /** 速度,单位 m/s */
49
+ speed: position.coords.speed,
50
+ /** 垂直精度,单位 m(Android 无法获取,返回 0) */
51
+ verticalAccuracy: position.coords.altitudeAccuracy || 0,
52
+ /** 调用结果,自动补充 */
53
+ errMsg: ''
54
+ };
55
+ handle.success(result, resolve);
56
+ }, (error) => {
57
+ handle.fail({ errMsg: error.message }, reject);
58
+ }, positionOptions);
59
+ });
60
+ };
61
+ export const getLocation = processOpenApi({
62
+ name: 'getLocation',
63
+ standardMethod: getLocationByW3CApi
64
+ });
@@ -3,11 +3,14 @@ import { processOpenApi, temporarilyNotSupport } from '../utils/index';
3
3
  export const stopLocationUpdate = temporarilyNotSupport('stopLocationUpdate');
4
4
  export const startLocationUpdateBackground = temporarilyNotSupport('startLocationUpdateBackground');
5
5
  export const startLocationUpdate = temporarilyNotSupport('startLocationUpdate');
6
- export const openLocation = processOpenApi('openLocation', { scale: 18 });
6
+ export const openLocation = processOpenApi({
7
+ name: 'openLocation',
8
+ defaultOptions: { scale: 18 }
9
+ });
7
10
  export const onLocationChangeError = temporarilyNotSupport('onLocationChangeError');
8
11
  export const onLocationChange = temporarilyNotSupport('onLocationChange');
9
12
  export const offLocationChangeError = temporarilyNotSupport('offLocationChangeError');
10
13
  export const offLocationChange = temporarilyNotSupport('offLocationChange');
11
- export const getLocation = processOpenApi('getLocation');
14
+ export { getLocation } from './getLocation';
12
15
  export const choosePoi = temporarilyNotSupport('choosePoi');
13
- export * from './chooseLocation';
16
+ export { chooseLocation } from './chooseLocation';
@@ -0,0 +1,14 @@
1
+ /**
2
+ * ease-in-out的函数
3
+ * @param t 0-1的数字
4
+ */
5
+ export const easeInOut = (t) => (t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1);
6
+ export const getTimingFunc = (easeFunc, frameCnt) => {
7
+ return x => {
8
+ if (frameCnt <= 1) {
9
+ return easeFunc(1);
10
+ }
11
+ const t = x / (frameCnt - 1);
12
+ return easeFunc(t);
13
+ };
14
+ };
@@ -90,7 +90,7 @@ export function temporarilyNotSupport(apiName) {
90
90
  }
91
91
  export function weixinCorpSupport(apiName) {
92
92
  return () => {
93
- const errMsg = `h5端仅在微信公众号中支持 API ${apiName}`;
93
+ const errMsg = `h5端当前仅在微信公众号JS-SDK环境下支持此 API ${apiName}`;
94
94
  if (process.env.NODE_ENV !== 'production') {
95
95
  console.error(errMsg);
96
96
  return Promise.reject({
@@ -122,51 +122,38 @@ export function permanentlyNotSupport(apiName) {
122
122
  }
123
123
  };
124
124
  }
125
- export function isFunction(obj) {
126
- return typeof obj === 'function';
127
- }
128
- const VALID_COLOR_REG = /^#[0-9a-fA-F]{6}$/;
129
- export const isValidColor = (color) => {
130
- return VALID_COLOR_REG.test(color);
131
- };
132
- export function processOpenApi(apiName, defaultOptions, formatResult = res => res, formatParams = options => options) {
133
- // @ts-ignore
134
- if (!window.wx) {
135
- return weixinCorpSupport(apiName);
136
- }
137
- return options => {
138
- options = options || {};
139
- const obj = Object.assign({}, defaultOptions, options);
140
- const p = new Promise((resolve, reject) => {
141
- ['fail', 'success', 'complete'].forEach(k => {
142
- obj[k] = oriRes => {
143
- const res = formatResult(oriRes);
144
- options[k] && options[k](res);
145
- if (k === 'success') {
146
- resolve(res);
147
- }
148
- else if (k === 'fail') {
149
- reject(res);
150
- }
151
- };
125
+ export function processOpenApi({ name, defaultOptions, standardMethod, formatOptions = options => options, formatResult = res => res }) {
126
+ const notSupported = weixinCorpSupport(name);
127
+ return (options = {}) => {
128
+ var _a;
129
+ // @ts-ignore
130
+ const targetApi = (_a = window === null || window === void 0 ? void 0 : window.wx) === null || _a === void 0 ? void 0 : _a[name];
131
+ const opts = formatOptions(Object.assign({}, defaultOptions, options));
132
+ if (typeof targetApi === 'function') {
133
+ return new Promise((resolve, reject) => {
134
+ ['fail', 'success', 'complete'].forEach(k => {
135
+ opts[k] = preRef => {
136
+ const res = formatResult(preRef);
137
+ options[k] && options[k](res);
138
+ if (k === 'success') {
139
+ resolve(res);
140
+ }
141
+ else if (k === 'fail') {
142
+ reject(res);
143
+ }
144
+ };
145
+ return targetApi(opts);
146
+ });
152
147
  });
153
- // @ts-ignore
154
- wx[apiName](formatParams(obj));
155
- });
156
- return p;
157
- };
158
- }
159
- /**
160
- * ease-in-out的函数
161
- * @param t 0-1的数字
162
- */
163
- export const easeInOut = (t) => t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
164
- export const getTimingFunc = (easeFunc, frameCnt) => {
165
- return x => {
166
- if (frameCnt <= 1) {
167
- return easeFunc(1);
168
148
  }
169
- const t = x / (frameCnt - 1);
170
- return easeFunc(t);
149
+ else if (typeof standardMethod === 'function') {
150
+ return standardMethod(opts);
151
+ }
152
+ else {
153
+ return notSupported();
154
+ }
171
155
  };
172
- };
156
+ }
157
+ export * from './animation';
158
+ export * from './lodash';
159
+ export * from './valid';
@@ -0,0 +1,29 @@
1
+ export function throttle(fn, threshold = 250, scope) {
2
+ let lastTime = 0;
3
+ let deferTimer;
4
+ return function (...args) {
5
+ const context = scope || this;
6
+ const now = Date.now();
7
+ if (now - lastTime > threshold) {
8
+ fn.apply(this, args);
9
+ lastTime = now;
10
+ }
11
+ else {
12
+ clearTimeout(deferTimer);
13
+ deferTimer = setTimeout(() => {
14
+ lastTime = now;
15
+ fn.apply(context, args);
16
+ }, threshold);
17
+ }
18
+ };
19
+ }
20
+ export function debounce(fn, ms = 250, scope) {
21
+ let timer;
22
+ return function (...args) {
23
+ const context = scope || this;
24
+ clearTimeout(timer);
25
+ timer = setTimeout(function () {
26
+ fn.apply(context, args);
27
+ }, ms);
28
+ };
29
+ }
@@ -0,0 +1,7 @@
1
+ export function isFunction(obj) {
2
+ return typeof obj === 'function';
3
+ }
4
+ const VALID_COLOR_REG = /^#[0-9a-fA-F]{6}$/;
5
+ export const isValidColor = (color) => {
6
+ return VALID_COLOR_REG.test(color);
7
+ };
@@ -1 +1,3 @@
1
- export declare const scanCode: (options: any) => Promise<unknown>;
1
+ export declare const scanCode: (options?: Partial<{
2
+ needResult: number;
3
+ }>) => Promise<any>;
@@ -0,0 +1,2 @@
1
+ import Taro from '@tarojs/api';
2
+ export declare const getLocation: (options?: Partial<Taro.getLocation.Option>) => Promise<Taro.getLocation.SuccessCallbackResult>;
@@ -7,7 +7,9 @@ export declare const startLocationUpdateBackground: () => Promise<{
7
7
  export declare const startLocationUpdate: () => Promise<{
8
8
  errMsg: string;
9
9
  }>;
10
- export declare const openLocation: (options: any) => Promise<unknown>;
10
+ export declare const openLocation: (options?: Partial<{
11
+ scale: number;
12
+ }>) => Promise<any>;
11
13
  export declare const onLocationChangeError: () => Promise<{
12
14
  errMsg: string;
13
15
  }>;
@@ -20,8 +22,8 @@ export declare const offLocationChangeError: () => Promise<{
20
22
  export declare const offLocationChange: () => Promise<{
21
23
  errMsg: string;
22
24
  }>;
23
- export declare const getLocation: (options: any) => Promise<unknown>;
25
+ export { getLocation } from './getLocation';
24
26
  export declare const choosePoi: () => Promise<{
25
27
  errMsg: string;
26
28
  }>;
27
- export * from './chooseLocation';
29
+ export { chooseLocation } from './chooseLocation';
@@ -0,0 +1,6 @@
1
+ /**
2
+ * ease-in-out的函数
3
+ * @param t 0-1的数字
4
+ */
5
+ export declare const easeInOut: (t: number) => number;
6
+ export declare const getTimingFunc: (easeFunc: any, frameCnt: any) => (x: any) => any;
@@ -26,13 +26,14 @@ export declare function weixinCorpSupport(apiName: any): () => Promise<{
26
26
  export declare function permanentlyNotSupport(apiName: any): () => Promise<{
27
27
  errMsg: string;
28
28
  }>;
29
- export declare function isFunction(obj: any): boolean;
30
- export declare const isValidColor: (color: any) => boolean;
31
- export declare function processOpenApi(apiName: string, defaultOptions?: Record<string, unknown>, formatResult?: (res: any) => any, formatParams?: (options: any) => any): (options: any) => Promise<unknown>;
32
- /**
33
- * ease-in-out的函数
34
- * @param t 0-1的数字
35
- */
36
- export declare const easeInOut: (t: number) => number;
37
- export declare const getTimingFunc: (easeFunc: any, frameCnt: any) => (x: any) => any;
38
- export {};
29
+ interface IProcessOpenApi<TOptions = Record<string, unknown>, TResult extends TaroGeneral.CallbackResult = any> {
30
+ name: string;
31
+ defaultOptions?: TOptions;
32
+ standardMethod?: (opts: TOptions) => Promise<TResult>;
33
+ formatOptions?: (opts: TOptions) => TOptions;
34
+ formatResult?: (res: TResult) => TResult;
35
+ }
36
+ export declare function processOpenApi<TOptions = Record<string, unknown>, TResult extends TaroGeneral.CallbackResult = any>({ name, defaultOptions, standardMethod, formatOptions, formatResult }: IProcessOpenApi<TOptions, TResult>): (options?: Partial<TOptions>) => Promise<TResult>;
37
+ export * from './animation';
38
+ export * from './lodash';
39
+ export * from './valid';
@@ -0,0 +1,2 @@
1
+ export declare function throttle(fn: any, threshold?: number, scope?: any): (...args: any[]) => void;
2
+ export declare function debounce(fn: any, ms?: number, scope?: any): (...args: any[]) => void;
@@ -0,0 +1,2 @@
1
+ export declare function isFunction(obj: any): boolean;
2
+ export declare const isValidColor: (color: any) => boolean;