utils.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. import { prefix } from './config';
  2. import { getWindowInfo, getAppBaseInfo, getDeviceInfo } from './wechat';
  3. export const systemInfo = getWindowInfo();
  4. export const appBaseInfo = getAppBaseInfo();
  5. export const deviceInfo = getDeviceInfo();
  6. export const debounce = function (func, wait = 500) {
  7. let timerId;
  8. return function (...rest) {
  9. if (timerId) {
  10. clearTimeout(timerId);
  11. }
  12. timerId = setTimeout(() => {
  13. func.apply(this, rest);
  14. }, wait);
  15. };
  16. };
  17. export const throttle = (func, wait = 100, options = null) => {
  18. let previous = 0;
  19. let timerid = null;
  20. if (!options) {
  21. options = {
  22. leading: true,
  23. };
  24. }
  25. return function (...args) {
  26. const now = Date.now();
  27. if (!previous && !options.leading)
  28. previous = now;
  29. const remaining = wait - (now - previous);
  30. const context = this;
  31. if (remaining <= 0) {
  32. if (timerid) {
  33. clearTimeout(timerid);
  34. timerid = null;
  35. }
  36. previous = now;
  37. func.apply(context, args);
  38. }
  39. };
  40. };
  41. export const classNames = function (...args) {
  42. const hasOwn = {}.hasOwnProperty;
  43. const classes = [];
  44. args.forEach((arg) => {
  45. if (!arg)
  46. return;
  47. const argType = typeof arg;
  48. if (argType === 'string' || argType === 'number') {
  49. classes.push(arg);
  50. }
  51. else if (Array.isArray(arg) && arg.length) {
  52. const inner = classNames(...arg);
  53. if (inner) {
  54. classes.push(inner);
  55. }
  56. }
  57. else if (argType === 'object') {
  58. for (const key in arg) {
  59. if (hasOwn.call(arg, key) && arg[key]) {
  60. classes.push(key);
  61. }
  62. }
  63. }
  64. });
  65. return classes.join(' ');
  66. };
  67. export const styles = function (styleObj) {
  68. return Object.keys(styleObj)
  69. .map((styleKey) => `${styleKey}: ${styleObj[styleKey]}`)
  70. .join('; ');
  71. };
  72. export const getAnimationFrame = function (context, cb) {
  73. return context
  74. .createSelectorQuery()
  75. .selectViewport()
  76. .boundingClientRect()
  77. .exec(() => {
  78. cb();
  79. });
  80. };
  81. export const getRect = function (context, selector, needAll = false) {
  82. return new Promise((resolve, reject) => {
  83. context
  84. .createSelectorQuery()[needAll ? 'selectAll' : 'select'](selector)
  85. .boundingClientRect((rect) => {
  86. if (rect) {
  87. resolve(rect);
  88. }
  89. else {
  90. reject(rect);
  91. }
  92. })
  93. .exec();
  94. });
  95. };
  96. export const isNumber = function (value) {
  97. return /^\d+(\.\d+)?$/.test(value);
  98. };
  99. export const isNull = function (value) {
  100. return value === null;
  101. };
  102. export const isUndefined = (value) => typeof value === 'undefined';
  103. export const isDef = function (value) {
  104. return !isUndefined(value) && !isNull(value);
  105. };
  106. export const isIOS = function () {
  107. var _a;
  108. return !!(((_a = deviceInfo === null || deviceInfo === void 0 ? void 0 : deviceInfo.system) === null || _a === void 0 ? void 0 : _a.toLowerCase().search('ios')) + 1);
  109. };
  110. export const addUnit = function (value) {
  111. if (!isDef(value)) {
  112. return undefined;
  113. }
  114. value = String(value);
  115. return isNumber(value) ? `${value}px` : value;
  116. };
  117. export const getCharacterLength = (type, char, max) => {
  118. const str = String(char !== null && char !== void 0 ? char : '');
  119. if (str.length === 0) {
  120. return {
  121. length: 0,
  122. characters: '',
  123. };
  124. }
  125. if (type === 'maxcharacter') {
  126. let len = 0;
  127. for (let i = 0; i < str.length; i += 1) {
  128. let currentStringLength = 0;
  129. if (str.charCodeAt(i) > 127 || str.charCodeAt(i) === 94) {
  130. currentStringLength = 2;
  131. }
  132. else {
  133. currentStringLength = 1;
  134. }
  135. if (len + currentStringLength > max) {
  136. return {
  137. length: len,
  138. characters: str.slice(0, i),
  139. };
  140. }
  141. len += currentStringLength;
  142. }
  143. return {
  144. length: len,
  145. characters: str,
  146. };
  147. }
  148. else if (type === 'maxlength') {
  149. const length = str.length > max ? max : str.length;
  150. return {
  151. length,
  152. characters: str.slice(0, length),
  153. };
  154. }
  155. return {
  156. length: str.length,
  157. characters: str,
  158. };
  159. };
  160. export const chunk = (arr, size) => Array.from({ length: Math.ceil(arr.length / size) }, (v, i) => arr.slice(i * size, i * size + size));
  161. export const getInstance = function (context, selector) {
  162. if (!context) {
  163. const pages = getCurrentPages();
  164. const page = pages[pages.length - 1];
  165. context = page.$$basePage || page;
  166. }
  167. const instance = context ? context.selectComponent(selector) : null;
  168. if (!instance) {
  169. console.warn('未找到组件,请检查selector是否正确');
  170. return null;
  171. }
  172. return instance;
  173. };
  174. export const unitConvert = (value) => {
  175. var _a;
  176. if (typeof value === 'string') {
  177. if (value.includes('rpx')) {
  178. return (parseInt(value, 10) * ((_a = systemInfo === null || systemInfo === void 0 ? void 0 : systemInfo.screenWidth) !== null && _a !== void 0 ? _a : 750)) / 750;
  179. }
  180. return parseInt(value, 10);
  181. }
  182. return value !== null && value !== void 0 ? value : 0;
  183. };
  184. export const setIcon = (iconName, icon, defaultIcon) => {
  185. if (icon) {
  186. if (typeof icon === 'string') {
  187. return {
  188. [`${iconName}Name`]: icon,
  189. [`${iconName}Data`]: {},
  190. };
  191. }
  192. else if (typeof icon === 'object') {
  193. return {
  194. [`${iconName}Name`]: '',
  195. [`${iconName}Data`]: icon,
  196. };
  197. }
  198. else {
  199. return {
  200. [`${iconName}Name`]: defaultIcon,
  201. [`${iconName}Data`]: {},
  202. };
  203. }
  204. }
  205. return {
  206. [`${iconName}Name`]: '',
  207. [`${iconName}Data`]: {},
  208. };
  209. };
  210. export const isBool = (val) => typeof val === 'boolean';
  211. export const isObject = (val) => typeof val === 'object' && val != null;
  212. export const isString = (val) => typeof val === 'string';
  213. export const toCamel = (str) => str.replace(/-(\w)/g, (match, m1) => m1.toUpperCase());
  214. export const getCurrentPage = function () {
  215. const pages = getCurrentPages();
  216. return pages[pages.length - 1];
  217. };
  218. export const uniqueFactory = (compName) => {
  219. let number = 0;
  220. return () => `${prefix}_${compName}_${number++}`;
  221. };
  222. export const calcIcon = (icon, defaultIcon) => {
  223. if (icon && ((isBool(icon) && defaultIcon) || isString(icon))) {
  224. return { name: isBool(icon) ? defaultIcon : icon };
  225. }
  226. if (isObject(icon)) {
  227. return icon;
  228. }
  229. return null;
  230. };
  231. export const isOverSize = (size, sizeLimit) => {
  232. var _a;
  233. if (!sizeLimit)
  234. return false;
  235. const base = 1000;
  236. const unitMap = {
  237. B: 1,
  238. KB: base,
  239. MB: base * base,
  240. GB: base * base * base,
  241. };
  242. const computedSize = typeof sizeLimit === 'number' ? sizeLimit * base : (sizeLimit === null || sizeLimit === void 0 ? void 0 : sizeLimit.size) * unitMap[(_a = sizeLimit === null || sizeLimit === void 0 ? void 0 : sizeLimit.unit) !== null && _a !== void 0 ? _a : 'KB'];
  243. return size > computedSize;
  244. };
  245. export const rpx2px = (rpx) => Math.floor((systemInfo.windowWidth * rpx) / 750);
  246. export const nextTick = () => {
  247. return new Promise((resolve) => {
  248. wx.nextTick(() => {
  249. resolve();
  250. });
  251. });
  252. };