utils.js 1.9 KB

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