utils.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { isNumber, isPlainObject } from './validator';
  2. export function isDef(value) {
  3. return value !== undefined && value !== null;
  4. }
  5. export function isObj(x) {
  6. const type = typeof x;
  7. return x !== null && (type === 'object' || type === 'function');
  8. }
  9. export function range(num, min, max) {
  10. return Math.min(Math.max(num, min), max);
  11. }
  12. export function nextTick(fn) {
  13. setTimeout(() => {
  14. fn();
  15. }, 1000 / 30);
  16. }
  17. let systemInfo;
  18. export function getSystemInfoSync() {
  19. if (systemInfo == null) {
  20. systemInfo = wx.getSystemInfoSync();
  21. }
  22. return systemInfo;
  23. }
  24. export function addUnit(value) {
  25. if (!isDef(value)) {
  26. return undefined;
  27. }
  28. value = String(value);
  29. return isNumber(value) ? `${value}px` : value;
  30. }
  31. export function requestAnimationFrame(cb) {
  32. const systemInfo = getSystemInfoSync();
  33. if (systemInfo.platform === 'devtools') {
  34. return nextTick(cb);
  35. }
  36. return wx
  37. .createSelectorQuery()
  38. .selectViewport()
  39. .boundingClientRect()
  40. .exec(() => {
  41. cb();
  42. });
  43. }
  44. export function pickExclude(obj, keys) {
  45. if (!isPlainObject(obj)) {
  46. return {};
  47. }
  48. return Object.keys(obj).reduce((prev, key) => {
  49. if (!keys.includes(key)) {
  50. prev[key] = obj[key];
  51. }
  52. return prev;
  53. }, {});
  54. }
  55. export function getRect(selector) {
  56. return new Promise((resolve) => {
  57. wx.createSelectorQuery()
  58. .in(this)
  59. .select(selector)
  60. .boundingClientRect()
  61. .exec((rect = []) => resolve(rect[0]));
  62. });
  63. }
  64. export function getAllRect(selector) {
  65. return new Promise((resolve) => {
  66. wx.createSelectorQuery()
  67. .in(this)
  68. .selectAll(selector)
  69. .boundingClientRect()
  70. .exec((rect = []) => resolve(rect[0]));
  71. });
  72. }