1
0

Tools.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. /**
  2. * 工具类
  3. */
  4. export const setDocumentTitle = title => {
  5. /**
  6. * 修改浏览器title 兼容ios
  7. */
  8. document.title = title;
  9. if (window.Env.isIos) {
  10. const i = document.createElement('iframe');
  11. i.src = '/favicon.ico';
  12. i.style.display = 'none';
  13. i.onload = () => {
  14. setTimeout(() => {
  15. i.remove();
  16. }, 10);
  17. };
  18. setTimeout(() => {
  19. document.body.appendChild(i);
  20. }, 500);
  21. }
  22. };
  23. export const setCookie = (name, value, time) => {
  24. const exp = new Date();
  25. exp.setTime(exp.getTime() + time * 1000);
  26. document.cookie = `${name}=${escape(value)};expires=${exp.toGMTString()};path=/`;
  27. };
  28. export const getCookie = name => {
  29. const reg = new RegExp(`(^| )${name}=([^;]*)(;|$)`);
  30. const arr = reg;
  31. if (arr === document.cookie.match(reg)) {
  32. return unescape(arr[2]);
  33. }
  34. return null;
  35. };
  36. export const delCookie = name => {
  37. const exp = new Date();
  38. exp.setTime(exp.getTime() - 1);
  39. const cval = window.getCookie(name);
  40. if (cval != null) {
  41. document.cookie = `${name}=${cval};expires=${exp.toGMTString()};path=/`;
  42. }
  43. };
  44. export const getQuery = name => {
  45. /**
  46. * 获取url参数
  47. */
  48. const reg = new RegExp(`(^|\\?|&)${name}=([^&]*)(&|$)`);
  49. const r = window.location.href.substr(1).match(reg);
  50. if (r != null) return unescape(r[2]);
  51. return null;
  52. };
  53. export function formatUrl(path, query) {
  54. let url = query ? `${path}?` : path;
  55. if (query) {
  56. Object.keys(query).forEach(i => {
  57. if (query[i] instanceof Object && query[i].length > 0) {
  58. query[i].forEach(k => {
  59. url += `${i}[]=${k}&`;
  60. });
  61. } else if (query[i] || query[i] === 0) {
  62. url += `${i}=${query[i]}&`;
  63. }
  64. });
  65. }
  66. return url;
  67. }
  68. export function checkMobile(s) {
  69. const { length } = s;
  70. if (length === 11 && /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(14[0-9]{1})|)+\d{8})$/.test(s)) {
  71. return true;
  72. }
  73. return false;
  74. }
  75. export function checkEmail(s) {
  76. if (/^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(s)) {
  77. return true;
  78. }
  79. return false;
  80. }
  81. export function loadScript(url, callback) {
  82. const script = document.createElement('script');
  83. script.type = 'text/javascript';
  84. script.async = true;
  85. script.defer = true;
  86. if (script.readyState) {
  87. script.onreadystatechange = function () {
  88. if (script.readyState === 'loaded' || script.readyState === 'complete') {
  89. script.onreadystatechange = null;
  90. if (callback) callback();
  91. }
  92. };
  93. } else {
  94. script.onload = function () {
  95. if (callback) callback();
  96. };
  97. }
  98. script.src = url;
  99. const head = document.getElementsByTagName('head')[0];
  100. head.appendChild(script);
  101. }
  102. export function generateUUID(len, radix) {
  103. const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  104. const id = [];
  105. radix = radix || chars.length;
  106. if (len) {
  107. for (let i = 0; i < len; i += 1) id[i] = chars[0 | (Math.random() * radix)];
  108. } else {
  109. id[8] = id[13] = id[18] = id[23] = '-';
  110. id[14] = '4';
  111. for (let i = 0; i < 36; i += 1) {
  112. if (!id[i]) {
  113. const r = 0 | (Math.random() * 16);
  114. id[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r];
  115. }
  116. }
  117. }
  118. return id.join('');
  119. }
  120. export function SortBy(a, b, asc, type) {
  121. if (!a && a !== 0) {
  122. return 1;
  123. }
  124. if (!b && b !== 0) {
  125. return -1;
  126. }
  127. if (a === b) {
  128. return 0;
  129. }
  130. if (a === '') {
  131. return 1;
  132. }
  133. if (b === '') {
  134. return -1;
  135. }
  136. a = `${a}`;
  137. b = `${b}`;
  138. return (
  139. (type === 'number'
  140. ? a.localeCompare(b, undefined, { numeric: true })
  141. : a.localeCompare(b, 'zh', { co: 'pinyin' })) * asc
  142. );
  143. }
  144. export function SortByProps(item1, item2, props) {
  145. const cps = [];
  146. for (let i = 0; i < props.length; i += 1) {
  147. const prop = props[i];
  148. const asc = prop.direction > 0 ? 1 : -1;
  149. cps.push(SortBy(item1[prop.key], item2[prop.key], asc, prop.type));
  150. }
  151. for (let j = 0; j < cps.length; j += 1) {
  152. if (cps[j] === 1 || cps[j] === -1) {
  153. return cps[j];
  154. }
  155. }
  156. return false;
  157. }
  158. export function getMap(list, key = 'value', value = null) {
  159. const map = {};
  160. for (let i = 0; i < list.length; i += 1) {
  161. map[list[i][key]] = value ? list[i][value] : list[i];
  162. }
  163. return map;
  164. }
  165. export function searchKeyword(data, key, keyword, limit) {
  166. const list = [];
  167. const tmp = {};
  168. for (let i = 0; i < data.length; i += 1) {
  169. const item = key ? data[i][key] : data[i];
  170. if (item && !tmp[item] && item.indexOf(keyword) >= 0) {
  171. list.push(item);
  172. tmp[item] = true;
  173. if (limit && list.length >= limit) break;
  174. }
  175. }
  176. return list;
  177. }
  178. export function search(data = [], key, value) {
  179. const index = -1;
  180. for (let i = 0; i < data.length; i += 1) {
  181. if ((key && data[i][key] === value) || data[i] === value) {
  182. return i;
  183. }
  184. }
  185. return index;
  186. }
  187. export function formatSecond(value) {
  188. let secondTime = parseInt(value, 10); // 秒
  189. let minuteTime = 0;
  190. let hourTime = 0;
  191. if (secondTime > 60) {
  192. minuteTime = parseInt(secondTime / 60, 10);
  193. secondTime = parseInt(secondTime % 60, 10);
  194. hourTime = parseInt(minuteTime / 60, 10);
  195. minuteTime = parseInt(minuteTime % 60, 10);
  196. }
  197. if (hourTime >= 10) {
  198. hourTime = `${hourTime}`;
  199. } else {
  200. hourTime = `0${hourTime}`;
  201. }
  202. if (minuteTime >= 10) {
  203. minuteTime = `${minuteTime}`;
  204. } else {
  205. minuteTime = `0${minuteTime}`;
  206. }
  207. if (secondTime >= 10) {
  208. secondTime = `${secondTime}`;
  209. } else {
  210. secondTime = `0${secondTime}`;
  211. }
  212. return `${hourTime}:${minuteTime}:${secondTime}`;
  213. }
  214. export function formatFormError(data, err, prefix = '') {
  215. const r = {};
  216. Object.keys(err).forEach(field => {
  217. r[`${prefix}${field}`] = { value: data[field], errors: err[field].map(e => new Error(e)) };
  218. });
  219. return r;
  220. }
  221. export function formatDate(time, format = 'YYYY-MM-DD HH:mm:ss') {
  222. const date = new Date(time);
  223. const o = {
  224. 'M+': date.getMonth() + 1,
  225. 'D+': date.getDate(),
  226. 'H+': date.getHours(),
  227. 'm+': date.getMinutes(),
  228. 's+': date.getSeconds(),
  229. 'q+': Math.floor((date.getMonth() + 3) / 3),
  230. S: date.getMilliseconds(),
  231. };
  232. if (/(Y+)/.test(format)) format = format.replace(RegExp.$1, `${date.getFullYear()}`.substr(4 - RegExp.$1.length));
  233. Object.keys(o).forEach(k => {
  234. if (new RegExp(`(${k})`).test(format)) {
  235. format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length));
  236. }
  237. });
  238. return format;
  239. }
  240. export function formatSeconds(seconds) {
  241. const time = parseInt(seconds, 10);
  242. if (time < 60) {
  243. return `${time}s`;
  244. }
  245. if (time >= 60 && time < 3600) {
  246. return `${parseInt(time / 60, 10)}m${formatSeconds(time % 60)}`;
  247. }
  248. return `${parseInt(time / 3600, 10)}h${formatSecond(time % 3600)}`;
  249. }
  250. export function formatPercent(child, mother) {
  251. if (!mother || !child) return '0%';
  252. return `${Math.floor((child * 100) / mother)}% `;
  253. }
  254. export function formatTreeData(list, key = 'id', title = 'title', index = 'parent_id') {
  255. const map = getMap(list, key);
  256. const result = [];
  257. list.forEach(row => {
  258. row.children = [];
  259. row.title = row[title];
  260. if (!row.key) row.key = `${row[key]} `;
  261. row.value = row[key];
  262. });
  263. list.forEach(row => {
  264. if (row[index] && map[row[index]]) {
  265. if (!map[row[index]].children) map[row[index]].children = [];
  266. map[row[index]].children.push(row);
  267. } else {
  268. result.push(row);
  269. }
  270. });
  271. return result;
  272. }
  273. export function flattenObject(ob, prefix = '') {
  274. const toReturn = {};
  275. if (prefix) prefix = `${prefix}.`;
  276. Object.keys(ob).forEach(i => {
  277. if (typeof ob[i] === 'object' && ob[i] !== null) {
  278. const flatObject = flattenObject(ob[i]);
  279. Object.keys(flatObject).forEach(x => {
  280. toReturn[`${prefix} ${i}.${x} `] = flatObject[x];
  281. });
  282. } else {
  283. toReturn[`${prefix} ${i} `] = ob[i];
  284. }
  285. });
  286. return toReturn;
  287. }
  288. function _formatMoney(s, n) {
  289. if (!s) s = 0;
  290. n = n > 0 && n <= 20 ? n : 2;
  291. s = `${parseFloat(`${s}`.replace(/[^\d.-]/g, '')).toFixed(n)} `;
  292. const l = s
  293. .split('.')[0]
  294. .split('')
  295. .reverse();
  296. const r = s.split('.')[1];
  297. let t = '';
  298. for (let i = 0; i < l.length; i += 1) {
  299. t += l[i] + ((i + 1) % 3 === 0 && i + 1 !== l.length ? ',' : '');
  300. }
  301. return `${t.split('').reverse().join('')}.${r} `;
  302. }
  303. export function formatMoney(price) {
  304. if (typeof price === 'object') {
  305. return `${price.symbol} ${_formatMoney(price.value, 2)} `;
  306. }
  307. return `¥${_formatMoney(price, 2)} `;
  308. }
  309. export function bindTags(targetList, field, render, def, notFound) {
  310. let index = -1;
  311. targetList.forEach((row, i) => {
  312. if (row.key === field) index = i;
  313. });
  314. targetList[index].notFoundContent = notFound;
  315. targetList[index].select = (def || []).map(row => {
  316. return render(row);
  317. });
  318. }
  319. export function bindSearch(targetList, field, Component, listFunc, render, def, notFound = null) {
  320. let index = -1;
  321. targetList.forEach((row, i) => {
  322. if (row.key === field) index = i;
  323. });
  324. const key = `lastFetchId${field} ${index} `;
  325. if (!Component[key]) Component[key] = 0;
  326. const searchFunc = data => {
  327. Component[key] += 1;
  328. const fetchId = Component[key];
  329. targetList[index].loading = true;
  330. Component.setState({ fetching: true });
  331. listFunc(data).then(result => {
  332. if (fetchId !== Component[key]) {
  333. // for fetch callback order
  334. return;
  335. }
  336. targetList[index].select = (result.list || result || []).map(row => {
  337. return render(row);
  338. });
  339. targetList[index].loading = false;
  340. Component.setState({ fetching: false });
  341. });
  342. };
  343. const item = {
  344. showSearch: true,
  345. showArrow: true,
  346. filterOption: false,
  347. onSearch: keyword => {
  348. searchFunc({ page: 1, number: 5, keyword });
  349. },
  350. notFoundContent: notFound,
  351. };
  352. targetList[index] = Object.assign(targetList[index], item);
  353. if (def) {
  354. if (targetList[index].type === 'multiple' || targetList[index].mode === 'multiple') {
  355. searchFunc({ ids: def, page: 1, number: def.length });
  356. } else {
  357. searchFunc({ ids: [def], page: 1, number: 1 });
  358. }
  359. } else {
  360. item.onSearch();
  361. }
  362. }
  363. export function generateSearch(field, props, Component, listFunc, render, def, notFound = null) {
  364. const key = `lastFetchId${field} `;
  365. if (!Component[key]) Component[key] = 0;
  366. let item = {
  367. showSearch: true,
  368. showArrow: true,
  369. filterOption: false,
  370. notFoundContent: notFound,
  371. };
  372. item = Object.assign(props || {}, item);
  373. const searchFunc = data => {
  374. Component[key] += 1;
  375. const fetchId = Component[key];
  376. item.loading = true;
  377. Component.setState({ [field]: item, fetching: true });
  378. listFunc(data).then(result => {
  379. if (fetchId !== Component[key]) {
  380. // for fetch callback order
  381. return;
  382. }
  383. item.select = result.list.map(row => {
  384. return render(row);
  385. });
  386. item.loading = false;
  387. Component.setState({ [field]: item, fetching: false });
  388. });
  389. };
  390. item.onSearch = keyword => {
  391. searchFunc({ page: 1, number: 5, keyword });
  392. };
  393. if (def) {
  394. if (item.mode === 'multiple' || item.type === 'multiple') {
  395. searchFunc({ ids: def, page: 1, number: def.length });
  396. } else {
  397. searchFunc({ ids: [def], page: 1, number: 1 });
  398. }
  399. } else {
  400. item.onSearch();
  401. }
  402. Component.setState({ [field]: item });
  403. }
  404. export function getHtmlText(text) {
  405. text = text.replace(new RegExp(/\r\n/, 'g'), '\r').replace(new RegExp(/\n/, 'g'), '\r');
  406. let html = '';
  407. text.split('\r').forEach(item => {
  408. item.split(' ').forEach(t => {
  409. html += `< i uuid = "${generateUUID(4)}" > ${t}</i > `;
  410. });
  411. html += '<br/>';
  412. });
  413. return html;
  414. }
  415. export function getSimpleText(html) {
  416. let text = html.replace(new RegExp('<br/>', 'g'), '\n\r');
  417. text = text.replace(new RegExp('<.+?>', 'g'), '');
  418. return text;
  419. }