Tools.js 13 KB

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