z-paging-utils.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. // [z-paging]工具类
  2. import zLocalConfig from '../config/index'
  3. import c from './z-paging-constant'
  4. const storageKey = 'Z-PAGING-REFRESHER-TIME-STORAGE-KEY';
  5. let config = null;
  6. let configLoaded = false;
  7. const timeoutMap = {};
  8. // 获取默认配置信息
  9. function gc(key, defaultValue) {
  10. // 这里return一个函数以解决在vue3+appvue中,props默认配置读取在main.js之前执行导致uni.$zp全局配置无效的问题。相当于props的default中传入一个带有返回值的函数
  11. return () => {
  12. // 处理z-paging全局配置
  13. _handleDefaultConfig();
  14. // 如果全局配置不存在,则返回默认值
  15. if (!config) return defaultValue;
  16. const value = config[key];
  17. // 如果全局配置存在但对应的配置项不存在,则返回默认值;反之返回配置项
  18. return value === undefined ? defaultValue : value;
  19. };
  20. }
  21. // 获取最终的touch位置
  22. function getTouch(e) {
  23. let touch = null;
  24. if (e.touches && e.touches.length) {
  25. touch = e.touches[0];
  26. } else if (e.changedTouches && e.changedTouches.length) {
  27. touch = e.changedTouches[0];
  28. } else if (e.datail && e.datail != {}) {
  29. touch = e.datail;
  30. } else {
  31. return { touchX: 0, touchY: 0 }
  32. }
  33. return {
  34. touchX: touch.clientX,
  35. touchY: touch.clientY
  36. };
  37. }
  38. // 判断当前手势是否在z-paging内触发
  39. function getTouchFromZPaging(target) {
  40. if (target && target.tagName && target.tagName !== 'BODY' && target.tagName !== 'UNI-PAGE-BODY') {
  41. const classList = target.classList;
  42. if (classList && classList.contains('z-paging-content')) {
  43. // 此处额外记录当前z-paging是否是页面滚动、是否滚动到了顶部、是否是聊天记录模式以传给renderjs。避免不同z-paging组件renderjs内部判断数据互相影响导致的各种问题
  44. return {
  45. isFromZp: true,
  46. isPageScroll: classList.contains('z-paging-content-page'),
  47. isReachedTop: classList.contains('z-paging-reached-top'),
  48. isUseChatRecordMode: classList.contains('z-paging-use-chat-record-mode')
  49. };
  50. } else {
  51. return getTouchFromZPaging(target.parentNode);
  52. }
  53. } else {
  54. return { isFromZp: false };
  55. }
  56. }
  57. // 递归获取z-paging所在的parent,如果查找不到则返回null
  58. function getParent(parent) {
  59. if (!parent) return null;
  60. if (parent.$refs.paging) return parent;
  61. return getParent(parent.$parent);
  62. }
  63. // 打印错误信息
  64. function consoleErr(err) {
  65. console.error(`[z-paging]${err}`);
  66. }
  67. // 延时操作,如果key存在,调用时清除对应key之前的延时操作
  68. function delay(callback, ms = c.delayTime, key) {
  69. const timeout = setTimeout(callback, ms);;
  70. if (!!key) {
  71. timeoutMap[key] && clearTimeout(timeoutMap[key]);
  72. timeoutMap[key] = timeout;
  73. }
  74. return timeout;
  75. }
  76. // 设置下拉刷新时间
  77. function setRefesrherTime(time, key) {
  78. const datas = getRefesrherTime() || {};
  79. datas[key] = time;
  80. uni.setStorageSync(storageKey, datas);
  81. }
  82. // 获取下拉刷新时间
  83. function getRefesrherTime() {
  84. return uni.getStorageSync(storageKey);
  85. }
  86. // 通过下拉刷新标识key获取下拉刷新时间
  87. function getRefesrherTimeByKey(key) {
  88. const datas = getRefesrherTime();
  89. return datas && datas[key] ? datas[key] : null;
  90. }
  91. // 通过下拉刷新标识key获取下拉刷新时间(格式化之后)
  92. function getRefesrherFormatTimeByKey(key, textMap) {
  93. const time = getRefesrherTimeByKey(key);
  94. const timeText = time ? _timeFormat(time, textMap) : textMap.none;
  95. return `${textMap.title}${timeText}`;
  96. }
  97. // 将文本的px或者rpx转为px的值
  98. function convertToPx(text) {
  99. const dataType = Object.prototype.toString.call(text);
  100. if (dataType === '[object Number]') return text;
  101. let isRpx = false;
  102. if (text.indexOf('rpx') !== -1 || text.indexOf('upx') !== -1) {
  103. text = text.replace('rpx', '').replace('upx', '');
  104. isRpx = true;
  105. } else if (text.indexOf('px') !== -1) {
  106. text = text.replace('px', '');
  107. }
  108. if (!isNaN(text)) {
  109. if (isRpx) return Number(uni.upx2px(text));
  110. return Number(text);
  111. }
  112. return 0;
  113. }
  114. // 获取当前时间
  115. function getTime() {
  116. return (new Date()).getTime();
  117. }
  118. // 获取z-paging实例id,随机生成10位数字+字母
  119. function getInstanceId() {
  120. const s = [];
  121. const hexDigits = "0123456789abcdef";
  122. for (let i = 0; i < 10; i++) {
  123. s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  124. }
  125. return s.join('') + getTime();
  126. }
  127. // 等待一段时间
  128. function wait(ms) {
  129. return new Promise(resolve => {
  130. setTimeout(resolve, ms);
  131. });
  132. }
  133. // 是否是promise
  134. function isPromise(func) {
  135. return Object.prototype.toString.call(func) === '[object Promise]';
  136. }
  137. // 添加单位
  138. function addUnit(value, unit) {
  139. if (Object.prototype.toString.call(value) === '[object String]') {
  140. let tempValue = value;
  141. tempValue = tempValue.replace('rpx', '').replace('upx', '').replace('px', '');
  142. if (value.indexOf('rpx') === -1 && value.indexOf('upx') === -1 && value.indexOf('px') !== -1) {
  143. tempValue = parseFloat(tempValue) * 2;
  144. }
  145. value = tempValue;
  146. }
  147. return unit === 'rpx' ? value + 'rpx' : (value / 2) + 'px';
  148. }
  149. // 深拷贝
  150. function deepCopy(obj) {
  151. if (typeof obj !== 'object' || obj === null) return obj;
  152. let newObj = Array.isArray(obj) ? [] : {};
  153. for (let key in obj) {
  154. if (obj.hasOwnProperty(key)) {
  155. newObj[key] = deepCopy(obj[key]);
  156. }
  157. }
  158. return newObj;
  159. }
  160. // ------------------ 私有方法 ------------------------
  161. // 处理全局配置
  162. function _handleDefaultConfig() {
  163. // 确保只加载一次全局配置
  164. if (configLoaded) return;
  165. // 优先从config.js中读取
  166. if (zLocalConfig && Object.keys(zLocalConfig).length) {
  167. config = zLocalConfig;
  168. }
  169. // 如果在config.js中读取不到,则尝试到uni.$zp读取
  170. if (!config && uni.$zp) {
  171. config = uni.$zp.config;
  172. }
  173. // 将config中的短横线写法全部转为驼峰写法,使得读取配置时可以直接通过key去匹配,而非读取每个配置时候再去转,减少不必要的性能开支
  174. config = config ? Object.keys(config).reduce((result, key) => {
  175. result[_toCamelCase(key)] = config[key];
  176. return result;
  177. }, {}) : null;
  178. configLoaded = true;
  179. }
  180. // 时间格式化
  181. function _timeFormat(time, textMap) {
  182. const date = new Date(time);
  183. const currentDate = new Date();
  184. // 设置time对应的天,去除时分秒,使得可以直接比较日期
  185. const dateDay = new Date(time).setHours(0, 0, 0, 0);
  186. // 设置当前的天,去除时分秒,使得可以直接比较日期
  187. const currentDateDay = new Date().setHours(0, 0, 0, 0);
  188. const disTime = dateDay - currentDateDay;
  189. let dayStr = '';
  190. const timeStr = _dateTimeFormat(date);
  191. if (disTime === 0) {
  192. dayStr = textMap.today;
  193. } else if (disTime === -86400000) {
  194. dayStr = textMap.yesterday;
  195. } else {
  196. dayStr = _dateDayFormat(date, date.getFullYear() !== currentDate.getFullYear());
  197. }
  198. return `${dayStr} ${timeStr}`;
  199. }
  200. // date格式化为年月日
  201. function _dateDayFormat(date, showYear = true) {
  202. const year = date.getFullYear();
  203. const month = date.getMonth() + 1;
  204. const day = date.getDate();
  205. return showYear ? `${year}-${_fullZeroToTwo(month)}-${_fullZeroToTwo(day)}` : `${_fullZeroToTwo(month)}-${_fullZeroToTwo(day)}`;
  206. }
  207. // data格式化为时分
  208. function _dateTimeFormat(date) {
  209. const hour = date.getHours();
  210. const minute = date.getMinutes();
  211. return `${_fullZeroToTwo(hour)}:${_fullZeroToTwo(minute)}`;
  212. }
  213. // 不满2位在前面填充0
  214. function _fullZeroToTwo(str) {
  215. str = str.toString();
  216. return str.length === 1 ? '0' + str : str;
  217. }
  218. // 驼峰转短横线
  219. function _toKebab(value) {
  220. return value.replace(/([A-Z])/g, "-$1").toLowerCase();
  221. }
  222. // 短横线转驼峰
  223. function _toCamelCase(value) {
  224. return value.replace(/-([a-z])/g, (_, group1) => group1.toUpperCase());
  225. }
  226. export default {
  227. gc,
  228. setRefesrherTime,
  229. getRefesrherFormatTimeByKey,
  230. getTouch,
  231. getTouchFromZPaging,
  232. getParent,
  233. convertToPx,
  234. getTime,
  235. getInstanceId,
  236. consoleErr,
  237. delay,
  238. wait,
  239. isPromise,
  240. addUnit,
  241. deepCopy
  242. };