Tools.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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 flattenTree(tree, fn, children = 'children') {
  159. const l = tree.map(item => {
  160. if (item[children] && item[children].length > 0) {
  161. const list = flattenTree(item[children], fn, children);
  162. return list.map((row) => fn(row, item));
  163. }
  164. return [item];
  165. });
  166. return [].concat(...l);
  167. }
  168. export function getMap(list, key = 'value', value = null, children = null) {
  169. const map = {};
  170. for (let i = 0; i < list.length; i += 1) {
  171. const item = list[i];
  172. let v = value ? item[value] : item;
  173. if (children && item[children] && item[children].length > 0) {
  174. v = getMap(item[children], key, value, children);
  175. }
  176. map[item[key]] = v;
  177. }
  178. return map;
  179. }
  180. export function searchKeyword(data, key, keyword, limit) {
  181. const list = [];
  182. const tmp = {};
  183. for (let i = 0; i < data.length; i += 1) {
  184. const item = key ? data[i][key] : data[i];
  185. if (item && !tmp[item] && item.indexOf(keyword) >= 0) {
  186. list.push(item);
  187. tmp[item] = true;
  188. if (limit && list.length >= limit) break;
  189. }
  190. }
  191. return list;
  192. }
  193. export function search(data = [], key, value) {
  194. const index = -1;
  195. for (let i = 0; i < data.length; i += 1) {
  196. if ((key && data[i][key] === value) || data[i] === value) {
  197. return i;
  198. }
  199. }
  200. return index;
  201. }
  202. export function dataURLtoBlob(dataurl) {
  203. const arr = dataurl.split(',');
  204. const mime = arr[0].match(/:(.*?);/)[1];
  205. const bstr = atob(arr[1]);
  206. const n = bstr.length;
  207. const u8arr = new Uint8Array(n);
  208. for (let i = 0; i < n; i += 1) {
  209. u8arr[i] = bstr.charCodeAt(i);
  210. }
  211. return new Blob([u8arr], { type: mime });
  212. }
  213. export function formatSecond(value) {
  214. let secondTime = parseInt(value || 0, 10); // 秒
  215. let minuteTime = 0;
  216. let hourTime = 0;
  217. if (secondTime > 60) {
  218. minuteTime = parseInt(secondTime / 60, 10);
  219. secondTime = parseInt(secondTime % 60, 10);
  220. hourTime = parseInt(minuteTime / 60, 10);
  221. minuteTime = parseInt(minuteTime % 60, 10);
  222. }
  223. if (hourTime >= 10) {
  224. hourTime = `${hourTime}`;
  225. } else {
  226. hourTime = `0${hourTime}`;
  227. }
  228. if (minuteTime >= 10) {
  229. minuteTime = `${minuteTime}`;
  230. } else {
  231. minuteTime = `0${minuteTime}`;
  232. }
  233. if (secondTime >= 10) {
  234. secondTime = `${secondTime}`;
  235. } else {
  236. secondTime = `0${secondTime}`;
  237. }
  238. return `${hourTime}:${minuteTime}:${secondTime}`;
  239. }
  240. export function formatMinuteSecond(value) {
  241. let secondTime = parseInt(value || 0, 10); // 秒
  242. let minuteTime = 0;
  243. if (secondTime > 60) {
  244. minuteTime = parseInt(secondTime / 60, 10);
  245. secondTime = parseInt(secondTime % 60, 10);
  246. }
  247. if (minuteTime >= 10) {
  248. minuteTime = `${minuteTime}`;
  249. } else {
  250. minuteTime = `0${minuteTime}`;
  251. }
  252. if (secondTime >= 10) {
  253. secondTime = `${secondTime}`;
  254. } else {
  255. secondTime = `0${secondTime}`;
  256. }
  257. return `${minuteTime}:${secondTime}`;
  258. }
  259. export function formatFormError(data, err, prefix = '') {
  260. const r = {};
  261. Object.keys(err).forEach(field => {
  262. r[`${prefix}${field}`] = { value: data[field], errors: err[field].map(e => new Error(e)) };
  263. });
  264. return r;
  265. }
  266. export function formatDate(time, format = 'YYYY-MM-DD HH:mm:ss') {
  267. const date = new Date(time);
  268. const o = {
  269. 'M+': date.getMonth() + 1,
  270. 'D+': date.getDate(),
  271. 'H+': date.getHours(),
  272. 'm+': date.getMinutes(),
  273. 's+': date.getSeconds(),
  274. 'q+': Math.floor((date.getMonth() + 3) / 3),
  275. S: date.getMilliseconds(),
  276. };
  277. if (/(Y+)/.test(format)) format = format.replace(RegExp.$1, `${date.getFullYear()}`.substr(4 - RegExp.$1.length));
  278. Object.keys(o).forEach(k => {
  279. if (new RegExp(`(${k})`).test(format)) {
  280. format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length));
  281. }
  282. });
  283. return format;
  284. }
  285. export function formatMinute(seconds, number = true) {
  286. const time = parseInt(seconds || 0, 10);
  287. return number ? parseInt(time / 60, 10) : `${parseInt(time / 60, 10)}min`;
  288. }
  289. export function formatSeconds(seconds, rand = false) {
  290. const time = parseInt(seconds || 0, 10);
  291. if (time < 60) {
  292. return `${time}s`;
  293. }
  294. if (time >= 60 && time < 3600) {
  295. return `${parseInt(time / 60, 10)}min${rand ? '' : formatSeconds(time % 60)}`;
  296. }
  297. return `${parseInt(time / 3600, 10)}hour${rand ? '' : formatSecond(time % 3600)}hour`;
  298. }
  299. export function formatPercent(child, mother, number = true) {
  300. if (!mother || !child) return number ? 0 : '0%';
  301. return number ? Math.floor((child * 100) / mother) : `${Math.floor((child * 100) / mother)}%`;
  302. }
  303. export function formatTreeData(list, key = 'id', title = 'title', index = 'parent_id') {
  304. const map = getMap(list, key);
  305. const result = [];
  306. list.forEach(row => {
  307. row.children = [];
  308. row.title = row[title];
  309. if (!row.key) row.key = `${row[key]}`;
  310. row.value = row[key];
  311. });
  312. list.forEach(row => {
  313. if (row[index] && map[row[index]]) {
  314. if (!map[row[index]].children) map[row[index]].children = [];
  315. map[row[index]].children.push(row);
  316. } else {
  317. result.push(row);
  318. }
  319. });
  320. return result;
  321. }
  322. export function flattenObject(ob, prefix = '') {
  323. const toReturn = {};
  324. if (prefix) prefix = `${prefix}.`;
  325. Object.keys(ob).forEach(i => {
  326. if (typeof ob[i] === 'object' && ob[i] !== null && !ob[i].length) {
  327. const flatObject = flattenObject(ob[i]);
  328. Object.keys(flatObject).forEach(x => {
  329. toReturn[`${prefix}${i}.${x}`] = flatObject[x];
  330. });
  331. } else {
  332. toReturn[`${prefix}${i}`] = ob[i];
  333. }
  334. });
  335. return toReturn;
  336. }
  337. function _formatMoney(s, n) {
  338. if (!s) s = 0;
  339. n = n > 0 && n <= 20 ? n : 2;
  340. s = `${parseFloat(`${s}`.replace(/[^\d.-]/g, '')).toFixed(n)}`;
  341. const l = s
  342. .split('.')[0]
  343. .split('')
  344. .reverse();
  345. const r = s.split('.')[1];
  346. let t = '';
  347. for (let i = 0; i < l.length; i += 1) {
  348. t += l[i] + ((i + 1) % 3 === 0 && i + 1 !== l.length ? ',' : '');
  349. }
  350. return `${t
  351. .split('')
  352. .reverse()
  353. .join('')}.${r}`;
  354. }
  355. export function formatMoney(price) {
  356. if (typeof price === 'object') {
  357. return `${price.symbol} ${_formatMoney(price.value, 2)}`;
  358. }
  359. return `${_formatMoney(price, 2)}`;
  360. }
  361. export function bindTags(targetList, field, render, def, notFound) {
  362. let index = -1;
  363. targetList.forEach((row, i) => {
  364. if (row.key === field) index = i;
  365. });
  366. targetList[index].notFoundContent = notFound;
  367. targetList[index].select = (def || []).map(row => {
  368. return render(row);
  369. });
  370. }
  371. export function bindSearch(targetList, field, Component, listFunc, render, def, notFound = null) {
  372. let index = -1;
  373. targetList.forEach((row, i) => {
  374. if (row.key === field) index = i;
  375. });
  376. const key = `lastFetchId${field}${index}${generateUUID(4)}`;
  377. if (!Component[key]) Component[key] = 0;
  378. const searchFunc = data => {
  379. Component[key] += 1;
  380. const fetchId = Component[key];
  381. targetList[index].loading = true;
  382. Component.setState({ fetching: true });
  383. listFunc(data).then(result => {
  384. if (fetchId !== Component[key]) {
  385. // for fetch callback order
  386. return;
  387. }
  388. targetList[index].select = (result.list || result || []).map(row => {
  389. return render(row);
  390. });
  391. targetList[index].loading = false;
  392. Component.setState({ fetching: false });
  393. });
  394. };
  395. const item = {
  396. showSearch: true,
  397. showArrow: true,
  398. filterOption: false,
  399. onSearch: keyword => {
  400. searchFunc({ page: 1, size: 5, keyword });
  401. },
  402. notFoundContent: notFound,
  403. };
  404. targetList[index] = Object.assign(targetList[index], item);
  405. if (def) {
  406. if (targetList[index].type === 'multiple' || targetList[index].mode === 'multiple') {
  407. searchFunc({ ids: def, page: 1, size: def.length });
  408. } else {
  409. searchFunc({ ids: [def], page: 1, size: 1 });
  410. }
  411. } else {
  412. item.onSearch();
  413. }
  414. }
  415. export function generateSearch(field, props, Component, listFunc, render, def, notFound = null) {
  416. const key = `lastFetchId${field}${generateUUID(4)}`;
  417. if (!Component[key]) Component[key] = 0;
  418. let item = {
  419. showSearch: true,
  420. showArrow: true,
  421. filterOption: false,
  422. notFoundContent: notFound,
  423. };
  424. item = Object.assign(props || {}, item);
  425. const searchFunc = data => {
  426. Component[key] += 1;
  427. const fetchId = Component[key];
  428. item.loading = true;
  429. Component.setState({ [field]: item, fetching: true });
  430. listFunc(data).then(result => {
  431. if (fetchId !== Component[key]) {
  432. // for fetch callback order
  433. return;
  434. }
  435. item.select = result.list.map(row => {
  436. return render(row);
  437. });
  438. item.loading = false;
  439. Component.setState({ [field]: item, fetching: false });
  440. });
  441. };
  442. item.onSearch = keyword => {
  443. searchFunc({ page: 1, size: 5, keyword });
  444. };
  445. if (def) {
  446. if (item.mode === 'multiple' || item.type === 'multiple') {
  447. searchFunc({ ids: def, page: 1, size: def.length });
  448. } else {
  449. searchFunc({ ids: [def], page: 1, size: 1 });
  450. }
  451. } else {
  452. item.onSearch();
  453. }
  454. Component.setState({ [field]: item });
  455. }
  456. export function getHtmlText(text) {
  457. text = text.replace(new RegExp(/\r\n/, 'g'), '\r').replace(new RegExp(/\n/, 'g'), '\r');
  458. let html = '';
  459. text.split('\r').forEach(item => {
  460. item.split(' ').forEach(t => {
  461. html += `< i uuid = "${generateUUID(4)}" > ${t}</i > `;
  462. });
  463. html += '<br/>';
  464. });
  465. return html;
  466. }
  467. export function getSimpleText(html) {
  468. let text = html.replace(new RegExp('<br/>', 'g'), '\n\r');
  469. text = text.replace(new RegExp('<.+?>', 'g'), '');
  470. return text;
  471. }
  472. export function randomList(length) {
  473. const list = [];
  474. for (let i = 0; i < length; i += 1) {
  475. list.push(i);
  476. }
  477. for (let i = 0; i < length; i += 1) {
  478. const o = Math.floor(Math.random() * length);
  479. const tmp = list[o];
  480. list[o] = list[i];
  481. list[i] = tmp;
  482. }
  483. return list;
  484. }
  485. export function sortListWithOrder(target, order) {
  486. const list = [];
  487. order.forEach(t => {
  488. list.push(target[t]);
  489. });
  490. return list;
  491. }
  492. export function resortListWithOrder(target, order) {
  493. const list = [];
  494. for (let i = 0; i < order.length; i += 1) {
  495. list.push('');
  496. }
  497. order.forEach((t, i) => {
  498. list[t] = target[i];
  499. });
  500. return list;
  501. }
  502. // 下划线转换驼峰
  503. export function toHump(name) {
  504. return name.replace(/_(\w)/g, (all, letter) => {
  505. return letter.toUpperCase();
  506. });
  507. }
  508. // 驼峰转换下划线
  509. export function toLine(name) {
  510. return name.replace(/([A-Z])/g, '_$1').toLowerCase();
  511. }