utils.js 4.86 KB
Newer Older
1
import moment from 'moment';
ddcat1115's avatar
ddcat1115 committed
2
import React from 'react';
陈帅's avatar
陈帅 committed
3
import nzh from 'nzh/cn';
4
import { parse, stringify } from 'qs';
5

偏右's avatar
偏右 committed
6
export function fixedZero(val) {
7 8 9
  return val * 1 < 10 ? `0${val}` : val;
}

偏右's avatar
偏右 committed
10
export function getTimeDistance(type) {
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
  const now = new Date();
  const oneDay = 1000 * 60 * 60 * 24;

  if (type === 'today') {
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);
    return [moment(now), moment(now.getTime() + (oneDay - 1000))];
  }

  if (type === 'week') {
    let day = now.getDay();
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);

    if (day === 0) {
      day = 6;
    } else {
      day -= 1;
    }

jim's avatar
jim committed
33
    const beginTime = now.getTime() - day * oneDay;
34

jim's avatar
jim committed
35
    return [moment(beginTime), moment(beginTime + (7 * oneDay - 1000))];
36 37 38 39 40 41 42 43 44
  }

  if (type === 'month') {
    const year = now.getFullYear();
    const month = now.getMonth();
    const nextDate = moment(now).add(1, 'months');
    const nextYear = nextDate.year();
    const nextMonth = nextDate.month();

jim's avatar
jim committed
45 46 47 48
    return [
      moment(`${year}-${fixedZero(month + 1)}-01 00:00:00`),
      moment(moment(`${nextYear}-${fixedZero(nextMonth + 1)}-01 00:00:00`).valueOf() - 1000),
    ];
49 50
  }

愚道's avatar
愚道 committed
51 52
  const year = now.getFullYear();
  return [moment(`${year}-01-01 00:00:00`), moment(`${year}-12-31 23:59:59`)];
53
}
ddcat1115's avatar
ddcat1115 committed
54

55
export function getPlainNode(nodeList, parentPath = '') {
ddcat1115's avatar
ddcat1115 committed
56
  const arr = [];
jim's avatar
jim committed
57
  nodeList.forEach(node => {
ddcat1115's avatar
ddcat1115 committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
    const item = node;
    item.path = `${parentPath}/${item.path || ''}`.replace(/\/+/g, '/');
    item.exact = true;
    if (item.children && !item.component) {
      arr.push(...getPlainNode(item.children, item.path));
    } else {
      if (item.children && item.component) {
        item.exact = false;
      }
      arr.push(item);
    }
  });
  return arr;
}

73
export function digitUppercase(n) {
陈帅's avatar
陈帅 committed
74
  return nzh.toMoney(n);
75
}
ddcat1115's avatar
ddcat1115 committed
76 77 78

function getRelation(str1, str2) {
  if (str1 === str2) {
jim's avatar
jim committed
79
    console.warn('Two path are equal!'); // eslint-disable-line
ddcat1115's avatar
ddcat1115 committed
80 81 82 83 84
  }
  const arr1 = str1.split('/');
  const arr2 = str2.split('/');
  if (arr2.every((item, index) => item === arr1[index])) {
    return 1;
85 86
  }
  if (arr1.every((item, index) => item === arr2[index])) {
ddcat1115's avatar
ddcat1115 committed
87 88 89 90 91
    return 2;
  }
  return 3;
}

陈帅's avatar
陈帅 committed
92
function getRenderArr(routes) {
ddcat1115's avatar
ddcat1115 committed
93 94 95
  let renderArr = [];
  renderArr.push(routes[0]);
  for (let i = 1; i < routes.length; i += 1) {
陈帅's avatar
陈帅 committed
96
    // 去重
ddcat1115's avatar
ddcat1115 committed
97
    renderArr = renderArr.filter(item => getRelation(item, routes[i]) !== 1);
Amumu's avatar
Amumu committed
98 99
    // 是否包含
    const isAdd = renderArr.every(item => getRelation(item, routes[i]) === 3);
ddcat1115's avatar
ddcat1115 committed
100 101 102 103
    if (isAdd) {
      renderArr.push(routes[i]);
    }
  }
陈帅's avatar
陈帅 committed
104 105 106 107 108 109 110 111 112 113
  return renderArr;
}

/**
 * Get router routing configuration
 * { path:{name,...param}}=>Array<{name,path ...param}>
 * @param {string} path
 * @param {routerData} routerData
 */
export function getRoutes(path, routerData) {
jim's avatar
jim committed
114 115 116
  let routes = Object.keys(routerData).filter(
    routePath => routePath.indexOf(path) === 0 && routePath !== path
  );
陈帅's avatar
陈帅 committed
117 118 119 120 121
  // Replace path to '' eg. path='user' /user/name => name
  routes = routes.map(item => item.replace(path, ''));
  // Get the route to be rendered to remove the deep rendering
  const renderArr = getRenderArr(routes);
  // Conversion and stitching parameters
jim's avatar
jim committed
122
  const renderRoutes = renderArr.map(item => {
ddcat1115's avatar
ddcat1115 committed
123 124
    const exact = !routes.some(route => route !== item && getRelation(route, item) === 1);
    return {
125
      exact,
ddcat1115's avatar
ddcat1115 committed
126
      ...routerData[`${path}${item}`],
ddcat1115's avatar
ddcat1115 committed
127 128 129 130 131 132
      key: `${path}${item}`,
      path: `${path}${item}`,
    };
  });
  return renderRoutes;
}
133

yoyo837's avatar
yoyo837 committed
134 135 136 137
export function getPageQuery() {
  return parse(window.location.href.split('?')[1]);
}

138 139 140 141 142 143 144 145
export function getQueryPath(path = '', query = {}) {
  const search = stringify(query);
  if (search.length) {
    return `${path}?${search}`;
  }
  return path;
}

146
/* eslint no-useless-escape:0 */
147
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
148 149 150 151

export function isUrl(path) {
  return reg.test(path);
}
ddcat1115's avatar
ddcat1115 committed
152 153 154

export function formatWan(val) {
  const v = val * 1;
155
  if (!v || Number.isNaN(v)) return '';
ddcat1115's avatar
ddcat1115 committed
156 157 158 159 160 161 162

  let result = val;
  if (val > 10000) {
    result = Math.floor(val / 10000);
    result = (
      <span>
        {result}
jim's avatar
jim committed
163
        <span
happy wang's avatar
happy wang committed
164
          style={{
ddcat1115's avatar
ddcat1115 committed
165 166 167 168 169 170 171 172
            position: 'relative',
            top: -2,
            fontSize: 14,
            fontStyle: 'normal',
            marginLeft: 2,
          }}
        >
          
ddcat1115's avatar
ddcat1115 committed
173
        </span>
ddcat1115's avatar
ddcat1115 committed
174 175 176 177 178
      </span>
    );
  }
  return result;
}
陈帅's avatar
陈帅 committed
179

afc163's avatar
afc163 committed
180
// 给官方演示站点用,用于关闭真实开发环境不需要使用的特性
陈帅's avatar
陈帅 committed
181 182 183
export function isAntdPro() {
  return window.location.hostname === 'preview.pro.ant.design';
}
陈帅's avatar
陈帅 committed
184 185 186 187 188 189 190 191 192 193 194

export const importCDN = (url, name) =>
  new Promise(resolve => {
    const dom = document.createElement('script');
    dom.src = url;
    dom.type = 'text/javascript';
    dom.onload = () => {
      resolve(window[name]);
    };
    document.head.appendChild(dom);
  });