utils.js 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { isDef, isNumber, isPlainObject, isPromise } from './validator';
  2. import { canIUseGroupSetData, canIUseNextTick } from './version';
  3. export { isDef } from './validator';
  4. export function range(num, min, max) {
  5. return Math.min(Math.max(num, min), max);
  6. }
  7. export function nextTick(cb) {
  8. if (canIUseNextTick()) {
  9. wx.nextTick(cb);
  10. }
  11. else {
  12. setTimeout(() => {
  13. cb();
  14. }, 1000 / 30);
  15. }
  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 setTimeout(() => {
  35. cb();
  36. }, 1000 / 30);
  37. }
  38. return wx
  39. .createSelectorQuery()
  40. .selectViewport()
  41. .boundingClientRect()
  42. .exec(() => {
  43. cb();
  44. });
  45. }
  46. export function pickExclude(obj, keys) {
  47. if (!isPlainObject(obj)) {
  48. return {};
  49. }
  50. return Object.keys(obj).reduce((prev, key) => {
  51. if (!keys.includes(key)) {
  52. prev[key] = obj[key];
  53. }
  54. return prev;
  55. }, {});
  56. }
  57. export function getRect(context, selector) {
  58. return new Promise((resolve) => {
  59. wx.createSelectorQuery()
  60. .in(context)
  61. .select(selector)
  62. .boundingClientRect()
  63. .exec((rect = []) => resolve(rect[0]));
  64. });
  65. }
  66. export function getAllRect(context, selector) {
  67. return new Promise((resolve) => {
  68. wx.createSelectorQuery()
  69. .in(context)
  70. .selectAll(selector)
  71. .boundingClientRect()
  72. .exec((rect = []) => resolve(rect[0]));
  73. });
  74. }
  75. export function groupSetData(context, cb) {
  76. if (canIUseGroupSetData()) {
  77. context.groupSetData(cb);
  78. }
  79. else {
  80. cb();
  81. }
  82. }
  83. export function toPromise(promiseLike) {
  84. if (isPromise(promiseLike)) {
  85. return promiseLike;
  86. }
  87. return Promise.resolve(promiseLike);
  88. }
  89. export function getCurrentPage() {
  90. const pages = getCurrentPages();
  91. return pages[pages.length - 1];
  92. }