utils.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. }