Skip to content

Commit

Permalink
feat: 升级脚手架
Browse files Browse the repository at this point in the history
  • Loading branch information
MyCupOfTeaOo committed Jan 26, 2021
1 parent a664d76 commit 27bffac
Show file tree
Hide file tree
Showing 27 changed files with 910 additions and 176 deletions.
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,15 @@
"@sentry/tracing": "^5.27.6",
"ag-grid-community": "^23.0.2",
"ag-grid-react": "^23.0.3",
"antd": "^4.2.0",
"antd": "^4.6.2",
"array-move": "^2.2.1",
"async-validator": "^3.2.1",
"axios": "^0.21.1",
"classnames": "^2.2.6",
"crypto-js": "^4.0.0",
"js-base64": "^2.5.2",
"js-md5": "^0.7.3",
"lodash": "^4.17.20",
"lodash-decorators": "^6.0.1",
"mobx": "^5.13.0",
"mobx-react": "^6.1.3",
Expand All @@ -46,7 +47,7 @@
"react-sortable-hoc": "^1.10.1",
"react-virtualized": "^9.21.1",
"tea-eval": "0.0.6",
"teaness": "^4.1.22",
"teaness": "^4.1.43",
"uuid": "^3.3.3"
},
"devDependencies": {
Expand Down
20 changes: 20 additions & 0 deletions src/components/Dict/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
group:
path: /
---

# Dict(字典)

字典的选择与翻译,在 antd Cascader 基础上实现,继承 antd Cascader 的几乎所有的特性

## 基本用例

<code src="./example/Normal.tsx" />

## 选中即改变

<code src="./example/ChangeOnSelect.tsx" />

## 更多用法

<code src="./example/More.tsx" />
155 changes: 3 additions & 152 deletions src/components/Dict/TransDict.tsx
Original file line number Diff line number Diff line change
@@ -1,159 +1,10 @@
/* eslint-disable no-nested-ternary */
import React, { useEffect } from 'react';
import { observable, flow } from 'mobx';
import { getCurrentDict, Dict, DictMeta, getDictMeta } from '@/service/config';
import { ReqResponse } from '@/utils/request';
import { Circle } from 'teaness';
import { observer } from 'mobx-react';
import { splitCode } from './utils';

export interface NodeType {
label?: string;
state: 'ready' | 'loading' | 'success' | 'error' | 'notFound';
father?: NodeType;
children: {
[key: string]: NodeType;
};
}

export interface NodeMeta {
splitLens?: number[];
levelNum?: number;
label?: string;
state: 'ready' | 'loading' | 'success' | 'error' | 'notFound';
}

export interface CascaderCache {
[key: string]: NodeType;
}

export class Store {
@observable
cascaderCache: CascaderCache = {};

@observable
metaCache: Record<string, NodeMeta> = {};

setMetaCache = flow(function*(
this: Store,
server: string,
dictType: string,
): any {
if (!this.metaCache[dictType]) {
this.metaCache[dictType] = {
state: 'ready',
};
}
const curMeta = this.metaCache[dictType];
switch (curMeta.state) {
case 'loading':
case 'notFound':
case 'success':
break;
case 'error':
case 'ready':
default:
// 加载元信息
// 失败重复请求三次
for (let i = 0; i < 3; i += 1) {
curMeta.state = 'loading';
const res: ReqResponse<DictMeta> = yield getDictMeta(
server,
dictType,
);
if (res.isSuccess) {
if (res.data) {
Object.assign(curMeta, {
state: 'success',
label: res.data.label,
levelNum: Number(res.data.levelNum),
splitLens: res.data.levelCodeLen
?.split('-')
.map(item => parseInt(item, 10)) || [0xffffff],
} as NodeMeta);
} else {
curMeta.state = 'notFound';
}
} else {
console.error(res.msg);
}
}
}
});

setCacheByDictTypeAndDictCode = flow(function*(
this: Store,
server: string,
dictType: string,
codes: string[],
searchFather?: boolean,
): any {
if (!this.cascaderCache[dictType]) {
this.cascaderCache[dictType] = {
state: 'ready',
children: {},
};
}
const typeNode = this.cascaderCache[dictType];

let node: NodeType = typeNode;
let index = 1;
for (const code of codes) {
if (!node.children[code]) {
node.children[code] = {
state: 'ready',
children: {},
father: node,
};
}
const curNode = node.children[code];
switch (curNode.state) {
case 'loading':
case 'notFound':
case 'success':
break;
case 'error':
case 'ready':
default:
// 加载当前节点 || 需要加载父节点
if (index === codes.length || searchFather) {
// 加载当前节点
// 失败重复请求三次
for (let i = 0; i < 3; i += 1) {
curNode.state = 'loading';
const resp: ReqResponse<Dict> = yield getCurrentDict(
server,
dictType,
codes.slice(0, index).join(''),
);
if (resp.isSuccess) {
if (!resp.data) {
curNode.state = 'notFound';
} else {
curNode.state = 'success';
curNode.label = resp.data.label;
}
// 中断循环
break;
} else {
console.error(resp.msg);
}
}
// 加载失败
if (curNode.state === 'loading') {
curNode.state = 'error';
}
}

break;
}
node = node.children[code];
index += 1;
}
});
}
const store = new Store();
export { store };
import { NodeMeta, NodeType } from './interface';
import { store } from './store';

export function getTarget(
code?: string,
Expand Down Expand Up @@ -330,7 +181,7 @@ const TransDict: React.FC<TransDictProps> = props => {
)
.join(props.separator)
: props.notFound || props.code;
if (props.notDiv) return <React.Fragment>{element}</React.Fragment>;
if (props.notDiv) return <>{element}</>;
return <span>{element}</span>;
}
}
Expand Down
165 changes: 165 additions & 0 deletions src/components/Dict/_mock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
import mockjs from 'mockjs';
import moment from 'moment';
import { apiPrefix } from '../../../config/projectConfig';
import { Dict } from './interface';

function genDicts(levelCodeLen: string, curLevel = 1): Dict[] {
const level = levelCodeLen.split('-').length;
const curValueLenght = levelCodeLen.split('-')[curLevel - 1].length;
return [...Array(3)].map(() => ({
label: mockjs.Random.cname(),
value: mockjs.Random.word(curValueLenght, curValueLenght),
isLeaf: levelCodeLen.split('-').length <= curLevel,
description: mockjs.Random.cparagraph(),
levelCodeLen,
children:
level > curLevel ? genDicts(levelCodeLen, curLevel + 1) : undefined,
}));
}

const dicts = [...Array(10)].map(() => ({
label: mockjs.Random.cword(),
value: mockjs.Random.word(),
children: genDicts('4-4-4-4'),
}));

dicts.push({
label: '区划',
value: 'adminArea',
children: [
{
label: '江苏省',
value: '32',
levelCodeLen: '2-2-2-2',
isLeaf: false,
children: [
{
label: '南京市',
value: '01',
levelCodeLen: '2-2-2-2',
isLeaf: false,
children: [
{
label: '秦淮区',
value: '01',
levelCodeLen: '2-2-2-2',
isLeaf: false,
children: [
{
label: '夫子庙街道',
value: '01',
levelCodeLen: '2-2-2-2',
isLeaf: true,
},
],
},
],
},
],
},
{
label: '安徽省',
value: '33',
levelCodeLen: '2-2-2-2',
isLeaf: true,
},
],
});

function splitCode(code: string, splitLenCode: string) {
return splitLenCode
.split('-')
.reduce<[number, number][]>((arr, curLen, i) => {
if (!i) {
arr.push([0, Number(curLen)]);
} else {
const lastIndex = arr[i - 1][1];
arr.push([lastIndex, lastIndex + Number(curLen)]);
}
return arr;
}, [])
.map(item => code.slice(...item))
.filter(item => item);
}

function getTargetDicts(theDicts: Dict[], code?: string) {
if (!code) {
return {
children: theDicts,
};
}
const codes = splitCode(code, theDicts[0].levelCodeLen as string);
function search(codeList: string[], dictList: Dict[]): Dict | undefined {
const target = dictList.find(dict => {
return dict.value === codeList[0];
});
if (!target) {
return undefined;
}

if (codeList.length > 1) {
return search(codeList.slice(1), target.children || []);
}
return target;
}
return search(codes, theDicts);
}

const returnUtil = (data?: any) => ({
data,
code: 200,
msg: '请求成功啦',
timestamp: moment().format('YYYY-MM-DD HH:mm:ss'),
});

const delay = 200;

export default {
[`GET /${apiPrefix}/:server/dicts/:dictType`]: (req: any, res: any) => {
const { code, queryAll } = req.query;
const { dictType } = req.params;
const target = getTargetDicts(
dicts.find(item => item.value === dictType)?.children || [],
code,
);
const filterTarget = target
? {
...target,
children: queryAll === 'true' ? target.children : undefined,
}
: undefined;
setTimeout(() => res.send(returnUtil(filterTarget)), delay);
},
[`GET /${apiPrefix}/:server/dicts/:dictType/children`]: (
req: any,
res: any,
) => {
const { code, queryAll } = req.query;
const { dictType } = req.params;
const target = getTargetDicts(
dicts.find(item => item.value === dictType)?.children || [],
code,
);
const filterTarget = target?.children?.map(item => {
return {
...item,
children: queryAll === 'true' ? item.children : undefined,
};
});
setTimeout(() => res.send(returnUtil(filterTarget)), delay);
},
[`GET /${apiPrefix}/:server/dictTypes`]: (req: any, res: any) => {
setTimeout(
() =>
res.send(
returnUtil(
dicts.map(item => ({
label: item.label,
value: item.value,
})),
),
),
delay,
);
},
};
Loading

0 comments on commit 27bffac

Please sign in to comment.