This commit is contained in:
2024-03-01 20:28:14 +08:00
commit 076c21dc36
491 changed files with 84482 additions and 0 deletions

View File

@@ -0,0 +1,58 @@
import './Activity.scss';
import React, { PureComponent as Component } from 'react';
import TimeTree from '../../../components/TimeLine/TimeLine';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Button } from 'antd';
@connect(state => {
return {
uid: state.user.uid + '',
curdata: state.inter.curdata,
currProject: state.project.currProject
};
})
class Activity extends Component {
constructor(props) {
super(props);
}
static propTypes = {
uid: PropTypes.string,
getMockUrl: PropTypes.func,
match: PropTypes.object,
curdata: PropTypes.object,
currProject: PropTypes.object
};
render() {
let { currProject } = this.props;
return (
<div className="g-row">
<section className="news-box m-panel">
<div style={{ display: 'none' }} className="logHead">
{/*<Breadcrumb />*/}
<div className="projectDes">
<p>高效易用可部署的API管理平台</p>
</div>
<div className="Mockurl">
<span>Mock地址</span>
<p>
{location.protocol +
'//' +
location.hostname +
(location.port !== '' ? ':' + location.port : '') +
`/mock/${currProject._id}${currProject.basepath}/yourPath`}
</p>
<Button type="primary">
<a href={`/api/project/download?project_id=${this.props.match.params.id}`}>
下载Mock数据
</a>
</Button>
</div>
</div>
<TimeTree type={'project'} typeid={+this.props.match.params.id} />
</section>
</div>
);
}
}
export default Activity;

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1,141 @@
import React, { PureComponent as Component } from 'react';
import PropTypes from 'prop-types';
import { Tabs, Layout } from 'antd';
import { Route, Switch, matchPath } from 'react-router-dom';
import { connect } from 'react-redux';
const { Content, Sider } = Layout;
import './interface.scss';
import InterfaceMenu from './InterfaceList/InterfaceMenu.js';
import InterfaceList from './InterfaceList/InterfaceList.js';
import InterfaceContent from './InterfaceList/InterfaceContent.js';
import InterfaceColMenu from './InterfaceCol/InterfaceColMenu.js';
import InterfaceColContent from './InterfaceCol/InterfaceColContent.js';
import InterfaceCaseContent from './InterfaceCol/InterfaceCaseContent.js';
import { getProject } from '../../../reducer/modules/project';
import { setColData } from '../../../reducer/modules/interfaceCol.js';
const contentRouter = {
path: '/project/:id/interface/:action/:actionId',
exact: true
};
const InterfaceRoute = props => {
let C;
if (props.match.params.action === 'api') {
if (!props.match.params.actionId) {
C = InterfaceList;
} else if (!isNaN(props.match.params.actionId)) {
C = InterfaceContent;
} else if (props.match.params.actionId.indexOf('cat_') === 0) {
C = InterfaceList;
}
} else if (props.match.params.action === 'col') {
C = InterfaceColContent;
} else if (props.match.params.action === 'case') {
C = InterfaceCaseContent;
} else {
const params = props.match.params;
props.history.replace('/project/' + params.id + '/interface/api');
return null;
}
return <C {...props} />;
};
InterfaceRoute.propTypes = {
match: PropTypes.object,
history: PropTypes.object
};
@connect(
state => {
return {
isShowCol: state.interfaceCol.isShowCol
};
},
{
setColData,
getProject
}
)
class Interface extends Component {
static propTypes = {
match: PropTypes.object,
history: PropTypes.object,
location: PropTypes.object,
isShowCol: PropTypes.bool,
getProject: PropTypes.func,
setColData: PropTypes.func
// fetchInterfaceColList: PropTypes.func
};
constructor(props) {
super(props);
// this.state = {
// curkey: this.props.match.params.action === 'api' ? 'api' : 'colOrCase'
// }
}
onChange = action => {
let params = this.props.match.params;
if (action === 'colOrCase') {
action = this.props.isShowCol ? 'col' : 'case';
}
this.props.history.push('/project/' + params.id + '/interface/' + action);
};
async UNSAFE_componentWillMount() {
this.props.setColData({
isShowCol: true
});
// await this.props.fetchInterfaceColList(this.props.match.params.id)
}
render() {
const { action } = this.props.match.params;
// const activeKey = this.state.curkey;
const activeKey = action === 'api' ? 'api' : 'colOrCase';
return (
<Layout style={{ minHeight: 'calc(100vh - 156px)', marginLeft: '24px', marginTop: '24px' }}>
<Sider style={{ height: '100%' }} width={450}>
<div className="left-menu">
<Tabs type="card" className="tabs-large" activeKey={activeKey} onChange={this.onChange}>
<Tabs.TabPane tab="接口列表" key="api" />
<Tabs.TabPane tab="测试集合" key="colOrCase" />
</Tabs>
{activeKey === 'api' ? (
<InterfaceMenu
router={matchPath(this.props.location.pathname, contentRouter)}
projectId={this.props.match.params.id}
/>
) : (
<InterfaceColMenu
router={matchPath(this.props.location.pathname, contentRouter)}
projectId={this.props.match.params.id}
/>
)}
</div>
</Sider>
<Layout>
<Content
style={{
height: '100%',
margin: '0 24px 0 16px',
overflow: 'initial',
backgroundColor: '#fff'
}}
>
<div className="right-content">
<Switch>
<Route exact path="/project/:id/interface/:action" component={InterfaceRoute} />
<Route {...contentRouter} component={InterfaceRoute} />
</Switch>
</div>
</Content>
</Layout>
</Layout>
);
}
}
export default Interface;

View File

@@ -0,0 +1,125 @@
import React from 'react';
import PropTypes from 'prop-types';
import { Row, Col, Tabs } from 'antd';
const TabPane = Tabs.TabPane;
function jsonFormat(json) {
// console.log('json',json)
if (json && typeof json === 'object') {
return JSON.stringify(json, null, ' ');
}
return json;
}
const CaseReport = function(props) {
let params = jsonFormat(props.data);
let headers = jsonFormat(props.headers, null, ' ');
let res_header = jsonFormat(props.res_header, null, ' ');
let res_body = jsonFormat(props.res_body);
let httpCode = props.status;
let validRes;
if (props.validRes && Array.isArray(props.validRes)) {
validRes = props.validRes.map((item, index) => {
return <div key={index}>{item.message}</div>;
});
}
return (
<div className="report">
<Tabs defaultActiveKey="request">
<TabPane className="case-report-pane" tab="Request" key="request">
<Row className="case-report">
<Col className="case-report-title" span="6">
Url
</Col>
<Col span="18">{props.url}</Col>
</Row>
{props.query ? (
<Row className="case-report">
<Col className="case-report-title" span="6">
Query
</Col>
<Col span="18">{props.query}</Col>
</Row>
) : null}
{props.headers ? (
<Row className="case-report">
<Col className="case-report-title" span="6">
Headers
</Col>
<Col span="18">
<pre>{headers}</pre>
</Col>
</Row>
) : null}
{params ? (
<Row className="case-report">
<Col className="case-report-title" span="6">
Body
</Col>
<Col span="18">
<pre style={{ whiteSpace: 'pre-wrap' }}>{params}</pre>
</Col>
</Row>
) : null}
</TabPane>
<TabPane className="case-report-pane" tab="Response" key="response">
<Row className="case-report">
<Col className="case-report-title" span="6">
HttpCode
</Col>
<Col span="18">
<pre>{httpCode}</pre>
</Col>
</Row>
{props.res_header ? (
<Row className="case-report">
<Col className="case-report-title" span="6">
Headers
</Col>
<Col span="18">
<pre>{res_header}</pre>
</Col>
</Row>
) : null}
{props.res_body ? (
<Row className="case-report">
<Col className="case-report-title" span="6">
Body
</Col>
<Col span="18">
<pre>{res_body}</pre>
</Col>
</Row>
) : null}
</TabPane>
<TabPane className="case-report-pane" tab="验证结果" key="valid">
{props.validRes ? (
<Row className="case-report">
<Col className="case-report-title" span="6">
验证结果
</Col>
<Col span="18"><pre>
{validRes}
</pre></Col>
</Row>
) : null}
</TabPane>
</Tabs>
</div>
);
};
CaseReport.propTypes = {
url: PropTypes.string,
data: PropTypes.any,
headers: PropTypes.object,
res_header: PropTypes.object,
res_body: PropTypes.any,
query: PropTypes.string,
validRes: PropTypes.array,
status: PropTypes.number
};
export default CaseReport;

View File

@@ -0,0 +1,241 @@
import React, { PureComponent as Component } from 'react';
import PropTypes from 'prop-types';
import { Table, Select, Tooltip, Icon } from 'antd';
import variable from '../../../../constants/variable';
import { connect } from 'react-redux';
const Option = Select.Option;
import { fetchInterfaceListMenu } from '../../../../reducer/modules/interface.js';
@connect(
state => {
return {
projectList: state.project.projectList,
list: state.inter.list
};
},
{
fetchInterfaceListMenu
}
)
export default class ImportInterface extends Component {
constructor(props) {
super(props);
}
state = {
selectedRowKeys: [],
categoryCount: {},
project: this.props.currProjectId
};
static propTypes = {
list: PropTypes.array,
selectInterface: PropTypes.func,
projectList: PropTypes.array,
currProjectId: PropTypes.string,
fetchInterfaceListMenu: PropTypes.func
};
async componentDidMount() {
// console.log(this.props.currProjectId)
await this.props.fetchInterfaceListMenu(this.props.currProjectId);
}
// 切换项目
onChange = async val => {
this.setState({
project: val,
selectedRowKeys: [],
categoryCount: {}
});
await this.props.fetchInterfaceListMenu(val);
};
render() {
const { list, projectList } = this.props;
// const { selectedRowKeys } = this.state;
const data = list.map(item => {
return {
key: 'category_' + item._id,
title: item.name,
isCategory: true,
children: item.list
? item.list.map(e => {
e.key = e._id;
e.categoryKey = 'category_' + item._id;
e.categoryLength = item.list.length;
return e;
})
: []
};
});
const self = this;
const rowSelection = {
// onChange: (selectedRowKeys) => {
// console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
// if (selectedRows.isCategory) {
// const selectedRowKeys = selectedRows.children.map(item => item._id)
// this.setState({ selectedRowKeys })
// }
// this.props.onChange(selectedRowKeys.filter(id => ('' + id).indexOf('category') === -1));
// },
onSelect: (record, selected) => {
// console.log(record, selected, selectedRows);
const oldSelecteds = self.state.selectedRowKeys;
const categoryCount = self.state.categoryCount;
const categoryKey = record.categoryKey;
const categoryLength = record.categoryLength;
let selectedRowKeys = [];
if (record.isCategory) {
selectedRowKeys = record.children.map(item => item._id).concat(record.key);
if (selected) {
selectedRowKeys = selectedRowKeys
.filter(id => oldSelecteds.indexOf(id) === -1)
.concat(oldSelecteds);
categoryCount[categoryKey] = categoryLength;
} else {
selectedRowKeys = oldSelecteds.filter(id => selectedRowKeys.indexOf(id) === -1);
categoryCount[categoryKey] = 0;
}
} else {
if (selected) {
selectedRowKeys = oldSelecteds.concat(record._id);
if (categoryCount[categoryKey]) {
categoryCount[categoryKey] += 1;
} else {
categoryCount[categoryKey] = 1;
}
if (categoryCount[categoryKey] === record.categoryLength) {
selectedRowKeys.push(categoryKey);
}
} else {
selectedRowKeys = oldSelecteds.filter(id => id !== record._id);
if (categoryCount[categoryKey]) {
categoryCount[categoryKey] -= 1;
}
selectedRowKeys = selectedRowKeys.filter(id => id !== categoryKey);
}
}
self.setState({ selectedRowKeys, categoryCount });
self.props.selectInterface(
selectedRowKeys.filter(id => ('' + id).indexOf('category') === -1),
self.state.project
);
},
onSelectAll: selected => {
// console.log(selected, selectedRows, changeRows);
let selectedRowKeys = [];
let categoryCount = self.state.categoryCount;
if (selected) {
data.forEach(item => {
if (item.children) {
categoryCount['category_' + item._id] = item.children.length;
selectedRowKeys = selectedRowKeys.concat(item.children.map(item => item._id));
}
});
selectedRowKeys = selectedRowKeys.concat(data.map(item => item.key));
} else {
categoryCount = {};
selectedRowKeys = [];
}
self.setState({ selectedRowKeys, categoryCount });
self.props.selectInterface(
selectedRowKeys.filter(id => ('' + id).indexOf('category') === -1),
self.state.project
);
},
selectedRowKeys: self.state.selectedRowKeys
};
const columns = [
{
title: '接口名称',
dataIndex: 'title',
width: '30%'
},
{
title: '接口路径',
dataIndex: 'path',
width: '40%'
},
{
title: '请求方法',
dataIndex: 'method',
render: item => {
let methodColor = variable.METHOD_COLOR[item ? item.toLowerCase() : 'get'];
return (
<span
style={{
color: methodColor.color,
backgroundColor: methodColor.bac,
borderRadius: 4
}}
className="colValue"
>
{item}
</span>
);
}
},
{
title: (
<span>
状态{' '}
<Tooltip title="筛选满足条件的接口集合">
<Icon type="question-circle-o" />
</Tooltip>
</span>
),
dataIndex: 'status',
render: text => {
return (
text &&
(text === 'done' ? (
<span className="tag-status done">已完成</span>
) : (
<span className="tag-status undone">未完成</span>
))
);
},
filters: [
{
text: '已完成',
value: 'done'
},
{
text: '未完成',
value: 'undone'
}
],
onFilter: (value, record) => {
let arr = record.children.filter(item => {
return item.status.indexOf(value) === 0;
});
return arr.length > 0;
// record.status.indexOf(value) === 0
}
}
];
return (
<div>
<div className="select-project">
<span>选择要导入的项目 </span>
<Select value={this.state.project} style={{ width: 200 }} onChange={this.onChange}>
{projectList.map(item => {
return item.projectname ? (
''
) : (
<Option value={`${item._id}`} key={item._id}>
{item.name}
</Option>
);
})}
</Select>
</div>
<Table columns={columns} rowSelection={rowSelection} dataSource={data} pagination={false} />
</div>
);
}
}

View File

@@ -0,0 +1,235 @@
import React, { PureComponent as Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router';
import { Link } from 'react-router-dom';
import axios from 'axios';
import { message, Tooltip, Input } from 'antd';
import { getEnv } from '../../../../reducer/modules/project';
import {
fetchInterfaceColList,
setColData,
fetchCaseData,
fetchCaseList
} from '../../../../reducer/modules/interfaceCol';
import { Postman } from '../../../../components';
import './InterfaceCaseContent.scss';
@connect(
state => {
return {
interfaceColList: state.interfaceCol.interfaceColList,
currColId: state.interfaceCol.currColId,
currCaseId: state.interfaceCol.currCaseId,
currCase: state.interfaceCol.currCase,
isShowCol: state.interfaceCol.isShowCol,
currProject: state.project.currProject,
projectEnv: state.project.projectEnv,
curUid: state.user.uid
};
},
{
fetchInterfaceColList,
fetchCaseData,
setColData,
fetchCaseList,
getEnv
}
)
@withRouter
export default class InterfaceCaseContent extends Component {
static propTypes = {
match: PropTypes.object,
interfaceColList: PropTypes.array,
fetchInterfaceColList: PropTypes.func,
fetchCaseData: PropTypes.func,
setColData: PropTypes.func,
fetchCaseList: PropTypes.func,
history: PropTypes.object,
currColId: PropTypes.number,
currCaseId: PropTypes.number,
currCase: PropTypes.object,
isShowCol: PropTypes.bool,
currProject: PropTypes.object,
getEnv: PropTypes.func,
projectEnv: PropTypes.object,
curUid: PropTypes.number
};
state = {
isEditingCasename: true,
editCasename: ''
};
constructor(props) {
super(props);
}
getColId(colList, currCaseId) {
let currColId = 0;
colList.forEach(col => {
col.caseList.forEach(caseItem => {
if (+caseItem._id === +currCaseId) {
currColId = col._id;
}
});
});
return currColId;
}
async UNSAFE_componentWillMount() {
const result = await this.props.fetchInterfaceColList(this.props.match.params.id);
let { currCaseId } = this.props;
const params = this.props.match.params;
const { actionId } = params;
currCaseId = +actionId || +currCaseId || result.payload.data.data[0].caseList[0]._id;
let currColId = this.getColId(result.payload.data.data, currCaseId);
// this.props.history.push('/project/' + params.id + '/interface/case/' + currCaseId);
await this.props.fetchCaseData(currCaseId);
this.props.setColData({ currCaseId: +currCaseId, currColId, isShowCol: false });
// 获取当前case 下的环境变量
await this.props.getEnv(this.props.currCase.project_id);
// await this.getCurrEnv()
this.setState({ editCasename: this.props.currCase.casename });
}
async UNSAFE_componentWillReceiveProps(nextProps) {
const oldCaseId = this.props.match.params.actionId;
const newCaseId = nextProps.match.params.actionId;
const { interfaceColList } = nextProps;
let currColId = this.getColId(interfaceColList, newCaseId);
if (oldCaseId !== newCaseId) {
await this.props.fetchCaseData(newCaseId);
this.props.setColData({ currCaseId: +newCaseId, currColId, isShowCol: false });
await this.props.getEnv(this.props.currCase.project_id);
// await this.getCurrEnv()
this.setState({ editCasename: this.props.currCase.casename });
}
}
savePostmanRef = postman => {
this.postman = postman;
};
updateCase = async () => {
const {
case_env,
req_params,
req_query,
req_headers,
req_body_type,
req_body_form,
req_body_other,
test_script,
enable_script,
test_res_body,
test_res_header
} = this.postman.state;
const { editCasename: casename } = this.state;
const { _id: id } = this.props.currCase;
let params = {
id,
casename,
case_env,
req_params,
req_query,
req_headers,
req_body_type,
req_body_form,
req_body_other,
test_script,
enable_script,
test_res_body,
test_res_header
};
const res = await axios.post('/api/col/up_case', params);
if (this.props.currCase.casename !== casename) {
this.props.fetchInterfaceColList(this.props.match.params.id);
}
if (res.data.errcode) {
message.error(res.data.errmsg);
} else {
message.success('更新成功');
this.props.fetchCaseData(id);
}
};
triggerEditCasename = () => {
this.setState({
isEditingCasename: true,
editCasename: this.props.currCase.casename
});
};
cancelEditCasename = () => {
this.setState({
isEditingCasename: false,
editCasename: this.props.currCase.casename
});
};
render() {
const { currCase, currProject, projectEnv } = this.props;
const { isEditingCasename, editCasename } = this.state;
const data = Object.assign(
{},
currCase,
{
env: projectEnv.env,
pre_script: currProject.pre_script,
after_script: currProject.after_script
},
{ _id: currCase._id }
);
return (
<div style={{ padding: '6px 0' }} className="case-content">
<div className="case-title">
{!isEditingCasename && (
<Tooltip title="点击编辑" placement="bottom">
<div className="case-name" onClick={this.triggerEditCasename}>
{currCase.casename}
</div>
</Tooltip>
)}
{isEditingCasename && (
<div className="edit-case-name">
<Input
value={editCasename}
onChange={e => this.setState({ editCasename: e.target.value })}
style={{ fontSize: 18 }}
/>
</div>
)}
<span className="inter-link" style={{ margin: '0px 8px 0px 6px', fontSize: 12 }}>
<Link
className="text"
to={`/project/${currCase.project_id}/interface/api/${currCase.interface_id}`}
>
对应接口
</Link>
</span>
</div>
<div>
{Object.keys(currCase).length > 0 && (
<Postman
data={data}
type="case"
saveTip="更新保存修改"
save={this.updateCase}
ref={this.savePostmanRef}
interfaceId={currCase.interface_id}
projectId={currCase.project_id}
curUid={this.props.curUid}
/>
)}
</div>
</div>
);
}
}

View File

@@ -0,0 +1,33 @@
.case-content {
padding: 6px 0;
.case-title {
display: flex;
.case-name {
margin-left: 8px;
border-radius: 4px;
border: 1px solid transparent;
padding: 0 5px;
background-color: #eee;
font-size: 20px;
flex-grow: 1;
cursor: pointer;
}
.case-name:hover {
color: rgba(0,0,0,.65);
border: 1px solid #d9d9d9;
}
.edit-case-name {
margin-left: 8px;
display: flex;
flex-grow: 1;
}
.inter-link {
flex-basis: 50px;
position: relative;
}
.inter-link .text {
position: absolute;
bottom: 4px;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,630 @@
import React, { PureComponent as Component } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import PropTypes from 'prop-types';
import {
fetchInterfaceColList,
fetchInterfaceCaseList,
setColData,
fetchCaseList,
fetchCaseData
} from '../../../../reducer/modules/interfaceCol';
import { fetchProjectList } from '../../../../reducer/modules/project';
import axios from 'axios';
import ImportInterface from './ImportInterface';
import { Input, Icon, Button, Modal, message, Tooltip, Tree, Form } from 'antd';
import { arrayChangeIndex } from '../../../../common.js';
import _ from 'underscore'
const TreeNode = Tree.TreeNode;
const FormItem = Form.Item;
const confirm = Modal.confirm;
const headHeight = 240; // menu顶部到网页顶部部分的高度
import './InterfaceColMenu.scss';
const ColModalForm = Form.create()(props => {
const { visible, onCancel, onCreate, form, title } = props;
const { getFieldDecorator } = form;
return (
<Modal visible={visible} title={title} onCancel={onCancel} onOk={onCreate}>
<Form layout="vertical">
<FormItem label="集合名">
{getFieldDecorator('colName', {
rules: [{ required: true, message: '请输入集合命名!' }]
})(<Input />)}
</FormItem>
<FormItem label="简介">{getFieldDecorator('colDesc')(<Input type="textarea" />)}</FormItem>
</Form>
</Modal>
);
});
@connect(
state => {
return {
interfaceColList: state.interfaceCol.interfaceColList,
currCase: state.interfaceCol.currCase,
isRander: state.interfaceCol.isRander,
currCaseId: state.interfaceCol.currCaseId,
// list: state.inter.list,
// 当前项目的信息
curProject: state.project.currProject
// projectList: state.project.projectList
};
},
{
fetchInterfaceColList,
fetchInterfaceCaseList,
fetchCaseData,
// fetchInterfaceListMenu,
fetchCaseList,
setColData,
fetchProjectList
}
)
@withRouter
export default class InterfaceColMenu extends Component {
static propTypes = {
match: PropTypes.object,
interfaceColList: PropTypes.array,
fetchInterfaceColList: PropTypes.func,
fetchInterfaceCaseList: PropTypes.func,
// fetchInterfaceListMenu: PropTypes.func,
fetchCaseList: PropTypes.func,
fetchCaseData: PropTypes.func,
setColData: PropTypes.func,
currCaseId: PropTypes.number,
history: PropTypes.object,
isRander: PropTypes.bool,
// list: PropTypes.array,
router: PropTypes.object,
currCase: PropTypes.object,
curProject: PropTypes.object,
fetchProjectList: PropTypes.func
// projectList: PropTypes.array
};
state = {
colModalType: '',
colModalVisible: false,
editColId: 0,
filterValue: '',
importInterVisible: false,
importInterIds: [],
importColId: 0,
expands: null,
list: [],
delIcon: null,
selectedProject: null
};
constructor(props) {
super(props);
}
UNSAFE_componentWillMount() {
this.getList();
}
UNSAFE_componentWillReceiveProps(nextProps) {
if (this.props.interfaceColList !== nextProps.interfaceColList) {
this.setState({
list: nextProps.interfaceColList
});
}
}
async getList() {
let r = await this.props.fetchInterfaceColList(this.props.match.params.id);
this.setState({
list: r.payload.data.data
});
return r;
}
addorEditCol = async () => {
const { colName: name, colDesc: desc } = this.form.getFieldsValue();
const { colModalType, editColId: col_id } = this.state;
const project_id = this.props.match.params.id;
let res = {};
if (colModalType === 'add') {
res = await axios.post('/api/col/add_col', { name, desc, project_id });
} else if (colModalType === 'edit') {
res = await axios.post('/api/col/up_col', { name, desc, col_id });
}
if (!res.data.errcode) {
this.setState({
colModalVisible: false
});
message.success(colModalType === 'edit' ? '修改集合成功' : '添加集合成功');
// await this.props.fetchInterfaceColList(project_id);
this.getList();
} else {
message.error(res.data.errmsg);
}
};
onExpand = keys => {
this.setState({ expands: keys });
};
onSelect = _.debounce(keys => {
if (keys.length) {
const type = keys[0].split('_')[0];
const id = keys[0].split('_')[1];
const project_id = this.props.match.params.id;
if (type === 'col') {
this.props.setColData({
isRander: false
});
this.props.history.push('/project/' + project_id + '/interface/col/' + id);
} else {
this.props.setColData({
isRander: false
});
this.props.history.push('/project/' + project_id + '/interface/case/' + id);
}
}
this.setState({
expands: null
});
}, 500);
showDelColConfirm = colId => {
let that = this;
const params = this.props.match.params;
confirm({
title: '您确认删除此测试集合',
content: '温馨提示:该操作会删除该集合下所有测试用例,用例删除后无法恢复',
okText: '确认',
cancelText: '取消',
async onOk() {
const res = await axios.get('/api/col/del_col?col_id=' + colId);
if (!res.data.errcode) {
message.success('删除集合成功');
const result = await that.getList();
const nextColId = result.payload.data.data[0]._id;
that.props.history.push('/project/' + params.id + '/interface/col/' + nextColId);
} else {
message.error(res.data.errmsg);
}
}
});
};
// 复制测试集合
copyInterface = async item => {
if (this._copyInterfaceSign === true) {
return;
}
this._copyInterfaceSign = true;
const { desc, project_id, _id: col_id } = item;
let { name } = item;
name = `${name} copy`;
// 添加集合
const add_col_res = await axios.post('/api/col/add_col', { name, desc, project_id });
if (add_col_res.data.errcode) {
message.error(add_col_res.data.errmsg);
return;
}
const new_col_id = add_col_res.data.data._id;
// 克隆集合
const add_case_list_res = await axios.post('/api/col/clone_case_list', {
new_col_id,
col_id,
project_id
});
this._copyInterfaceSign = false;
if (add_case_list_res.data.errcode) {
message.error(add_case_list_res.data.errmsg);
return;
}
// 刷新接口列表
// await this.props.fetchInterfaceColList(project_id);
this.getList();
this.props.setColData({ isRander: true });
message.success('克隆测试集成功');
};
showNoDelColConfirm = () => {
confirm({
title: '此测试集合为最后一个集合',
content: '温馨提示:建议不要删除'
});
};
caseCopy = async caseId=> {
let that = this;
let caseData = await that.props.fetchCaseData(caseId);
let data = caseData.payload.data.data;
data = JSON.parse(JSON.stringify(data));
data.casename=`${data.casename}_copy`
delete data._id
const res = await axios.post('/api/col/add_case',data);
if (!res.data.errcode) {
message.success('克隆用例成功');
let colId = res.data.data.col_id;
let projectId=res.data.data.project_id;
await this.getList();
this.props.history.push('/project/' + projectId + '/interface/col/' + colId);
this.setState({
visible: false
});
} else {
message.error(res.data.errmsg);
}
};
showDelCaseConfirm = caseId => {
let that = this;
const params = this.props.match.params;
confirm({
title: '您确认删除此测试用例',
content: '温馨提示:用例删除后无法恢复',
okText: '确认',
cancelText: '取消',
async onOk() {
const res = await axios.get('/api/col/del_case?caseid=' + caseId);
if (!res.data.errcode) {
message.success('删除用例成功');
that.getList();
// 如果删除当前选中 case切换路由到集合
if (+caseId === +that.props.currCaseId) {
that.props.history.push('/project/' + params.id + '/interface/col/');
} else {
// that.props.fetchInterfaceColList(that.props.match.params.id);
that.props.setColData({ isRander: true });
}
} else {
message.error(res.data.errmsg);
}
}
});
};
showColModal = (type, col) => {
const editCol =
type === 'edit' ? { colName: col.name, colDesc: col.desc } : { colName: '', colDesc: '' };
this.setState({
colModalVisible: true,
colModalType: type || 'add',
editColId: col && col._id
});
this.form.setFieldsValue(editCol);
};
saveFormRef = form => {
this.form = form;
};
selectInterface = (importInterIds, selectedProject) => {
this.setState({ importInterIds, selectedProject });
};
showImportInterfaceModal = async colId => {
// const projectId = this.props.match.params.id;
// console.log('project', this.props.curProject)
const groupId = this.props.curProject.group_id;
await this.props.fetchProjectList(groupId);
// await this.props.fetchInterfaceListMenu(projectId)
this.setState({ importInterVisible: true, importColId: colId });
};
handleImportOk = async () => {
const project_id = this.state.selectedProject || this.props.match.params.id;
const { importColId, importInterIds } = this.state;
const res = await axios.post('/api/col/add_case_list', {
interface_list: importInterIds,
col_id: importColId,
project_id
});
if (!res.data.errcode) {
this.setState({ importInterVisible: false });
message.success('导入集合成功');
// await this.props.fetchInterfaceColList(project_id);
this.getList();
this.props.setColData({ isRander: true });
} else {
message.error(res.data.errmsg);
}
};
handleImportCancel = () => {
this.setState({ importInterVisible: false });
};
filterCol = e => {
const value = e.target.value;
// console.log('list', this.props.interfaceColList);
// const newList = produce(this.props.interfaceColList, draftList => {})
// console.log('newList',newList);
this.setState({
filterValue: value,
list: JSON.parse(JSON.stringify(this.props.interfaceColList))
// list: newList
});
};
onDrop = async e => {
// const projectId = this.props.match.params.id;
const { interfaceColList } = this.props;
const dropColIndex = e.node.props.pos.split('-')[1];
const dropColId = interfaceColList[dropColIndex]._id;
const id = e.dragNode.props.eventKey;
const dragColIndex = e.dragNode.props.pos.split('-')[1];
const dragColId = interfaceColList[dragColIndex]._id;
const dropPos = e.node.props.pos.split('-');
const dropIndex = Number(dropPos[dropPos.length - 1]);
const dragPos = e.dragNode.props.pos.split('-');
const dragIndex = Number(dragPos[dragPos.length - 1]);
if (id.indexOf('col') === -1) {
if (dropColId === dragColId) {
// 同一个测试集合下的接口交换顺序
let caseList = interfaceColList[dropColIndex].caseList;
let changes = arrayChangeIndex(caseList, dragIndex, dropIndex);
axios.post('/api/col/up_case_index', changes).then();
}
await axios.post('/api/col/up_case', { id: id.split('_')[1], col_id: dropColId });
// this.props.fetchInterfaceColList(projectId);
this.getList();
this.props.setColData({ isRander: true });
} else {
let changes = arrayChangeIndex(interfaceColList, dragIndex, dropIndex);
axios.post('/api/col/up_col_index', changes).then();
this.getList();
}
};
enterItem = id => {
this.setState({ delIcon: id });
};
leaveItem = () => {
this.setState({ delIcon: null });
};
render() {
// const { currColId, currCaseId, isShowCol } = this.props;
const { colModalType, colModalVisible, importInterVisible } = this.state;
const currProjectId = this.props.match.params.id;
// const menu = (col) => {
// return (
// <Menu>
// <Menu.Item>
// <span onClick={() => this.showColModal('edit', col)}>修改集合</span>
// </Menu.Item>
// <Menu.Item>
// <span onClick={() => {
// this.showDelColConfirm(col._id)
// }}>删除集合</span>
// </Menu.Item>
// <Menu.Item>
// <span onClick={() => this.showImportInterface(col._id)}>导入接口</span>
// </Menu.Item>
// </Menu>
// )
// };
const defaultExpandedKeys = () => {
const { router, currCase, interfaceColList } = this.props,
rNull = { expands: [], selects: [] };
if (interfaceColList.length === 0) {
return rNull;
}
if (router) {
if (router.params.action === 'case') {
if (!currCase || !currCase._id) {
return rNull;
}
return {
expands: this.state.expands ? this.state.expands : ['col_' + currCase.col_id],
selects: ['case_' + currCase._id + '']
};
} else {
let col_id = router.params.actionId;
return {
expands: this.state.expands ? this.state.expands : ['col_' + col_id],
selects: ['col_' + col_id]
};
}
} else {
return {
expands: this.state.expands ? this.state.expands : ['col_' + interfaceColList[0]._id],
selects: ['col_' + interfaceColList[0]._id]
};
}
};
const itemInterfaceColCreate = interfaceCase => {
return (
<TreeNode
style={{ width: '100%' }}
key={'case_' + interfaceCase._id}
title={
<div
className="menu-title"
onMouseEnter={() => this.enterItem(interfaceCase._id)}
onMouseLeave={this.leaveItem}
title={interfaceCase.casename}
>
<span className="casename">{interfaceCase.casename}</span>
<div className="btns">
<Tooltip title="删除用例">
<Icon
type="delete"
className="interface-delete-icon"
onClick={e => {
e.stopPropagation();
this.showDelCaseConfirm(interfaceCase._id);
}}
style={{ display: this.state.delIcon == interfaceCase._id ? 'block' : 'none' }}
/>
</Tooltip>
<Tooltip title="克隆用例">
<Icon
type="copy"
className="interface-delete-icon"
onClick={e => {
e.stopPropagation();
this.caseCopy(interfaceCase._id);
}}
style={{ display: this.state.delIcon == interfaceCase._id ? 'block' : 'none' }}
/>
</Tooltip>
</div>
</div>
}
/>
);
};
let currentKes = defaultExpandedKeys();
// console.log('currentKey', currentKes)
let list = this.state.list;
if (this.state.filterValue) {
let arr = [];
list = list.filter(item => {
item.caseList = item.caseList.filter(inter => {
if (inter.casename.indexOf(this.state.filterValue) === -1
&& inter.path.indexOf(this.state.filterValue) === -1
) {
return false;
}
return true;
});
arr.push('col_' + item._id);
return true;
});
// console.log('arr', arr);
if (arr.length > 0) {
currentKes.expands = arr;
}
}
// console.log('list', list);
// console.log('currentKey', currentKes)
return (
<div>
<div className="interface-filter">
<Input placeholder="搜索测试集合" onChange={this.filterCol} />
<Tooltip placement="bottom" title="添加集合">
<Button
type="primary"
style={{ marginLeft: '16px' }}
onClick={() => this.showColModal('add')}
className="btn-filter"
>
添加集合
</Button>
</Tooltip>
</div>
<div className="tree-wrapper" style={{ maxHeight: parseInt(document.body.clientHeight) - headHeight + 'px'}}>
<Tree
className="col-list-tree"
defaultExpandedKeys={currentKes.expands}
defaultSelectedKeys={currentKes.selects}
expandedKeys={currentKes.expands}
selectedKeys={currentKes.selects}
onSelect={this.onSelect}
autoExpandParent
draggable
onExpand={this.onExpand}
onDrop={this.onDrop}
>
{list.map(col => (
<TreeNode
key={'col_' + col._id}
title={
<div className="menu-title">
<span>
<Icon type="folder-open" style={{ marginRight: 5 }} />
<span>{col.name}</span>
</span>
<div className="btns">
<Tooltip title="删除集合">
<Icon
type="delete"
style={{ display: list.length > 1 ? '' : 'none' }}
className="interface-delete-icon"
onClick={() => {
this.showDelColConfirm(col._id);
}}
/>
</Tooltip>
<Tooltip title="编辑集合">
<Icon
type="edit"
className="interface-delete-icon"
onClick={e => {
e.stopPropagation();
this.showColModal('edit', col);
}}
/>
</Tooltip>
<Tooltip title="导入接口">
<Icon
type="plus"
className="interface-delete-icon"
onClick={e => {
e.stopPropagation();
this.showImportInterfaceModal(col._id);
}}
/>
</Tooltip>
<Tooltip title="克隆集合">
<Icon
type="copy"
className="interface-delete-icon"
onClick={e => {
e.stopPropagation();
this.copyInterface(col);
}}
/>
</Tooltip>
</div>
{/*<Dropdown overlay={menu(col)} trigger={['click']} onClick={e => e.stopPropagation()}>
<Icon className="opts-icon" type='ellipsis'/>
</Dropdown>*/}
</div>
}
>
{col.caseList.map(itemInterfaceColCreate)}
</TreeNode>
))}
</Tree>
</div>
<ColModalForm
ref={this.saveFormRef}
type={colModalType}
visible={colModalVisible}
onCancel={() => {
this.setState({ colModalVisible: false });
}}
onCreate={this.addorEditCol}
/>
<Modal
title="导入接口到集合"
visible={importInterVisible}
onOk={this.handleImportOk}
onCancel={this.handleImportCancel}
className="import-case-modal"
width={800}
>
<ImportInterface currProjectId={currProjectId} selectInterface={this.selectInterface} />
</Modal>
</div>
);
}
}

View File

@@ -0,0 +1,186 @@
.col-list-tree {
line-height: 25px;
.ant-tree-node-content-wrapper {
width: calc(100% - 28px);
}
.opts-icon,
.case-delete-icon {
line-height: 25px;
width: 30px;
font-weight: bold;
}
.opts-icon:hover,
.case-delete-icon:hover {
color: #2395f1;
}
.menu-title {
display: flex;
justify-content: space-between;
overflow: hidden;
.casename {
overflow: hidden;
}
.case-delete-icon {
margin-left: 5px;
display: none;
}
.btns {
display: none;
}
}
.menu-title:hover {
.case-delete-icon {
display: block;
}
.btns {
display: block;
}
}
}
.container {
display: block;
width: 100%;
padding: 10px;
}
/*
* note that styling gu-mirror directly is a bad practice because it's too generic.
* you're better off giving the draggable elements a unique class and styling that directly!
*/
.gu-mirror {
padding: 10px;
background-color: rgba(0, 0, 0, 0.2);
transition: opacity 0.4s ease-in-out;
}
.container div {
cursor: move;
cursor: grab;
cursor: -moz-grab;
cursor: -webkit-grab;
margin-bottom: 10px;
}
.container div:last-child {
margin-bottom: 0;
}
.gu-mirror {
cursor: grabbing;
cursor: -moz-grabbing;
cursor: -webkit-grabbing;
}
.container .ex-moved {
background-color: #e74c3c;
}
.container.ex-over {
background-color: rgba(255, 255, 255, 0.3);
}
.handle {
padding: 0 5px;
margin-right: 5px;
background-color: rgba(0, 0, 0, 0.4);
cursor: move;
}
.report {
min-height: 500px;
.case-report-pane {
margin-top: 10px;
}
.url {
overflow: auto;
}
.case-report {
margin: 10px;
.case-report-title {
font-size: 14px;
font-weight: bold;
text-align: right;
padding-right: 20px;
}
pre {
white-space: pre-wrap;
}
}
}
.interface-col {
padding: 24px;
.interface-col-table-header {
background-color: rgb(238, 238, 238);
height: 50px;
line-height: 50px;
text-align: left;
}
.interface-col-table-body {
height: 50px;
line-height: 50px;
}
.interface-col-table-header th {
padding-left: 5px;
}
.interface-col-table-body td {
padding-left: 5px;
}
.interface-col-table-action button {
margin-right: 5px;
padding: 5px 10px;
max-width: 90px;
}
.component-label-wrapper {
margin-top: -10px;
margin-bottom: 15px;
}
}
.import-case-modal {
.ant-modal-body {
max-height: 800px;
overflow-y: scroll;
}
.select-project {
margin-bottom: 16px;
}
}
.autoTestsModal {
.autoTestUrl {
overflow: auto;
background-color: #f5f5f5;
border: 1px solid #f1f1f1ce;
padding: 16px;
}
.autoTestMsg {
padding: 8px 0 16px;
font-size: 12px;
}
.copy-btn {
margin-left: 16px;
height: 50px;
font-size: 14px;
width: 70px;
}
.ant-modal-body {
padding-top: 32px;
}
.row {
margin-bottom: 0.24rem;
}
.label {
text-align: left;
}
}
.tree-wrapper {
min-height: 500px;
overflow-y: scroll;
}

View File

@@ -0,0 +1,69 @@
import React, { PureComponent as Component } from 'react';
import PropTypes from 'prop-types';
import { Form, Input, Button } from 'antd';
const FormItem = Form.Item;
function hasErrors(fieldsError) {
return Object.keys(fieldsError).some(field => fieldsError[field]);
}
class AddInterfaceForm extends Component {
static propTypes = {
form: PropTypes.object,
onSubmit: PropTypes.func,
onCancel: PropTypes.func,
catdata: PropTypes.object
};
handleSubmit = e => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
this.props.onSubmit(values);
}
});
};
render() {
const { getFieldDecorator, getFieldsError } = this.props.form;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 6 }
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 }
}
};
return (
<Form onSubmit={this.handleSubmit}>
<FormItem {...formItemLayout} label="分类名">
{getFieldDecorator('name', {
rules: [
{
required: true,
message: '请输入分类名称!'
}
],
initialValue: this.props.catdata ? this.props.catdata.name || null : null
})(<Input placeholder="分类名称" />)}
</FormItem>
<FormItem {...formItemLayout} label="备注">
{getFieldDecorator('desc', {
initialValue: this.props.catdata ? this.props.catdata.desc || null : null
})(<Input placeholder="备注" />)}
</FormItem>
<FormItem className="catModalfoot" wrapperCol={{ span: 24, offset: 8 }}>
<Button onClick={this.props.onCancel} style={{ marginRight: '10px' }}>
取消
</Button>
<Button type="primary" htmlType="submit" disabled={hasErrors(getFieldsError())}>
提交
</Button>
</FormItem>
</Form>
);
}
}
export default Form.create()(AddInterfaceForm);

View File

@@ -0,0 +1,129 @@
import React, { PureComponent as Component } from 'react'
import PropTypes from 'prop-types'
import { Form, Input, Select, Button } from 'antd';
import constants from '../../../../constants/variable.js'
import { handleApiPath, nameLengthLimit } from '../../../../common.js'
const HTTP_METHOD = constants.HTTP_METHOD;
const HTTP_METHOD_KEYS = Object.keys(HTTP_METHOD);
const FormItem = Form.Item;
const Option = Select.Option;
function hasErrors(fieldsError) {
return Object.keys(fieldsError).some(field => fieldsError[field]);
}
class AddInterfaceForm extends Component {
static propTypes = {
form: PropTypes.object,
onSubmit: PropTypes.func,
onCancel: PropTypes.func,
catid: PropTypes.number,
catdata: PropTypes.array
}
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
this.props.onSubmit(values, () => {
this.props.form.resetFields();
});
}
});
}
handlePath = (e) => {
let val = e.target.value
this.props.form.setFieldsValue({
path: handleApiPath(val)
})
}
render() {
const { getFieldDecorator, getFieldsError } = this.props.form;
const prefixSelector = getFieldDecorator('method', {
initialValue: 'GET'
})(
<Select style={{ width: 75 }}>
{HTTP_METHOD_KEYS.map(item => {
return <Option key={item} value={item}>{item}</Option>
})}
</Select>
);
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 6 }
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 }
}
};
return (
<Form onSubmit={this.handleSubmit}>
<FormItem
{...formItemLayout}
label="接口分类"
>
{getFieldDecorator('catid', {
initialValue: this.props.catid ? this.props.catid + '' : this.props.catdata[0]._id + ''
})(
<Select>
{this.props.catdata.map(item => {
return <Option key={item._id} value={item._id + ""}>{item.name}</Option>
})}
</Select>
)}
</FormItem>
<FormItem
{...formItemLayout}
label="接口名称"
>
{getFieldDecorator('title', {
rules: nameLengthLimit('接口')
})(
<Input placeholder="接口名称" />
)}
</FormItem>
<FormItem
{...formItemLayout}
label="接口路径"
>
{getFieldDecorator('path', {
rules: [{
required: true, message: '请输入接口路径!'
}]
})(
<Input onBlur={this.handlePath} addonBefore={prefixSelector} placeholder="/path" />
)}
</FormItem>
<FormItem
{...formItemLayout}
label="注"
>
<span style={{ color: "#929292" }}>详细的接口数据可以在编辑页面中添加</span>
</FormItem>
<FormItem className="catModalfoot" wrapperCol={{ span: 24, offset: 8 }} >
<Button onClick={this.props.onCancel} style={{ marginRight: "10px" }} >取消</Button>
<Button
type="primary"
htmlType="submit"
disabled={hasErrors(getFieldsError())}
>
提交
</Button>
</FormItem>
</Form>
);
}
}
export default Form.create()(AddInterfaceForm);

View File

@@ -0,0 +1,229 @@
import React, { PureComponent as Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import InterfaceEditForm from './InterfaceEditForm.js';
import {
updateInterfaceData,
fetchInterfaceListMenu,
fetchInterfaceData
} from '../../../../reducer/modules/interface.js';
import { getProject } from '../../../../reducer/modules/project.js';
import axios from 'axios';
import { message, Modal } from 'antd';
import './Edit.scss';
import { withRouter, Link } from 'react-router-dom';
import ProjectTag from '../../Setting/ProjectMessage/ProjectTag.js';
@connect(
state => {
return {
curdata: state.inter.curdata,
currProject: state.project.currProject
};
},
{
updateInterfaceData,
fetchInterfaceListMenu,
fetchInterfaceData,
getProject
}
)
class InterfaceEdit extends Component {
static propTypes = {
curdata: PropTypes.object,
currProject: PropTypes.object,
updateInterfaceData: PropTypes.func,
fetchInterfaceListMenu: PropTypes.func,
fetchInterfaceData: PropTypes.func,
match: PropTypes.object,
switchToView: PropTypes.func,
getProject: PropTypes.func
};
constructor(props) {
super(props);
const { curdata, currProject } = this.props;
this.state = {
mockUrl:
location.protocol +
'//' +
location.hostname +
(location.port !== '' ? ':' + location.port : '') +
`/mock/${currProject._id}${currProject.basepath}${curdata.path}`,
curdata: {},
status: 0,
visible: false
// tag: []
};
}
onSubmit = async params => {
params.id = this.props.match.params.actionId;
let result = await axios.post('/api/interface/up', params);
this.props.fetchInterfaceListMenu(this.props.currProject._id).then();
this.props.fetchInterfaceData(params.id).then();
if (result.data.errcode === 0) {
this.props.updateInterfaceData(params);
message.success('保存成功');
} else {
message.error(result.data.errmsg);
}
};
componentWillUnmount() {
try {
if (this.state.status === 1) {
this.WebSocket.close();
}
} catch (e) {
return null;
}
}
componentDidMount() {
let domain = location.hostname + (location.port !== '' ? ':' + location.port : '');
let s,
initData = false;
//因后端 node 仅支持 ws 暂不支持 wss
let wsProtocol = location.protocol === 'https:' ? 'wss' : 'ws';
setTimeout(() => {
if (initData === false) {
this.setState({
curdata: this.props.curdata,
status: 1
});
initData = true;
}
}, 3000);
try {
s = new WebSocket(
wsProtocol +
'://' +
domain +
'/api/interface/solve_conflict?id=' +
this.props.match.params.actionId
);
s.onopen = () => {
this.WebSocket = s;
};
s.onmessage = e => {
initData = true;
let result = JSON.parse(e.data);
if (result.errno === 0) {
this.setState({
curdata: result.data,
status: 1
});
} else {
this.setState({
curdata: result.data,
status: 2
});
}
};
s.onerror = () => {
this.setState({
curdata: this.props.curdata,
status: 1
});
console.warn('websocket 连接失败,将导致多人编辑同一个接口冲突。');
};
} catch (e) {
this.setState({
curdata: this.props.curdata,
status: 1
});
console.error('websocket 连接失败,将导致多人编辑同一个接口冲突。');
}
}
onTagClick = () => {
this.setState({
visible: true
});
};
handleOk = async () => {
let { tag } = this.tag.state;
tag = tag.filter(val => {
return val.name !== '';
});
let id = this.props.currProject._id;
let params = {
id,
tag
};
let result = await axios.post('/api/project/up_tag', params);
if (result.data.errcode === 0) {
await this.props.getProject(id);
message.success('保存成功');
} else {
message.error(result.data.errmsg);
}
this.setState({
visible: false
});
};
handleCancel = () => {
this.setState({
visible: false
});
};
tagSubmit = tagRef => {
this.tag = tagRef;
// this.setState({tag})
};
render() {
const { cat, basepath, switch_notice, tag } = this.props.currProject;
return (
<div className="interface-edit">
{this.state.status === 1 ? (
<InterfaceEditForm
cat={cat}
mockUrl={this.state.mockUrl}
basepath={basepath}
noticed={switch_notice}
onSubmit={this.onSubmit}
curdata={this.state.curdata}
onTagClick={this.onTagClick}
/>
) : null}
{this.state.status === 2 ? (
<div style={{ textAlign: 'center', fontSize: '14px', paddingTop: '10px' }}>
<Link to={'/user/profile/' + this.state.curdata.uid}>
<b>{this.state.curdata.username}</b>
</Link>
<span>正在编辑该接口请稍后再试...</span>
</div>
) : null}
{this.state.status === 0 && '正在加载,请耐心等待...'}
<Modal
title="Tag 设置"
width={680}
visible={this.state.visible}
onOk={this.handleOk}
onCancel={this.handleCancel}
okText="保存"
>
<div className="tag-modal-center">
<ProjectTag tagMsg={tag} ref={this.tagSubmit} />
</div>
</Modal>
</div>
);
}
}
export default withRouter(InterfaceEdit);

View File

@@ -0,0 +1,116 @@
@import '../../../../styles/mixin.scss';
.interface-edit{
padding: 24px;
// overflow: hidden;
.interface-edit-item{
margin-bottom: 16px;
.ant-form-item-label label:after{
margin-left: 4px;
}
.interface-editor {
min-height: 300px;
}
}
.interface-edit-json-info{
margin-bottom: 5px;
}
.interface-edit-item.hide {
display: none;
}
.interface-edit-item-content{
margin-bottom: 16px;
.interface-edit-item-content-col{
padding:0 1px;
}
.interface-edit-item-content-col-drag{
width:24px;
padding: 7px;
cursor: ns-resize;
}
}
.interface-edit-del-icon{
margin-top: 10px;
margin-left: 5px;
cursor: pointer
}
.interface-edit-direc-icon{
margin-top: 5px;
margin-left: 5px;
cursor: pointer
}
.ant-select-selection__rendered{
line-height: 34px;
}
.interace-edit-desc{
height: 250px;
}
.ant-affix{
background-color: #f3f4f6;
padding: 16px 0;
z-index: 999;
}
.interface-edit-submit-button{
background-color: #1d1d3d;
color: #fff;
}
.interface-edit-submit-button:hover{
border-color: #434370;
background-color: #434370;
}
}
.table-interfacelist {
margin-top: .2rem;
white-space: nowrap;
table {
table-layout: fixed;
}
.path {
width: 95%;
display: inline-block;
overflow: hidden;
text-overflow:ellipsis;
white-space: nowrap;
padding-right: 24px;
// line-height: 100%;
vertical-align: middle;
}
.opened {
color: #00a854;
padding-right: 6px;
font-size: 14px;
}
.colValue{
display: inline-block;
border-radius: 4px;
color: #00a854;
background: #cfefdf;
border-color: #cfefdf;
height: 23px;
line-height: 23px;
text-align: center;
font-size: 10px;
margin-right: 7px;
padding: 0 5px;
}
.ant-select-selection {
background-color: transparent;
border: none;
}
}
.toolTip .ant-tooltip-inner{
white-space: normal;
word-break: break-all;
}
.tag-modal-center {
padding-left: 48px;
}

View File

@@ -0,0 +1,183 @@
import React, { PureComponent as Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Tabs, Modal, Button } from 'antd';
import Edit from './Edit.js';
import View from './View.js';
import { Prompt } from 'react-router';
import { fetchInterfaceData } from '../../../../reducer/modules/interface.js';
import { withRouter } from 'react-router-dom';
import Run from './Run/Run.js';
const plugin = require('client/plugin.js');
const TabPane = Tabs.TabPane;
@connect(
state => {
return {
curdata: state.inter.curdata,
list: state.inter.list,
editStatus: state.inter.editStatus
};
},
{
fetchInterfaceData
}
)
class Content extends Component {
static propTypes = {
match: PropTypes.object,
list: PropTypes.array,
curdata: PropTypes.object,
fetchInterfaceData: PropTypes.func,
history: PropTypes.object,
editStatus: PropTypes.bool
};
constructor(props) {
super(props);
this.title = 'YApi-高效、易用、功能强大的可视化接口管理平台';
this.state = {
curtab: 'view',
visible: false,
nextTab: ''
};
}
UNSAFE_componentWillMount() {
const params = this.props.match.params;
this.actionId = params.actionId;
this.handleRequest(this.props);
}
componentWillUnmount() {
document.getElementsByTagName('title')[0].innerText = this.title;
}
UNSAFE_componentWillReceiveProps(nextProps) {
const params = nextProps.match.params;
if (params.actionId !== this.actionId) {
this.actionId = params.actionId;
this.handleRequest(nextProps);
}
}
handleRequest(nextProps) {
const params = nextProps.match.params;
this.props.fetchInterfaceData(params.actionId);
this.setState({
curtab: 'view'
});
}
switchToView = () => {
this.setState({
curtab: 'view'
});
};
onChange = key => {
if (this.state.curtab === 'edit' && this.props.editStatus) {
this.showModal();
} else {
this.setState({
curtab: key
});
}
this.setState({
nextTab: key
});
};
// 确定离开页面
handleOk = () => {
this.setState({
visible: false,
curtab: this.state.nextTab
});
};
// 离开编辑页面的提示
showModal = () => {
this.setState({
visible: true
});
};
// 取消离开编辑页面
handleCancel = () => {
this.setState({
visible: false
});
};
render() {
if (this.props.curdata.title) {
document.getElementsByTagName('title')[0].innerText =
this.props.curdata.title + '-' + this.title;
}
let InterfaceTabs = {
view: {
component: View,
name: '预览'
},
edit: {
component: Edit,
name: '编辑'
},
run: {
component: Run,
name: '运行'
}
};
plugin.emitHook('interface_tab', InterfaceTabs);
const tabs = (
<Tabs
className="tabs-large"
onChange={this.onChange}
activeKey={this.state.curtab}
defaultActiveKey="view"
>
{Object.keys(InterfaceTabs).map(key => {
let item = InterfaceTabs[key];
return <TabPane tab={item.name} key={key} />;
})}
</Tabs>
);
let tabContent = null;
if (this.state.curtab) {
let C = InterfaceTabs[this.state.curtab].component;
tabContent = <C switchToView={this.switchToView} />;
}
return (
<div className="interface-content">
<Prompt
when={this.state.curtab === 'edit' && this.props.editStatus ? true : false}
message={() => {
// this.showModal();
return '离开页面会丢失当前编辑的内容,确定要离开吗?';
}}
/>
{tabs}
{tabContent}
{this.state.visible && (
<Modal
title="你即将离开编辑页面"
visible={this.state.visible}
onCancel={this.handleCancel}
footer={[
<Button key="back" onClick={this.handleCancel}>
</Button>,
<Button key="submit" onClick={this.handleOk}>
</Button>
]}
>
<p>离开页面会丢失当前编辑的内容确定要离开吗</p>
</Modal>
)}
</div>
);
}
}
export default withRouter(Content);

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,409 @@
import React, { PureComponent as Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import axios from 'axios';
import { Table, Button, Modal, message, Tooltip, Select, Icon } from 'antd';
import AddInterfaceForm from './AddInterfaceForm';
import {
fetchInterfaceListMenu,
fetchInterfaceList,
fetchInterfaceCatList
} from '../../../../reducer/modules/interface.js';
import { getProject } from '../../../../reducer/modules/project.js';
import { Link } from 'react-router-dom';
import variable from '../../../../constants/variable';
import './Edit.scss';
import Label from '../../../../components/Label/Label.js';
const Option = Select.Option;
const limit = 20;
@connect(
state => {
return {
curData: state.inter.curdata,
curProject: state.project.currProject,
catList: state.inter.list,
totalTableList: state.inter.totalTableList,
catTableList: state.inter.catTableList,
totalCount: state.inter.totalCount,
count: state.inter.count
};
},
{
fetchInterfaceListMenu,
fetchInterfaceList,
fetchInterfaceCatList,
getProject
}
)
class InterfaceList extends Component {
constructor(props) {
super(props);
this.state = {
visible: false,
data: [],
filteredInfo: {},
catid: null,
total: null,
current: 1
};
}
static propTypes = {
curData: PropTypes.object,
catList: PropTypes.array,
match: PropTypes.object,
curProject: PropTypes.object,
history: PropTypes.object,
fetchInterfaceListMenu: PropTypes.func,
fetchInterfaceList: PropTypes.func,
fetchInterfaceCatList: PropTypes.func,
totalTableList: PropTypes.array,
catTableList: PropTypes.array,
totalCount: PropTypes.number,
count: PropTypes.number,
getProject: PropTypes.func
};
handleRequest = async props => {
const { params } = props.match;
if (!params.actionId) {
let projectId = params.id;
this.setState({
catid: null
});
let option = {
page: this.state.current,
limit,
project_id: projectId,
status: this.state.filteredInfo.status,
tag: this.state.filteredInfo.tag
};
await this.props.fetchInterfaceList(option);
} else if (isNaN(params.actionId)) {
let catid = params.actionId.substr(4);
this.setState({catid: +catid});
let option = {
page: this.state.current,
limit,
catid,
status: this.state.filteredInfo.status,
tag: this.state.filteredInfo.tag
};
await this.props.fetchInterfaceCatList(option);
}
};
// 更新分类简介
handleChangeInterfaceCat = (desc, name) => {
let params = {
catid: this.state.catid,
name: name,
desc: desc
};
axios.post('/api/interface/up_cat', params).then(async res => {
if (res.data.errcode !== 0) {
return message.error(res.data.errmsg);
}
let project_id = this.props.match.params.id;
await this.props.getProject(project_id);
await this.props.fetchInterfaceListMenu(project_id);
message.success('接口集合简介更新成功');
});
};
handleChange = (pagination, filters, sorter) => {
this.setState({
current: pagination.current || 1,
sortedInfo: sorter,
filteredInfo: filters
}, () => this.handleRequest(this.props));
};
UNSAFE_componentWillMount() {
this.actionId = this.props.match.params.actionId;
this.handleRequest(this.props);
}
UNSAFE_componentWillReceiveProps(nextProps) {
let _actionId = nextProps.match.params.actionId;
if (this.actionId !== _actionId) {
this.actionId = _actionId;
this.setState(
{
current: 1
},
() => this.handleRequest(nextProps)
);
}
}
handleAddInterface = data => {
data.project_id = this.props.curProject._id;
axios.post('/api/interface/add', data).then(res => {
if (res.data.errcode !== 0) {
return message.error(`${res.data.errmsg}, 你可以在左侧的接口列表中对接口进行删改`);
}
message.success('接口添加成功');
let interfaceId = res.data.data._id;
this.props.history.push('/project/' + data.project_id + '/interface/api/' + interfaceId);
this.props.fetchInterfaceListMenu(data.project_id);
});
};
changeInterfaceCat = async (id, catid) => {
const params = {
id: id,
catid
};
let result = await axios.post('/api/interface/up', params);
if (result.data.errcode === 0) {
message.success('修改成功');
this.handleRequest(this.props);
this.props.fetchInterfaceListMenu(this.props.curProject._id);
} else {
message.error(result.data.errmsg);
}
};
changeInterfaceStatus = async value => {
const params = {
id: value.split('-')[0],
status: value.split('-')[1]
};
let result = await axios.post('/api/interface/up', params);
if (result.data.errcode === 0) {
message.success('修改成功');
this.handleRequest(this.props);
} else {
message.error(result.data.errmsg);
}
};
//page change will be processed in handleChange by pagination
// changePage = current => {
// if (this.state.current !== current) {
// this.setState(
// {
// current: current
// },
// () => this.handleRequest(this.props)
// );
// }
// };
render() {
let tag = this.props.curProject.tag;
let tagFilter = tag.map(item => {
return {text: item.name, value: item.name};
});
const columns = [
{
title: '接口名称',
dataIndex: 'title',
key: 'title',
width: 30,
render: (text, item) => {
return (
<Tooltip title= {text}>
<Link to={'/project/' + item.project_id + '/interface/api/' + item._id}>
<span className="path">{text}</span>
</Link>
</Tooltip>
);
}
},
{
title: '接口路径',
dataIndex: 'path',
key: 'path',
width: 50,
render: (item, record) => {
const path = this.props.curProject.basepath + item;
let methodColor =
variable.METHOD_COLOR[record.method ? record.method.toLowerCase() : 'get'] ||
variable.METHOD_COLOR['get'];
return (
<div>
<span
style={{ color: methodColor.color, backgroundColor: methodColor.bac }}
className="colValue"
>
{record.method}
</span>
<Tooltip title="开放接口" placement="topLeft">
<span>{record.api_opened && <Icon className="opened" type="eye-o" />}</span>
</Tooltip>
<Tooltip title={path} placement="topLeft" overlayClassName="toolTip">
<span className="path">{path}</span>
</Tooltip>
</div>
);
}
},
{
title: '接口分类',
dataIndex: 'catid',
key: 'catid',
width: 28,
render: (item, record) => {
return (
<Select
value={item + ''}
className="select path"
onChange={catid => this.changeInterfaceCat(record._id, catid)}
>
{this.props.catList.map(cat => {
return (
<Option key={cat.id + ''} value={cat._id + ''}>
<span>{cat.name}</span>
</Option>
);
})}
</Select>
);
}
},
{
title: '状态',
dataIndex: 'status',
key: 'status',
width: 24,
render: (text, record) => {
const key = record.key;
return (
<Select
value={key + '-' + text}
className="select"
onChange={this.changeInterfaceStatus}
>
<Option value={key + '-done'}>
<span className="tag-status done">已完成</span>
</Option>
<Option value={key + '-undone'}>
<span className="tag-status undone">未完成</span>
</Option>
</Select>
);
},
filters: [
{
text: '已完成',
value: 'done'
},
{
text: '未完成',
value: 'undone'
}
],
onFilter: (value, record) => record.status.indexOf(value) === 0
},
{
title: 'tag',
dataIndex: 'tag',
key: 'tag',
width: 14,
render: text => {
let textMsg = text.length > 0 ? text.join('\n') : '未设置';
return <div className="table-desc">{textMsg}</div>;
},
filters: tagFilter,
onFilter: (value, record) => {
return record.tag.indexOf(value) >= 0;
}
}
];
let intername = '',
desc = '';
let cat = this.props.curProject ? this.props.curProject.cat : [];
if (cat) {
for (let i = 0; i < cat.length; i++) {
if (cat[i]._id === this.state.catid) {
intername = cat[i].name;
desc = cat[i].desc;
break;
}
}
}
// const data = this.state.data ? this.state.data.map(item => {
// item.key = item._id;
// return item;
// }) : [];
let data = [];
let total = 0;
const { params } = this.props.match;
if (!params.actionId) {
data = this.props.totalTableList;
total = this.props.totalCount;
} else if (isNaN(params.actionId)) {
data = this.props.catTableList;
total = this.props.count;
}
data = data.map(item => {
item.key = item._id;
return item;
});
const pageConfig = {
total: total,
pageSize: limit,
current: this.state.current
// onChange: this.changePage
};
const isDisabled = this.props.catList.length === 0;
// console.log(this.props.curProject.tag)
return (
<div style={{ padding: '24px' }}>
<h2 className="interface-title" style={{ display: 'inline-block', margin: 0 }}>
{intername ? intername : '全部接口'} ({total})
</h2>
<Button
style={{ float: 'right' }}
disabled={isDisabled}
type="primary"
onClick={() => this.setState({ visible: true })}
>
添加接口
</Button>
<div style={{ marginTop: '10px' }}>
<Label onChange={value => this.handleChangeInterfaceCat(value, intername)} desc={desc} />
</div>
<Table
className="table-interfacelist"
pagination={pageConfig}
columns={columns}
onChange={this.handleChange}
dataSource={data}
/>
{this.state.visible && (
<Modal
title="添加接口"
visible={this.state.visible}
onCancel={() => this.setState({ visible: false })}
footer={null}
className="addcatmodal"
>
<AddInterfaceForm
catid={this.state.catid}
catdata={cat}
onCancel={() => this.setState({ visible: false })}
onSubmit={this.handleAddInterface}
/>
</Modal>
)}
</div>
);
}
}
export default InterfaceList;

View File

@@ -0,0 +1,641 @@
import React, { PureComponent as Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import {
fetchInterfaceListMenu,
fetchInterfaceList,
fetchInterfaceCatList,
fetchInterfaceData,
deleteInterfaceData,
deleteInterfaceCatData,
initInterface
} from '../../../../reducer/modules/interface.js';
import { getProject } from '../../../../reducer/modules/project.js';
import { Input, Icon, Button, Modal, message, Tree, Tooltip } from 'antd';
import AddInterfaceForm from './AddInterfaceForm';
import AddInterfaceCatForm from './AddInterfaceCatForm';
import axios from 'axios';
import { Link, withRouter } from 'react-router-dom';
import produce from 'immer';
import { arrayChangeIndex } from '../../../../common.js';
import './interfaceMenu.scss';
const confirm = Modal.confirm;
const TreeNode = Tree.TreeNode;
const headHeight = 240; // menu顶部到网页顶部部分的高度
@connect(
state => {
return {
list: state.inter.list,
inter: state.inter.curdata,
curProject: state.project.currProject,
expands: []
};
},
{
fetchInterfaceListMenu,
fetchInterfaceData,
deleteInterfaceCatData,
deleteInterfaceData,
initInterface,
getProject,
fetchInterfaceCatList,
fetchInterfaceList
}
)
class InterfaceMenu extends Component {
static propTypes = {
match: PropTypes.object,
inter: PropTypes.object,
projectId: PropTypes.string,
list: PropTypes.array,
fetchInterfaceListMenu: PropTypes.func,
curProject: PropTypes.object,
fetchInterfaceData: PropTypes.func,
addInterfaceData: PropTypes.func,
deleteInterfaceData: PropTypes.func,
initInterface: PropTypes.func,
history: PropTypes.object,
router: PropTypes.object,
getProject: PropTypes.func,
fetchInterfaceCatList: PropTypes.func,
fetchInterfaceList: PropTypes.func
};
/**
* @param {String} key
*/
changeModal = (key, status) => {
//visible add_cat_modal_visible change_cat_modal_visible del_cat_modal_visible
let newState = {};
newState[key] = status;
this.setState(newState);
};
handleCancel = () => {
this.setState({
visible: false
});
};
constructor(props) {
super(props);
this.state = {
curKey: null,
visible: false,
delIcon: null,
curCatid: null,
add_cat_modal_visible: false,
change_cat_modal_visible: false,
del_cat_modal_visible: false,
curCatdata: {},
expands: null,
list: []
};
}
handleRequest() {
this.props.initInterface();
this.getList();
}
async getList() {
let r = await this.props.fetchInterfaceListMenu(this.props.projectId);
this.setState({
list: r.payload.data.data
});
}
UNSAFE_componentWillMount() {
this.handleRequest();
}
UNSAFE_componentWillReceiveProps(nextProps) {
if (this.props.list !== nextProps.list) {
// console.log('next', nextProps.list)
this.setState({
list: nextProps.list
});
}
}
onSelect = selectedKeys => {
const { history, match } = this.props;
let curkey = selectedKeys[0];
if (!curkey || !selectedKeys) {
return false;
}
let basepath = '/project/' + match.params.id + '/interface/api';
if (curkey === 'root') {
history.push(basepath);
} else {
history.push(basepath + '/' + curkey);
}
this.setState({
expands: null
});
};
changeExpands = () => {
this.setState({
expands: null
});
};
handleAddInterface = (data, cb) => {
data.project_id = this.props.projectId;
axios.post('/api/interface/add', data).then(res => {
if (res.data.errcode !== 0) {
return message.error(res.data.errmsg);
}
message.success('接口添加成功');
let interfaceId = res.data.data._id;
this.props.history.push('/project/' + this.props.projectId + '/interface/api/' + interfaceId);
this.getList();
this.setState({
visible: false
});
if (cb) {
cb();
}
});
};
handleAddInterfaceCat = data => {
data.project_id = this.props.projectId;
axios.post('/api/interface/add_cat', data).then(res => {
if (res.data.errcode !== 0) {
return message.error(res.data.errmsg);
}
message.success('接口分类添加成功');
this.getList();
this.props.getProject(data.project_id);
this.setState({
add_cat_modal_visible: false
});
});
};
handleChangeInterfaceCat = data => {
data.project_id = this.props.projectId;
let params = {
catid: this.state.curCatdata._id,
name: data.name,
desc: data.desc
};
axios.post('/api/interface/up_cat', params).then(res => {
if (res.data.errcode !== 0) {
return message.error(res.data.errmsg);
}
message.success('接口分类更新成功');
this.getList();
this.props.getProject(data.project_id);
this.setState({
change_cat_modal_visible: false
});
});
};
showConfirm = data => {
let that = this;
let id = data._id;
let catid = data.catid;
const ref = confirm({
title: '您确认删除此接口????',
content: '温馨提示:接口删除后,无法恢复',
okText: '确认',
cancelText: '取消',
async onOk() {
await that.props.deleteInterfaceData(id, that.props.projectId);
await that.getList();
await that.props.fetchInterfaceCatList({ catid });
ref.destroy();
that.props.history.push(
'/project/' + that.props.match.params.id + '/interface/api/cat_' + catid
);
},
onCancel() {
ref.destroy();
}
});
};
showDelCatConfirm = catid => {
let that = this;
const ref = confirm({
title: '确定删除此接口分类吗?',
content: '温馨提示:该操作会删除该分类下所有接口,接口删除后无法恢复',
okText: '确认',
cancelText: '取消',
async onOk() {
await that.props.deleteInterfaceCatData(catid, that.props.projectId);
await that.getList();
// await that.props.getProject(that.props.projectId)
await that.props.fetchInterfaceList({ project_id: that.props.projectId });
that.props.history.push('/project/' + that.props.match.params.id + '/interface/api');
ref.destroy();
},
onCancel() {}
});
};
copyInterface = async id => {
let interfaceData = await this.props.fetchInterfaceData(id);
// let data = JSON.parse(JSON.stringify(interfaceData.payload.data.data));
// data.title = data.title + '_copy';
// data.path = data.path + '_' + Date.now();
let data = interfaceData.payload.data.data;
let newData = produce(data, draftData => {
draftData.title = draftData.title + '_copy';
draftData.path = draftData.path + '_' + Date.now();
});
axios.post('/api/interface/add', newData).then(async res => {
if (res.data.errcode !== 0) {
return message.error(res.data.errmsg);
}
message.success('接口添加成功');
let interfaceId = res.data.data._id;
await this.getList();
this.props.history.push('/project/' + this.props.projectId + '/interface/api/' + interfaceId);
this.setState({
visible: false
});
});
};
enterItem = id => {
this.setState({ delIcon: id });
};
leaveItem = () => {
this.setState({ delIcon: null });
};
onFilter = e => {
this.setState({
filter: e.target.value,
list: JSON.parse(JSON.stringify(this.props.list))
});
};
onExpand = e => {
this.setState({
expands: e
});
};
onDrop = async e => {
const dropCatIndex = e.node.props.pos.split('-')[1] - 1;
const dragCatIndex = e.dragNode.props.pos.split('-')[1] - 1;
if (dropCatIndex < 0 || dragCatIndex < 0) {
return;
}
const { list } = this.props;
const dropCatId = this.props.list[dropCatIndex]._id;
const id = e.dragNode.props.eventKey;
const dragCatId = this.props.list[dragCatIndex]._id;
const dropPos = e.node.props.pos.split('-');
const dropIndex = Number(dropPos[dropPos.length - 1]);
const dragPos = e.dragNode.props.pos.split('-');
const dragIndex = Number(dragPos[dragPos.length - 1]);
if (id.indexOf('cat') === -1) {
if (dropCatId === dragCatId) {
// 同一个分类下的接口交换顺序
let colList = list[dropCatIndex].list;
let changes = arrayChangeIndex(colList, dragIndex, dropIndex);
axios.post('/api/interface/up_index', changes).then();
} else {
await axios.post('/api/interface/up', { id, catid: dropCatId });
}
const { projectId, router } = this.props;
this.props.fetchInterfaceListMenu(projectId);
this.props.fetchInterfaceList({ project_id: projectId });
if (router && isNaN(router.params.actionId)) {
// 更新分类list下的数据
let catid = router.params.actionId.substr(4);
this.props.fetchInterfaceCatList({ catid });
}
} else {
// 分类之间拖动
let changes = arrayChangeIndex(list, dragIndex - 1, dropIndex - 1);
axios.post('/api/interface/up_cat_index', changes).then();
this.props.fetchInterfaceListMenu(this.props.projectId);
}
};
// 数据过滤
filterList = list => {
let that = this;
let arr = [];
let menuList = produce(list, draftList => {
draftList.filter(item => {
let interfaceFilter = false;
// arr = [];
if (item.name.indexOf(that.state.filter) === -1) {
item.list = item.list.filter(inter => {
if (
inter.title.indexOf(that.state.filter) === -1 &&
inter.path.indexOf(that.state.filter) === -1
) {
return false;
}
//arr.push('cat_' + inter.catid)
interfaceFilter = true;
return true;
});
arr.push('cat_' + item._id);
return interfaceFilter === true;
}
arr.push('cat_' + item._id);
return true;
});
});
return { menuList, arr };
};
render() {
const matchParams = this.props.match.params;
// let menuList = this.state.list;
const searchBox = (
<div className="interface-filter">
<Input onChange={this.onFilter} value={this.state.filter} placeholder="搜索接口" />
<Button
type="primary"
onClick={() => this.changeModal('add_cat_modal_visible', true)}
className="btn-filter"
>
添加分类
</Button>
{this.state.visible ? (
<Modal
title="添加接口"
visible={this.state.visible}
onCancel={() => this.changeModal('visible', false)}
footer={null}
className="addcatmodal"
>
<AddInterfaceForm
catdata={this.props.curProject.cat}
catid={this.state.curCatid}
onCancel={() => this.changeModal('visible', false)}
onSubmit={this.handleAddInterface}
/>
</Modal>
) : (
''
)}
{this.state.add_cat_modal_visible ? (
<Modal
title="添加分类"
visible={this.state.add_cat_modal_visible}
onCancel={() => this.changeModal('add_cat_modal_visible', false)}
footer={null}
className="addcatmodal"
>
<AddInterfaceCatForm
onCancel={() => this.changeModal('add_cat_modal_visible', false)}
onSubmit={this.handleAddInterfaceCat}
/>
</Modal>
) : (
''
)}
{this.state.change_cat_modal_visible ? (
<Modal
title="修改分类"
visible={this.state.change_cat_modal_visible}
onCancel={() => this.changeModal('change_cat_modal_visible', false)}
footer={null}
className="addcatmodal"
>
<AddInterfaceCatForm
catdata={this.state.curCatdata}
onCancel={() => this.changeModal('change_cat_modal_visible', false)}
onSubmit={this.handleChangeInterfaceCat}
/>
</Modal>
) : (
''
)}
</div>
);
const defaultExpandedKeys = () => {
const { router, inter, list } = this.props,
rNull = { expands: [], selects: [] };
if (list.length === 0) {
return rNull;
}
if (router) {
if (!isNaN(router.params.actionId)) {
if (!inter || !inter._id) {
return rNull;
}
return {
expands: this.state.expands ? this.state.expands : ['cat_' + inter.catid],
selects: [inter._id + '']
};
} else {
let catid = router.params.actionId.substr(4);
return {
expands: this.state.expands ? this.state.expands : ['cat_' + catid],
selects: ['cat_' + catid]
};
}
} else {
return {
expands: this.state.expands ? this.state.expands : ['cat_' + list[0]._id],
selects: ['root']
};
}
};
const itemInterfaceCreate = item => {
return (
<TreeNode
title={
<div
className="container-title"
onMouseEnter={() => this.enterItem(item._id)}
onMouseLeave={this.leaveItem}
>
<Tooltip title= {item.title}>
<Link
className="interface-item"
onClick={e => e.stopPropagation()}
to={'/project/' + matchParams.id + '/interface/api/' + item._id}
>
{item.title}
</Link>
</Tooltip>
<div className="btns">
<Tooltip title="删除接口">
<Icon
type="delete"
className="interface-delete-icon"
onClick={e => {
e.stopPropagation();
this.showConfirm(item);
}}
style={{ display: this.state.delIcon == item._id ? 'block' : 'none' }}
/>
</Tooltip>
<Tooltip title="复制接口">
<Icon
type="copy"
className="interface-delete-icon"
onClick={e => {
e.stopPropagation();
this.copyInterface(item._id);
}}
style={{ display: this.state.delIcon == item._id ? 'block' : 'none' }}
/>
</Tooltip>
</div>
{/*<Dropdown overlay={menu(item)} trigger={['click']} onClick={e => e.stopPropagation()}>
<Icon type='ellipsis' className="interface-delete-icon" style={{ opacity: this.state.delIcon == item._id ? 1 : 0 }}/>
</Dropdown>*/}
</div>
}
key={'' + item._id}
/>
);
};
let currentKes = defaultExpandedKeys();
let menuList;
if (this.state.filter) {
let res = this.filterList(this.state.list);
menuList = res.menuList;
currentKes.expands = res.arr;
} else {
menuList = this.state.list;
}
return (
<div>
{searchBox}
{menuList.length > 0 ? (
<div
className="tree-wrappper"
style={{ maxHeight: parseInt(document.body.clientHeight) - headHeight + 'px' }}
>
<Tree
className="interface-list"
defaultExpandedKeys={currentKes.expands}
defaultSelectedKeys={currentKes.selects}
expandedKeys={currentKes.expands}
selectedKeys={currentKes.selects}
onSelect={this.onSelect}
onExpand={this.onExpand}
draggable
onDrop={this.onDrop}
>
<TreeNode
className="item-all-interface"
title={
<Link
onClick={e => {
e.stopPropagation();
this.changeExpands();
}}
to={'/project/' + matchParams.id + '/interface/api'}
>
<Icon type="folder" style={{ marginRight: 5 }} />
全部接口
</Link>
}
key="root"
/>
{menuList.map(item => {
return (
<TreeNode
title={
<div
className="container-title"
onMouseEnter={() => this.enterItem(item._id)}
onMouseLeave={this.leaveItem}
>
<Link
className="interface-item"
onClick={e => {
e.stopPropagation();
this.changeExpands();
}}
to={'/project/' + matchParams.id + '/interface/api/cat_' + item._id}
>
<Icon type="folder-open" style={{ marginRight: 5 }} />
{item.name}
</Link>
<div className="btns">
<Tooltip title="删除分类">
<Icon
type="delete"
className="interface-delete-icon"
onClick={e => {
e.stopPropagation();
this.showDelCatConfirm(item._id);
}}
style={{ display: this.state.delIcon == item._id ? 'block' : 'none' }}
/>
</Tooltip>
<Tooltip title="修改分类">
<Icon
type="edit"
className="interface-delete-icon"
style={{ display: this.state.delIcon == item._id ? 'block' : 'none' }}
onClick={e => {
e.stopPropagation();
this.changeModal('change_cat_modal_visible', true);
this.setState({
curCatdata: item
});
}}
/>
</Tooltip>
<Tooltip title="添加接口">
<Icon
type="plus"
className="interface-delete-icon"
style={{ display: this.state.delIcon == item._id ? 'block' : 'none' }}
onClick={e => {
e.stopPropagation();
this.changeModal('visible', true);
this.setState({
curCatid: item._id
});
}}
/>
</Tooltip>
</div>
{/*<Dropdown overlay={menu(item)} trigger={['click']} onClick={e => e.stopPropagation()}>
<Icon type='ellipsis' className="interface-delete-icon" />
</Dropdown>*/}
</div>
}
key={'cat_' + item._id}
className={`interface-item-nav ${item.list.length ? '' : 'cat_switch_hidden'}`}
>
{item.list.map(itemInterfaceCreate)}
</TreeNode>
);
})}
</Tree>
</div>
) : null}
</div>
);
}
}
export default withRouter(InterfaceMenu);

View File

@@ -0,0 +1,149 @@
import React, { PureComponent as Component } from 'react';
import { connect } from 'react-redux';
import { Modal, Collapse, Row, Col, Input, message, Button, Icon } from 'antd';
import PropTypes from 'prop-types';
import axios from 'axios';
import { withRouter } from 'react-router';
import { fetchInterfaceColList } from '../../../../../reducer/modules/interfaceCol';
const { TextArea } = Input;
const Panel = Collapse.Panel;
@connect(
state => ({
interfaceColList: state.interfaceCol.interfaceColList
}),
{
fetchInterfaceColList
}
)
@withRouter
export default class AddColModal extends Component {
static propTypes = {
visible: PropTypes.bool,
interfaceColList: PropTypes.array,
fetchInterfaceColList: PropTypes.func,
match: PropTypes.object,
onOk: PropTypes.func,
onCancel: PropTypes.func,
caseName: PropTypes.string
};
state = {
visible: false,
addColName: '',
addColDesc: '',
id: 0,
caseName: ''
};
constructor(props) {
super(props);
}
UNSAFE_componentWillMount() {
this.props.fetchInterfaceColList(this.props.match.params.id);
this.setState({ caseName: this.props.caseName });
}
UNSAFE_componentWillReceiveProps(nextProps) {
this.setState({ id: nextProps.interfaceColList[0]._id });
this.setState({ caseName: nextProps.caseName });
}
addCol = async () => {
const { addColName: name, addColDesc: desc } = this.state;
const project_id = this.props.match.params.id;
const res = await axios.post('/api/col/add_col', { name, desc, project_id });
if (!res.data.errcode) {
message.success('添加集合成功');
await this.props.fetchInterfaceColList(project_id);
this.setState({ id: res.data.data._id });
} else {
message.error(res.data.errmsg);
}
};
select = id => {
this.setState({ id });
};
render() {
const { interfaceColList = [] } = this.props;
const { id } = this.state;
return (
<Modal
className="add-col-modal"
title="添加到集合"
visible={this.props.visible}
onOk={() => this.props.onOk(id, this.state.caseName)}
onCancel={this.props.onCancel}
>
<Row gutter={6} className="modal-input">
<Col span="5">
<div className="label">接口用例名</div>
</Col>
<Col span="15">
<Input
placeholder="请输入接口用例名称"
value={this.state.caseName}
onChange={e => this.setState({ caseName: e.target.value })}
/>
</Col>
</Row>
<p>请选择添加到的集合</p>
<ul className="col-list">
{interfaceColList.length ? (
interfaceColList.map(col => (
<li
key={col._id}
className={`col-item ${col._id === id ? 'selected' : ''}`}
onClick={() => this.select(col._id)}
>
<Icon type="folder-open" style={{ marginRight: 6 }} />
{col.name}
</li>
))
) : (
<span>暂无集合请添加</span>
)}
</ul>
<Collapse>
<Panel header="添加新集合">
<Row gutter={6} className="modal-input">
<Col span="5">
<div className="label">集合名</div>
</Col>
<Col span="15">
<Input
placeholder="请输入集合名称"
value={this.state.addColName}
onChange={e => this.setState({ addColName: e.target.value })}
/>
</Col>
</Row>
<Row gutter={6} className="modal-input">
<Col span="5">
<div className="label">简介</div>
</Col>
<Col span="15">
<TextArea
rows={3}
placeholder="请输入集合描述"
value={this.state.addColDesc}
onChange={e => this.setState({ addColDesc: e.target.value })}
/>
</Col>
</Row>
<Row type="flex" justify="end">
<Button style={{ float: 'right' }} type="primary" onClick={this.addCol}>
</Button>
</Row>
</Panel>
</Collapse>
</Modal>
);
}
}

View File

@@ -0,0 +1,113 @@
import React, { PureComponent as Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import axios from 'axios';
import { message } from 'antd';
import { Postman } from '../../../../../components';
import AddColModal from './AddColModal';
// import {
// } from '../../../reducer/modules/group.js'
import './Run.scss';
@connect(state => ({
currInterface: state.inter.curdata,
currProject: state.project.currProject,
curUid: state.user.uid
}))
@withRouter
export default class Run extends Component {
static propTypes = {
currProject: PropTypes.object,
currInterface: PropTypes.object,
match: PropTypes.object,
curUid: PropTypes.number
};
state = {};
constructor(props) {
super(props);
}
UNSAFE_componentWillMount() {}
UNSAFE_componentWillReceiveProps() {}
savePostmanRef = postman => {
this.postman = postman;
};
saveCase = async (colId, caseName) => {
const project_id = this.props.match.params.id;
const interface_id = this.props.currInterface._id;
const {
case_env,
req_params,
req_query,
req_headers,
req_body_type,
req_body_form,
req_body_other
} = this.postman.state;
let params = {
interface_id,
casename: caseName,
col_id: colId,
project_id,
case_env,
req_params,
req_query,
req_headers,
req_body_type,
req_body_form,
req_body_other
};
if (params.test_res_body && typeof params.test_res_body === 'object') {
params.test_res_body = JSON.stringify(params.test_res_body, null, ' ');
}
const res = await axios.post('/api/col/add_case', params);
if (res.data.errcode) {
message.error(res.data.errmsg);
} else {
message.success('添加成功');
this.setState({ saveCaseModalVisible: false });
}
};
render() {
const { currInterface, currProject } = this.props;
const data = Object.assign({}, currInterface, {
env: currProject.env,
pre_script: currProject.pre_script,
after_script: currProject.after_script
});
data.path = currProject.basepath + currInterface.path;
return (
<div>
<Postman
data={data}
id={currProject._id}
type="inter"
saveTip="保存到集合"
save={() => this.setState({ saveCaseModalVisible: true })}
ref={this.savePostmanRef}
interfaceId={currInterface._id}
projectId={currInterface.project_id}
curUid={this.props.curUid}
/>
<AddColModal
visible={this.state.saveCaseModalVisible}
caseName={currInterface.title}
onCancel={() => this.setState({ saveCaseModalVisible: false })}
onOk={this.saveCase}
/>
</div>
);
}
}

View File

@@ -0,0 +1,19 @@
.add-col-modal {
.col-list {
height: 200px;
overflow: auto;
margin: 7px 0 16px 0;
background: #eaeaea;
.col-item {
padding: 7px 10px 7px 10px;
}
.col-item:hover {
background: #fa0;
}
.col-item.selected {
background: #2395f1;
color: rgba(255, 255, 255, 1);
}
}
}

View File

@@ -0,0 +1,630 @@
import './View.scss'
import React, { PureComponent as Component } from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { Table, Icon, Row, Col, Tooltip, message } from 'antd'
import { Link } from 'react-router-dom'
import AceEditor from 'client/components/AceEditor/AceEditor'
import { formatTime, safeArray } from '../../../../common.js'
import ErrMsg from '../../../../components/ErrMsg/ErrMsg.js'
import variable from '../../../../constants/variable'
import constants from '../../../../constants/variable.js'
import copy from 'copy-to-clipboard'
import SchemaTable from '../../../../components/SchemaTable/SchemaTable.js'
const HTTP_METHOD = constants.HTTP_METHOD
@connect(state => {
return {
curData: state.inter.curdata,
custom_field: state.group.field,
currProject: state.project.currProject
}
})
class View extends Component {
constructor(props) {
super(props)
this.state = {
init: true,
enter: false
}
}
static propTypes = {
curData: PropTypes.object,
currProject: PropTypes.object,
custom_field: PropTypes.object
}
req_body_form(req_body_type, req_body_form) {
if (req_body_type === 'form') {
const columns = [
{
title: '参数名称',
dataIndex: 'name',
key: 'name',
width: 140
},
{
title: '参数类型',
dataIndex: 'type',
key: 'type',
width: 100,
render: text => {
text = text || ''
return text.toLowerCase() === 'text' ? (
<span>
<i className='query-icon text'>T</i>
</span>
) : (
<span>
<Icon type='file' className='query-icon' />
文件
</span>
)
}
},
{
title: '是否必须',
dataIndex: 'required',
key: 'required',
width: 100
},
{
title: '示例',
dataIndex: 'example',
key: 'example',
width: 80,
render(_, item) {
return <p style={{ whiteSpace: 'pre-wrap' }}>{item.example}</p>
}
},
{
title: '备注',
dataIndex: 'value',
key: 'value',
render(_, item) {
return <p style={{ whiteSpace: 'pre-wrap' }}>{item.value}</p>
}
}
]
const dataSource = []
if (req_body_form && req_body_form.length) {
req_body_form.map((item, i) => {
dataSource.push({
key: i,
name: item.name,
value: item.desc,
example: item.example,
required: item.required == 0 ? '否' : '是',
type: item.type
})
})
}
return (
<div
style={{ display: dataSource.length ? '' : 'none' }}
className='colBody'>
<Table
bordered
size='small'
pagination={false}
columns={columns}
dataSource={dataSource}
/>
</div>
)
}
}
res_body(res_body_type, res_body, res_body_is_json_schema) {
if (res_body_type === 'json') {
if (res_body_is_json_schema) {
return <SchemaTable dataSource={res_body} />
} else {
return (
<div className='colBody'>
{/* <div id="vres_body_json" style={{ minHeight: h * 16 + 100 }}></div> */}
<AceEditor
data={res_body}
readOnly={true}
style={{ minHeight: 600 }}
/>
</div>
)
}
} else if (res_body_type === 'raw') {
return (
<div className='colBody'>
<AceEditor
data={res_body}
readOnly={true}
mode='text'
style={{ minHeight: 300 }}
/>
</div>
)
}
}
req_body(req_body_type, req_body_other, req_body_is_json_schema) {
if (req_body_other) {
if (req_body_is_json_schema && req_body_type === 'json') {
return <SchemaTable dataSource={req_body_other} />
} else {
return (
<div className='colBody'>
<AceEditor
data={req_body_other}
readOnly={true}
style={{ minHeight: 300 }}
mode={req_body_type === 'json' ? 'javascript' : 'text'}
/>
</div>
)
}
}
}
req_query(query) {
const columns = [
{
title: '参数名称',
dataIndex: 'name',
width: 140,
key: 'name'
},
{
title: '类型',
dataIndex: 'type',
width: 140,
key: 'type'
},
{
title: '是否必须',
width: 100,
dataIndex: 'required',
key: 'required'
},
{
title: '示例',
dataIndex: 'example',
key: 'example',
width: 80,
render(_, item) {
return <p style={{ whiteSpace: 'pre-wrap' }}>{item.example}</p>
}
},
{
title: '备注',
dataIndex: 'value',
key: 'value',
render(_, item) {
return <p style={{ whiteSpace: 'pre-wrap' }}>{item.value}</p>
}
}
]
const dataSource = []
if (query && query.length) {
query.map((item, i) => {
dataSource.push({
key: i,
name: item.name,
value: item.desc,
example: item.example,
required: item.required == 0 ? '否' : '是',
type: item.type
})
})
}
return (
<Table
bordered
size='small'
pagination={false}
columns={columns}
dataSource={dataSource}
/>
)
}
countEnter(str) {
let i = 0
let c = 0
if (!str || !str.indexOf) {
return 0
}
while (str.indexOf('\n', i) > -1) {
i = str.indexOf('\n', i) + 2
c++
}
return c
}
componentDidMount() {
if (!this.props.curData.title && this.state.init) {
this.setState({ init: false })
}
}
enterItem = () => {
this.setState({
enter: true
})
}
leaveItem = () => {
this.setState({
enter: false
})
}
copyUrl = url => {
copy(url)
message.success('已经成功复制到剪切板')
}
flagMsg = (mock, strice) => {
if (mock && strice) {
return <span>( 全局mock & 严格模式 )</span>
} else if (!mock && strice) {
return <span>( 严格模式 )</span>
} else if (mock && !strice) {
return <span>( 全局mock )</span>
} else {
return
}
}
render() {
const dataSource = []
if (
this.props.curData.req_headers &&
this.props.curData.req_headers.length
) {
this.props.curData.req_headers.map((item, i) => {
dataSource.push({
key: i,
name: item.name,
required: item.required == 0 ? '否' : '是',
value: item.value,
example: item.example,
desc: item.desc
})
})
}
const req_dataSource = []
if (this.props.curData.req_params && this.props.curData.req_params.length) {
this.props.curData.req_params.map((item, i) => {
req_dataSource.push({
key: i,
name: item.name,
desc: item.desc,
example: item.example,
type: item.type
})
})
}
const req_params_columns = [
{
title: '参数名称',
dataIndex: 'name',
key: 'name',
width: 140
},
{
title: '类型',
dataIndex: 'type',
key: 'type',
width: 140
},
{
title: '示例',
dataIndex: 'example',
key: 'example',
width: 80,
render(_, item) {
return <p style={{ whiteSpace: 'pre-wrap' }}>{item.example}</p>
}
},
{
title: '备注',
dataIndex: 'desc',
key: 'desc',
render(_, item) {
return <p style={{ whiteSpace: 'pre-wrap' }}>{item.desc}</p>
}
}
]
const columns = [
{
title: '参数名称',
dataIndex: 'name',
key: 'name',
width: '200px'
},
{
title: '参数值',
dataIndex: 'value',
key: 'value',
width: '300px'
},
{
title: '是否必须',
dataIndex: 'required',
key: 'required',
width: '100px'
},
{
title: '示例',
dataIndex: 'example',
key: 'example',
width: '80px',
render(_, item) {
return <p style={{ whiteSpace: 'pre-wrap' }}>{item.example}</p>
}
},
{
title: '备注',
dataIndex: 'desc',
key: 'desc',
render(_, item) {
return <p style={{ whiteSpace: 'pre-wrap' }}>{item.desc}</p>
}
}
]
let status = {
undone: '未完成',
done: '已完成'
}
let bodyShow =
this.props.curData.req_body_other ||
(this.props.curData.req_body_type === 'form' &&
this.props.curData.req_body_form &&
this.props.curData.req_body_form.length)
let requestShow =
(dataSource && dataSource.length) ||
(req_dataSource && req_dataSource.length) ||
(this.props.curData.req_query && this.props.curData.req_query.length) ||
bodyShow
let methodColor =
variable.METHOD_COLOR[
this.props.curData.method
? this.props.curData.method.toLowerCase()
: 'get'
]
// statusColor = statusColor[this.props.curData.status?this.props.curData.status.toLowerCase():"undone"];
// const aceEditor = <div style={{ display: this.props.curData.req_body_other && (this.props.curData.req_body_type !== "form") ? "block" : "none" }} className="colBody">
// <AceEditor data={this.props.curData.req_body_other} readOnly={true} style={{ minHeight: 300 }} mode={this.props.curData.req_body_type === 'json' ? 'javascript' : 'text'} />
// </div>
if (!methodColor) {
methodColor = 'get'
}
const { tag, up_time, title, uid, username } = this.props.curData
let res = (
<div className='caseContainer'>
<h2 className='interface-title' style={{ marginTop: 0 }}>
基本信息
</h2>
<div className='panel-view'>
<Row className='row'>
<Col span={4} className='colKey'>
接口名称
</Col>
<Col span={8} className='colName'>
{title}
</Col>
<Col span={4} className="colKey">
&ensp;&ensp;
</Col>
<Col span={8} className='colValue'>
<Link className='user-name' to={'/user/profile/' + uid}>
<img src={'/api/user/avatar?uid=' + uid} className='user-img' />
{username}
</Link>
</Col>
</Row>
<Row className="row">
<Col span={4} className="colKey">
&emsp;&emsp;
</Col>
<Col span={8} className={'tag-status ' + this.props.curData.status}>
{status[this.props.curData.status]}
</Col>
<Col span={4} className='colKey'>
更新时间
</Col>
<Col span={8}>{formatTime(up_time)}</Col>
</Row>
{safeArray(tag) && safeArray(tag).length > 0 && (
<Row className='row remark'>
<Col span={4} className='colKey'>
Tag
</Col>
<Col span={18} className='colValue'>
{tag.join(' , ')}
</Col>
</Row>
)}
<Row className='row'>
<Col span={4} className='colKey'>
接口路径
</Col>
<Col
span={18}
className='colValue'
onMouseEnter={this.enterItem}
onMouseLeave={this.leaveItem}>
<span
style={{
color: methodColor.color,
backgroundColor: methodColor.bac
}}
className='colValue tag-method'>
{this.props.curData.method}
</span>
<span className='colValue'>
{this.props.currProject.basepath}
{this.props.curData.path}
</span>
<Tooltip title='复制路径'>
<Icon
type='copy'
className='interface-url-icon'
onClick={() =>
this.copyUrl(
this.props.currProject.basepath + this.props.curData.path,
)
}
style={{
display: this.state.enter ? 'inline-block' : 'none'
}}
/>
</Tooltip>
</Col>
</Row>
<Row className='row'>
<Col span={4} className='colKey'>
Mock地址
</Col>
<Col span={18} className='colValue'>
{this.flagMsg(
this.props.currProject.is_mock_open,
this.props.currProject.strice,
)}
<span
className='href'
onClick={() =>
window.open(
location.protocol +
'//' +
location.hostname +
(location.port !== '' ? ':' + location.port : '') +
`/mock/${this.props.currProject._id}${this.props.currProject.basepath}${this.props.curData.path}`,
'_blank',
)
}>
{location.protocol +
'//' +
location.hostname +
(location.port !== '' ? ':' + location.port : '') +
`/mock/${this.props.currProject._id}${this.props.currProject.basepath}${this.props.curData.path}`}
</span>
</Col>
</Row>
{this.props.curData.custom_field_value &&
this.props.custom_field.enable && (
<Row className='row remark'>
<Col span={4} className='colKey'>
{this.props.custom_field.name}
</Col>
<Col span={18} className='colValue'>
{this.props.curData.custom_field_value}
</Col>
</Row>
)}
</div>
{this.props.curData.desc && <h2 className='interface-title'>备注</h2>}
{this.props.curData.desc && (
<div
className='tui-editor-contents'
style={{ margin: '0px', padding: '0px 20px', float: 'none' }}
dangerouslySetInnerHTML={{ __html: this.props.curData.desc }}
/>
)}
<h2
className='interface-title'
style={{ display: requestShow ? '' : 'none' }}>
请求参数
</h2>
{req_dataSource.length ? (
<div className='colHeader'>
<h3 className='col-title'>路径参数</h3>
<Table
bordered
size='small'
pagination={false}
columns={req_params_columns}
dataSource={req_dataSource}
/>
</div>
) : (
''
)}
{dataSource.length ? (
<div className='colHeader'>
<h3 className='col-title'>Headers</h3>
<Table
bordered
size='small'
pagination={false}
columns={columns}
dataSource={dataSource}
/>
</div>
) : (
''
)}
{this.props.curData.req_query && this.props.curData.req_query.length ? (
<div className='colQuery'>
<h3 className='col-title'>Query</h3>
{this.req_query(this.props.curData.req_query)}
</div>
) : (
''
)}
<div
style={{
display:
this.props.curData.method &&
HTTP_METHOD[this.props.curData.method.toUpperCase()].request_body
? ''
: 'none'
}}>
<h3 style={{ display: bodyShow ? '' : 'none' }} className='col-title'>
Body:
</h3>
{this.props.curData.req_body_type === 'form'
? this.req_body_form(
this.props.curData.req_body_type,
this.props.curData.req_body_form,
)
: this.req_body(
this.props.curData.req_body_type,
this.props.curData.req_body_other,
this.props.curData.req_body_is_json_schema,
)}
</div>
<h2 className='interface-title'>返回数据</h2>
{this.res_body(
this.props.curData.res_body_type,
this.props.curData.res_body,
this.props.curData.res_body_is_json_schema,
)}
</div>
)
if (!this.props.curData.title) {
if (this.state.init) {
res = <div />
} else {
res = <ErrMsg type='noData' />
}
}
return res
}
}
export default View

View File

@@ -0,0 +1,135 @@
.caseContainer{
padding: 24px;
font-size: 13px;
// display: flex;
overflow: hidden;
>div{
margin: 8px 0px;
// background-color: #ececec;
padding: 16px;
width: 100%;
box-sizing: border-box;
float: left;
.colKey{
font-weight: bold;
text-align: left;
width: 100px;
padding-left: 10px;
}
.colName{
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.col-title{margin-bottom: 5px}
.colValue.href {
color: #2395f1;
cursor: pointer;
}
.ace_print-margin{
display: none;
}
.interface-url-icon{
padding-left: 8px;
}
.colBody{
.query-icon {
display: inline-block;
width: .13rem;
margin-right: 4px;
position: relative;
&.text:after {
content: 'T';
display: block;
position: absolute;
right: 2px;
bottom: -2px;
transform: scale(.7);
}
}
}
.colDesc{
margin-bottom: 0px;
padding-bottom: 0px;
}
.ant-table-thead {
th{
color: #6d6c6c;
font-weight: normal;
}
tr{
// background-color: black;
}
}
.ant-table-thead>tr>th{
background: #f7f7f7;
}
.colMethod{
.colValue{
display: inline-block;
border-radius: 4px;
color: #00a854;
background: #cfefdf;
border-color: #cfefdf;
height: 23px;
line-height: 23px;
text-align: center;
font-size: 10px;
margin-right: 7px;
padding: 0 5px;
}
}
.colstatus{
.colValue{
height: 23px;
padding: 0 5px;
line-height: 23px;
display: inline-block;
border-radius: 4px;
color: white;
}
}
.user-img {
width: .3rem;
height: .3rem;
border-radius: 50%;
border: 2px solid #eee;
vertical-align: middle;
margin-right: 4px;
}
.tag-method {
padding: 4px 6px;
margin-right: 8px;
border-radius: 4px;
vertical-align: middle;
}
}
.colHalf {
width: 50%;
float: left;
margin-bottom: .16rem;
.colKey{
padding-bottom: 0px;
text-align: right;
}
}
.panel-view {
.row {
margin-bottom: .16rem;
line-height: 36px;
}
.user-img {
position: absolute;
left: 0;
top: 50%;
transform: translate(0, -50%);
}
.user-name {
padding-left: .38rem;
}
}

View File

@@ -0,0 +1,617 @@
.tui-editor-contents h1 {
font-size: 45px;
line-height: 1.5;
border-bottom: 3px double #999;
margin: 52px 0 15px 0;
padding-bottom: 7px;
color: #000;
}
.tui-editor-contents h2 {
font-size: 34px;
line-height: 1.5;
border-bottom: 1px solid #dbdbdb;
margin: 30px 0 13px 0;
padding-bottom: 7px;
color: #333;
}
.tui-editor-contents h3,
.tui-editor-contents h4 {
font-size: 24px;
line-height: 1.5;
margin: 20px 0 2px;
color: #333;
}
.tui-editor-contents h5,
.tui-editor-contents h6 {
font-size: 16px;
line-height: 1.5;
margin: 10px 0 -4px;
color: #333;
}
/*
github.com style (c) Vasily Polovnyov <vast@whiteants.net>
*/
.hljs {
display: block;
overflow-x: auto;
padding: 0.5em;
color: #333;
background: #f8f8f8;
}
.hljs-comment,
.hljs-quote {
color: #998;
font-style: italic;
}
.hljs-keyword,
.hljs-selector-tag,
.hljs-subst {
color: #333;
font-weight: bold;
}
.hljs-number,
.hljs-literal,
.hljs-variable,
.hljs-template-variable,
.hljs-tag .hljs-attr {
color: #008080;
}
.hljs-string,
.hljs-doctag {
color: #d14;
}
.hljs-title,
.hljs-section,
.hljs-selector-id {
color: #900;
font-weight: bold;
}
.hljs-subst {
font-weight: normal;
}
.hljs-type,
.hljs-class .hljs-title {
color: #458;
font-weight: bold;
}
.hljs-tag,
.hljs-name,
.hljs-attribute {
color: #000080;
font-weight: normal;
}
.hljs-regexp,
.hljs-link {
color: #009926;
}
.hljs-symbol,
.hljs-bullet {
color: #990073;
}
.hljs-built_in,
.hljs-builtin-name {
color: #0086b3;
}
.hljs-meta {
color: #999;
font-weight: bold;
}
.hljs-deletion {
background: #fdd;
}
.hljs-addition {
background: #dfd;
}
.hljs-emphasis {
font-style: italic;
}
.hljs-strong {
font-weight: bold;
}
/* BASICS */
.CodeMirror {
/* Set height, width, borders, and global font properties here */
font-family: monospace;
height: 300px;
color: black;
direction: ltr;
}
/* PADDING */
.CodeMirror-lines {
padding: 4px 0; /* Vertical padding around content */
}
.CodeMirror pre {
padding: 0 4px; /* Horizontal padding of content */
}
.CodeMirror-scrollbar-filler,
.CodeMirror-gutter-filler {
background-color: white; /* The little square between H and V scrollbars */
}
/* GUTTER */
.CodeMirror-gutters {
border-right: 1px solid #ddd;
background-color: #f7f7f7;
white-space: nowrap;
}
.CodeMirror-linenumber {
padding: 0 3px 0 5px;
min-width: 20px;
text-align: right;
color: #999;
white-space: nowrap;
}
.CodeMirror-guttermarker {
color: black;
}
.CodeMirror-guttermarker-subtle {
color: #999;
}
/* CURSOR */
.CodeMirror-cursor {
border-left: 1px solid black;
border-right: none;
width: 0;
}
/* Shown when moving in bi-directional text */
.CodeMirror div.CodeMirror-secondarycursor {
border-left: 1px solid silver;
}
.cm-fat-cursor .CodeMirror-cursor {
width: auto;
border: 0 !important;
background: #7e7;
}
.cm-fat-cursor div.CodeMirror-cursors {
z-index: 1;
}
.cm-fat-cursor-mark {
background-color: rgba(20, 255, 20, 0.5);
-webkit-animation: blink 1.06s steps(1) infinite;
-moz-animation: blink 1.06s steps(1) infinite;
animation: blink 1.06s steps(1) infinite;
}
.cm-animate-fat-cursor {
width: auto;
border: 0;
-webkit-animation: blink 1.06s steps(1) infinite;
-moz-animation: blink 1.06s steps(1) infinite;
animation: blink 1.06s steps(1) infinite;
background-color: #7e7;
}
@-moz-keyframes blink {
0% {
}
50% {
background-color: transparent;
}
100% {
}
}
@-webkit-keyframes blink {
0% {
}
50% {
background-color: transparent;
}
100% {
}
}
@keyframes blink {
0% {
}
50% {
background-color: transparent;
}
100% {
}
}
/* Can style cursor different in overwrite (non-insert) mode */
/* .CodeMirror-overwrite .CodeMirror-cursor {
} */
.cm-tab {
display: inline-block;
text-decoration: inherit;
}
.CodeMirror-rulers {
position: absolute;
left: 0;
right: 0;
top: -50px;
bottom: -20px;
overflow: hidden;
}
.CodeMirror-ruler {
border-left: 1px solid #ccc;
top: 0;
bottom: 0;
position: absolute;
}
/* DEFAULT THEME */
.cm-s-default .cm-header {
color: blue;
}
.cm-s-default .cm-quote {
color: #090;
}
.cm-negative {
color: #d44;
}
.cm-positive {
color: #292;
}
.cm-header,
.cm-strong {
font-weight: bold;
}
.cm-em {
font-style: italic;
}
.cm-link {
text-decoration: underline;
}
.cm-strikethrough {
text-decoration: line-through;
}
.cm-s-default .cm-keyword {
color: #708;
}
.cm-s-default .cm-atom {
color: #219;
}
.cm-s-default .cm-number {
color: #164;
}
.cm-s-default .cm-def {
color: #00f;
}
/* .cm-s-default .cm-variable,
.cm-s-default .cm-punctuation,
.cm-s-default .cm-property,
.cm-s-default .cm-operator {
} */
.cm-s-default .cm-variable-2 {
color: #05a;
}
.cm-s-default .cm-variable-3,
.cm-s-default .cm-type {
color: #085;
}
.cm-s-default .cm-comment {
color: #a50;
}
.cm-s-default .cm-string {
color: #a11;
}
.cm-s-default .cm-string-2 {
color: #f50;
}
.cm-s-default .cm-meta {
color: #555;
}
.cm-s-default .cm-qualifier {
color: #555;
}
.cm-s-default .cm-builtin {
color: #30a;
}
.cm-s-default .cm-bracket {
color: #997;
}
.cm-s-default .cm-tag {
color: #170;
}
.cm-s-default .cm-attribute {
color: #00c;
}
.cm-s-default .cm-hr {
color: #999;
}
.cm-s-default .cm-link {
color: #00c;
}
.cm-s-default .cm-error {
color: #f00;
}
.cm-invalidchar {
color: #f00;
}
.CodeMirror-composing {
border-bottom: 2px solid;
}
/* Default styles for common addons */
div.CodeMirror span.CodeMirror-matchingbracket {
color: #0b0;
}
div.CodeMirror span.CodeMirror-nonmatchingbracket {
color: #a22;
}
.CodeMirror-matchingtag {
background: rgba(255, 150, 0, 0.3);
}
.CodeMirror-activeline-background {
background: #e8f2ff;
}
/* STOP */
/* The rest of this file contains styles related to the mechanics of
the editor. You probably shouldn't touch them. */
.CodeMirror {
position: relative;
overflow: hidden;
background: white;
}
.CodeMirror-scroll {
overflow: scroll !important; /* Things will break if this is overridden */
/* 30px is the magic margin used to hide the element's real scrollbars */
/* See overflow: hidden in .CodeMirror */
margin-bottom: -30px;
margin-right: -30px;
padding-bottom: 30px;
height: 100%;
outline: none; /* Prevent dragging from highlighting the element */
position: relative;
}
.CodeMirror-sizer {
position: relative;
border-right: 30px solid transparent;
}
/* The fake, visible scrollbars. Used to force redraw during scrolling
before actual scrolling happens, thus preventing shaking and
flickering artifacts. */
.CodeMirror-vscrollbar,
.CodeMirror-hscrollbar,
.CodeMirror-scrollbar-filler,
.CodeMirror-gutter-filler {
position: absolute;
z-index: 6;
display: none;
}
.CodeMirror-vscrollbar {
right: 0;
top: 0;
overflow-x: hidden;
overflow-y: scroll;
}
.CodeMirror-hscrollbar {
bottom: 0;
left: 0;
overflow-y: hidden;
overflow-x: scroll;
}
.CodeMirror-scrollbar-filler {
right: 0;
bottom: 0;
}
.CodeMirror-gutter-filler {
left: 0;
bottom: 0;
}
.CodeMirror-gutters {
position: absolute;
left: 0;
top: 0;
min-height: 100%;
z-index: 3;
}
.CodeMirror-gutter {
white-space: normal;
height: 100%;
display: inline-block;
vertical-align: top;
margin-bottom: -30px;
}
.CodeMirror-gutter-wrapper {
position: absolute;
z-index: 4;
background: none !important;
border: none !important;
}
.CodeMirror-gutter-background {
position: absolute;
top: 0;
bottom: 0;
z-index: 4;
}
.CodeMirror-gutter-elt {
position: absolute;
cursor: default;
z-index: 4;
}
.CodeMirror-gutter-wrapper ::selection {
background-color: transparent;
}
.CodeMirror-gutter-wrapper ::-moz-selection {
background-color: transparent;
}
.CodeMirror-lines {
cursor: text;
min-height: 1px; /* prevents collapsing before first draw */
}
.CodeMirror pre {
/* Reset some styles that the rest of the page might have set */
-moz-border-radius: 0;
-webkit-border-radius: 0;
border-radius: 0;
border-width: 0;
background: transparent;
font-family: inherit;
font-size: inherit;
margin: 0;
white-space: pre;
word-wrap: normal;
line-height: inherit;
color: inherit;
z-index: 2;
position: relative;
overflow: visible;
-webkit-tap-highlight-color: transparent;
-webkit-font-variant-ligatures: contextual;
font-variant-ligatures: contextual;
}
.CodeMirror-wrap pre {
word-wrap: break-word;
white-space: pre-wrap;
word-break: normal;
}
.CodeMirror-linebackground {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
z-index: 0;
}
.CodeMirror-linewidget {
position: relative;
z-index: 2;
padding: 0.1px; /* Force widget margins to stay inside of the container */
}
/* .CodeMirror-widget {
} */
.CodeMirror-rtl pre {
direction: rtl;
}
.CodeMirror-code {
outline: none;
}
/* Force content-box sizing for the elements where we expect it */
.CodeMirror-scroll,
.CodeMirror-sizer,
.CodeMirror-gutter,
.CodeMirror-gutters,
.CodeMirror-linenumber {
-moz-box-sizing: content-box;
box-sizing: content-box;
}
.CodeMirror-measure {
position: absolute;
width: 100%;
height: 0;
overflow: hidden;
visibility: hidden;
}
.CodeMirror-cursor {
position: absolute;
pointer-events: none;
}
.CodeMirror-measure pre {
position: static;
}
div.CodeMirror-cursors {
visibility: hidden;
position: relative;
z-index: 3;
}
div.CodeMirror-dragcursors {
visibility: visible;
}
.CodeMirror-focused div.CodeMirror-cursors {
visibility: visible;
}
.CodeMirror-selected {
background: #d9d9d9;
}
.CodeMirror-focused .CodeMirror-selected {
background: #d7d4f0;
}
.CodeMirror-crosshair {
cursor: crosshair;
}
.CodeMirror-line::selection,
.CodeMirror-line > span::selection,
.CodeMirror-line > span > span::selection {
background: #d7d4f0;
}
.CodeMirror-line::-moz-selection,
.CodeMirror-line > span::-moz-selection,
.CodeMirror-line > span > span::-moz-selection {
background: #d7d4f0;
}
.cm-searching {
background-color: #ffa;
background-color: rgba(255, 255, 0, 0.4);
}
/* Used to force a border model for a node */
.cm-force-border {
padding-right: 0.1px;
}
@media print {
/* Hide the cursor when printing */
.CodeMirror div.CodeMirror-cursors {
visibility: hidden;
}
}
/* See issue #2901 */
.cm-tab-wrap-hack:after {
content: '';
}
/* Help users use markselection to safely style text background */
span.CodeMirror-selectedtext {
background: none;
}

View File

@@ -0,0 +1,4 @@
.tree-wrappper{
min-height: 500px;
overflow-y: scroll;
}

View File

@@ -0,0 +1,298 @@
@import '../../../styles/mixin.scss';
.left-menu {
min-height: 5rem;
// background: #FFF;
// .item-all-interface {
// background-color: red;
// }
// .ant-tabs-bar{
// border-bottom: none;
// margin-bottom: 0
// }
.ant-tag {
margin-right: 0.16rem;
}
.ant-tabs-nav {
width: 100%;
background-color: $color-bg-gray;
}
.ant-tabs-tab {
min-width: 49.4%;
}
.ant-tabs.ant-tabs-card > .ant-tabs-bar .ant-tabs-tab {
height: 39px;
background: #fff;
border-bottom: 0;
border-radius: 0;
}
.ant-tabs.ant-tabs-card > .ant-tabs-bar .ant-tabs-tab:nth-of-type(2) {
border-left: 0;
}
// .ant-tabs.ant-tabs-card > .ant-tabs-bar .ant-tabs-tab:last-of-type {
// border-right: 0;
// }
.ant-tabs.ant-tabs-card > .ant-tabs-bar .ant-tabs-tab-active {
height: 40px;
background-color: #ddd;
// color: $color-white;
}
.ant-tabs.ant-tabs-card > .ant-tabs-bar .ant-tabs-nav-container {
height: 40px;
}
.ant-tabs.ant-tabs-card > .ant-tabs-bar {
text-align: center;
// background: #ececec;
}
.ant-tabs-nav-wrap {
height: 40px;
line-height: 31px;
// border-bottom: 1px solid #d9d9d9;
}
.ant-input {
width: 100%;
}
.interface-filter {
padding: 12px 16px;
padding-right: 110px;
line-height: 32px;
background-color: #ddd;
position: relative;
}
.btn-filter {
position: absolute;
right: 16px;
top: 50%;
transform: translateY(-50%);
}
.ant-tree li .ant-tree-node-content-wrapper {
width: calc(100% - 28px);
position: relative;
.container-title {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.btns {
background-color: #eef7fe;
position: absolute;
top: 50%;
right: 0;
transform: translateY(-60%);
transition: all 0.2s;
}
}
.ant-tree li .ant-tree-node-selected {
.btns {
background-color: #d5ebfc;
transition: all 0.2s;
}
}
.interface-delete-icon {
position: relative;
right: 0;
float: right;
line-height: 25px;
width: 24px;
font-weight: bold;
}
.anticon-ellipsis {
transform: rotate(90deg);
}
.interface-delete-icon:hover {
color: #2395f1;
}
.interface-list {
//max-height: 600px;
//overflow-y: scroll;
.cat_switch_hidden {
.ant-tree-switcher {
visibility: hidden;
}
}
a {
color: rgba(13, 27, 62, 0.65);
}
.btn-http {
height: 23px;
font-size: 10px;
margin-right: 7px;
padding: 0 5px;
width: auto !important;
}
.interface-item {
display: inline-block;
overflow: hidden;
top: 0px;
}
.interface-item-nav {
line-height: 25px;
}
.interface-list {
.cat_switch_hidden {
.ant-tree-switcher {
visibility: hidden;
}
}
.btn-http {
height: 23px;
font-size: 10px;
margin-right: 7px;
padding: 0 5px;
width: auto !important;
}
.interface-item {
display: inline-block;
overflow: hidden;
top: 0px;
line-height: 100%;
text-decoration: none;
}
.interface-item-nav {
line-height: 25px;
}
}
}
}
.right-content {
min-height: 5rem;
background: #fff;
.caseContainer {
table {
border-radius: 4px;
// border-collapse: collapse;
}
.ant-table-small .ant-table-thead > tr > th {
text-align: left;
background-color: #f8f8f8;
}
tr:nth-child(even) {
background: #f8f8f8;
}
}
.interface-content {
.ant-tabs-nav {
width: 100%;
// background-color: #ddd;
// color: $color-white;
}
.ant-tabs-nav-wrap {
text-align: left;
}
}
.interface-title {
clear: both;
font-weight: normal;
margin-top: 0.48rem;
margin-bottom: 0.16rem;
border-left: 3px solid #2395f1;
padding-left: 8px;
.tooltip {
font-size: 13px;
font-weight: normal;
}
}
.container-radiogroup {
text-align: center;
margin-bottom: 0.16rem;
}
.panel-sub {
background: rgba(236, 238, 241, 0.67);
padding: 0.1rem;
.bulk-import {
color: #2395f1;
text-align: right;
margin-right: 16px;
cursor: pointer;
}
}
.ant-radio-button-wrapper-checked {
color: #fff;
background-color: #2395f1;
&:hover {
color: #ddd;
}
}
.href {
color: #2395f1;
cursor: pointer;
}
.remark-editor {
background-color: #fff;
}
.remark {
table {
border-collapse: collapse;
}
th {
text-align: left;
font-weight: normal;
background-color: #f8f8f8;
text-indent: 0.4em;
}
tr {
text-indent: 0.4em;
}
th,
td {
border: 1px solid #e9e9e9;
}
tr:nth-child(odd) {
background: #f8f8f8;
}
tr:nth-child(even) {
background: #fff;
}
}
}
.addcatmodal {
.ant-modal-body {
padding: 10px 0px;
.ant-form-item {
margin-bottom: 10px;
}
.catModalfoot {
border-top: 1px solid #e9e9e9;
margin-bottom: 0px;
padding-top: 10px;
margin-top: 0px;
.ant-form-item-control-wrapper {
margin-left: 0px;
}
.ant-form-item-control {
float: right;
margin-right: 10px;
}
}
}
}
.common-setting-modal{
.setting-item{
margin: 10px;
line-height: 35px;
.col-item{
padding:5px;
}
}
.case-script{
min-height: 200px;
margin: 10px;
width: 98%;
}
.insert-code{
padding-top: 45px;
}
}

View File

@@ -0,0 +1,175 @@
import React, { PureComponent as Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Route, Switch, Redirect, matchPath } from 'react-router-dom';
import { Subnav } from '../../components/index';
import { fetchGroupMsg } from '../../reducer/modules/group';
import { setBreadcrumb } from '../../reducer/modules/user';
import { getProject } from '../../reducer/modules/project';
import Interface from './Interface/Interface.js';
import Activity from './Activity/Activity.js';
import Setting from './Setting/Setting.js';
import Loading from '../../components/Loading/Loading';
import ProjectMember from './Setting/ProjectMember/ProjectMember.js';
import ProjectData from './Setting/ProjectData/ProjectData.js';
const plugin = require('client/plugin.js');
@connect(
state => {
return {
curProject: state.project.currProject,
currGroup: state.group.currGroup
};
},
{
getProject,
fetchGroupMsg,
setBreadcrumb
}
)
export default class Project extends Component {
static propTypes = {
match: PropTypes.object,
curProject: PropTypes.object,
getProject: PropTypes.func,
location: PropTypes.object,
fetchGroupMsg: PropTypes.func,
setBreadcrumb: PropTypes.func,
currGroup: PropTypes.object
};
constructor(props) {
super(props);
}
async UNSAFE_componentWillMount() {
await this.props.getProject(this.props.match.params.id);
await this.props.fetchGroupMsg(this.props.curProject.group_id);
this.props.setBreadcrumb([
{
name: this.props.currGroup.group_name,
href: '/group/' + this.props.currGroup._id
},
{
name: this.props.curProject.name
}
]);
}
async UNSAFE_componentWillReceiveProps(nextProps) {
const currProjectId = this.props.match.params.id;
const nextProjectId = nextProps.match.params.id;
if (currProjectId !== nextProjectId) {
await this.props.getProject(nextProjectId);
await this.props.fetchGroupMsg(this.props.curProject.group_id);
this.props.setBreadcrumb([
{
name: this.props.currGroup.group_name,
href: '/group/' + this.props.currGroup._id
},
{
name: this.props.curProject.name
}
]);
}
}
render() {
const { match, location } = this.props;
let routers = {
interface: { name: '接口', path: '/project/:id/interface/:action', component: Interface },
activity: { name: '动态', path: '/project/:id/activity', component: Activity },
data: { name: '数据管理', path: '/project/:id/data', component: ProjectData },
members: { name: '成员管理', path: '/project/:id/members', component: ProjectMember },
setting: { name: '设置', path: '/project/:id/setting', component: Setting }
};
plugin.emitHook('sub_nav', routers);
let key, defaultName;
for (key in routers) {
if (
matchPath(location.pathname, {
path: routers[key].path
}) !== null
) {
defaultName = routers[key].name;
break;
}
}
// let subnavData = [{
// name: routers.interface.name,
// path: `/project/${match.params.id}/interface/api`
// }, {
// name: routers.activity.name,
// path: `/project/${match.params.id}/activity`
// }, {
// name: routers.data.name,
// path: `/project/${match.params.id}/data`
// }, {
// name: routers.members.name,
// path: `/project/${match.params.id}/members`
// }, {
// name: routers.setting.name,
// path: `/project/${match.params.id}/setting`
// }];
let subnavData = [];
Object.keys(routers).forEach(key => {
let item = routers[key];
let value = {};
if (key === 'interface') {
value = {
name: item.name,
path: `/project/${match.params.id}/interface/api`
};
} else {
value = {
name: item.name,
path: item.path.replace(/\:id/gi, match.params.id)
};
}
subnavData.push(value);
});
if (this.props.currGroup.type === 'private') {
subnavData = subnavData.filter(item => {
return item.name != '成员管理';
});
}
if (this.props.curProject == null || Object.keys(this.props.curProject).length === 0) {
return <Loading visible />;
}
return (
<div>
<Subnav default={defaultName} data={subnavData} />
<Switch>
<Redirect exact from="/project/:id" to={`/project/${match.params.id}/interface/api`} />
{/* <Route path={routers.activity.path} component={Activity} />
<Route path={routers.setting.path} component={Setting} />
{this.props.currGroup.type !== 'private' ?
<Route path={routers.members.path} component={routers.members.component}/>
: null
}
<Route path={routers.data.path} component={ProjectData} /> */}
{Object.keys(routers).map(key => {
let item = routers[key];
return key === 'members' ? (
this.props.currGroup.type !== 'private' ? (
<Route path={item.path} component={item.component} key={key} />
) : null
) : (
<Route path={item.path} component={item.component} key={key} />
);
})}
</Switch>
</div>
);
}
}

View File

@@ -0,0 +1,524 @@
import React, { PureComponent as Component } from 'react';
import {
Upload,
Icon,
message,
Select,
Tooltip,
Button,
Spin,
Switch,
Modal,
Radio,
Input,
Checkbox
} from 'antd';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import './ProjectData.scss';
import axios from 'axios';
import URL from 'url';
const Dragger = Upload.Dragger;
import { saveImportData } from '../../../../reducer/modules/interface';
import { fetchUpdateLogData } from '../../../../reducer/modules/news.js';
import { handleSwaggerUrlData } from '../../../../reducer/modules/project';
const Option = Select.Option;
const confirm = Modal.confirm;
const plugin = require('client/plugin.js');
const RadioGroup = Radio.Group;
const importDataModule = {};
const exportDataModule = {};
const HandleImportData = require('common/HandleImportData');
function handleExportRouteParams(url, status, isWiki) {
if (!url) {
return;
}
let urlObj = URL.parse(url, true),
query = {};
query = Object.assign(query, urlObj.query, { status, isWiki });
return URL.format({
pathname: urlObj.pathname,
query
});
}
// exportDataModule.pdf = {
// name: 'Pdf',
// route: '/api/interface/download_crx',
// desc: '导出项目接口文档为 pdf 文件'
// }
@connect(
state => {
return {
curCatid: -(-state.inter.curdata.catid),
basePath: state.project.currProject.basepath,
updateLogList: state.news.updateLogList,
swaggerUrlData: state.project.swaggerUrlData
};
},
{
saveImportData,
fetchUpdateLogData,
handleSwaggerUrlData
}
)
class ProjectData extends Component {
constructor(props) {
super(props);
this.state = {
selectCatid: '',
menuList: [],
curImportType: 'swagger',
curExportType: null,
showLoading: false,
dataSync: 'merge',
exportContent: 'all',
isSwaggerUrl: false,
swaggerUrl: '',
isWiki: false
};
}
static propTypes = {
match: PropTypes.object,
curCatid: PropTypes.number,
basePath: PropTypes.string,
saveImportData: PropTypes.func,
fetchUpdateLogData: PropTypes.func,
updateLogList: PropTypes.array,
handleSwaggerUrlData: PropTypes.func,
swaggerUrlData: PropTypes.string
};
UNSAFE_componentWillMount() {
axios.get(`/api/interface/getCatMenu?project_id=${this.props.match.params.id}`).then(data => {
if (data.data.errcode === 0) {
let menuList = data.data.data;
this.setState({
menuList: menuList,
selectCatid: menuList[0]._id
});
}
});
plugin.emitHook('import_data', importDataModule);
plugin.emitHook('export_data', exportDataModule, this.props.match.params.id);
}
selectChange(value) {
this.setState({
selectCatid: +value
});
}
uploadChange = info => {
const status = info.file.status;
if (status !== 'uploading') {
console.log(info.file, info.fileList);
}
if (status === 'done') {
message.success(`${info.file.name} 文件上传成功`);
} else if (status === 'error') {
message.error(`${info.file.name} 文件上传失败`);
}
};
handleAddInterface = async res => {
return await HandleImportData(
res,
this.props.match.params.id,
this.state.selectCatid,
this.state.menuList,
this.props.basePath,
this.state.dataSync,
message.error,
message.success,
() => this.setState({ showLoading: false })
);
};
// 本地文件上传
handleFile = info => {
if (!this.state.curImportType) {
return message.error('请选择导入数据的方式');
}
if (this.state.selectCatid) {
this.setState({ showLoading: true });
let reader = new FileReader();
reader.readAsText(info.file);
reader.onload = async res => {
res = await importDataModule[this.state.curImportType].run(res.target.result);
if (this.state.dataSync === 'merge') {
// 开启同步
this.showConfirm(res);
} else {
// 未开启同步
await this.handleAddInterface(res);
}
};
} else {
message.error('请选择上传的默认分类');
}
};
showConfirm = async res => {
let that = this;
let typeid = this.props.match.params.id;
let apiCollections = res.apis.map(item => {
return {
method: item.method,
path: item.path
};
});
let result = await this.props.fetchUpdateLogData({
type: 'project',
typeid,
apis: apiCollections
});
let domainData = result.payload.data.data;
const ref = confirm({
title: '您确认要进行数据同步????',
width: 600,
okType: 'danger',
iconType: 'exclamation-circle',
className: 'dataImport-confirm',
okText: '确认',
cancelText: '取消',
content: (
<div className="postman-dataImport-modal">
<div className="postman-dataImport-modal-content">
{domainData.map((item, index) => {
return (
<div key={index} className="postman-dataImport-show-diff">
<span className="logcontent" dangerouslySetInnerHTML={{ __html: item.content }} />
</div>
);
})}
</div>
<p className="info">温馨提示 数据同步后可能会造成原本的修改数据丢失</p>
</div>
),
async onOk() {
await that.handleAddInterface(res);
},
onCancel() {
that.setState({ showLoading: false, dataSync: 'normal' });
ref.destroy();
}
});
};
handleImportType = val => {
this.setState({
curImportType: val,
isSwaggerUrl: false
});
};
handleExportType = val => {
this.setState({
curExportType: val,
isWiki: false
});
};
// 处理导入信息同步
onChange = checked => {
this.setState({
dataSync: checked
});
};
// 处理swagger URL 导入
handleUrlChange = checked => {
this.setState({
isSwaggerUrl: checked
});
};
// 记录输入的url
swaggerUrlInput = url => {
this.setState({
swaggerUrl: url
});
};
// url导入上传
onUrlUpload = async () => {
if (!this.state.curImportType) {
return message.error('请选择导入数据的方式');
}
if (!this.state.swaggerUrl) {
return message.error('url 不能为空');
}
if (this.state.selectCatid) {
this.setState({ showLoading: true });
try {
// 处理swagger url 导入
await this.props.handleSwaggerUrlData(this.state.swaggerUrl);
// let result = json5_parse(this.props.swaggerUrlData)
let res = await importDataModule[this.state.curImportType].run(this.props.swaggerUrlData);
if (this.state.dataSync === 'merge') {
// merge
this.showConfirm(res);
} else {
// 未开启同步
await this.handleAddInterface(res);
}
} catch (e) {
this.setState({ showLoading: false });
message.error(e.message);
}
} else {
message.error('请选择上传的默认分类');
}
};
// 处理导出接口是全部还是公开
handleChange = e => {
this.setState({ exportContent: e.target.value });
};
// 处理是否开启wiki导出
handleWikiChange = e => {
this.setState({
isWiki: e.target.checked
});
};
/**
*
*
* @returns
* @memberof ProjectData
*/
render() {
const uploadMess = {
name: 'interfaceData',
multiple: true,
showUploadList: false,
action: '/api/interface/interUpload',
customRequest: this.handleFile,
onChange: this.uploadChange
};
let exportUrl =
this.state.curExportType &&
exportDataModule[this.state.curExportType] &&
exportDataModule[this.state.curExportType].route;
let exportHref = handleExportRouteParams(
exportUrl,
this.state.exportContent,
this.state.isWiki
);
// console.log('inter', this.state.exportContent);
return (
<div className="g-row">
<div className="m-panel">
<div className="postman-dataImport">
<div className="dataImportCon">
<div>
<h3>
数据导入&nbsp;
<a
target="_blank"
rel="noopener noreferrer"
href="https://hellosean1025.github.io/yapi/documents/data.html"
>
<Tooltip title="点击查看文档">
<Icon type="question-circle-o" />
</Tooltip>
</a>
</h3>
</div>
<div className="dataImportTile">
<Select
placeholder="请选择导入数据的方式"
value={this.state.curImportType}
onChange={this.handleImportType}
>
{Object.keys(importDataModule).map(name => {
return (
<Option key={name} value={name}>
{importDataModule[name].name}
</Option>
);
})}
</Select>
</div>
<div className="catidSelect">
<Select
value={this.state.selectCatid + ''}
showSearch
style={{ width: '100%' }}
placeholder="请选择数据导入的默认分类"
optionFilterProp="children"
onChange={this.selectChange.bind(this)}
filterOption={(input, option) =>
option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
>
{this.state.menuList.map((item, key) => {
return (
<Option key={key} value={item._id + ''}>
{item.name}
</Option>
);
})}
</Select>
</div>
<div className="dataSync">
<span className="label">
数据同步&nbsp;
<Tooltip
title={
<div>
<h3 style={{ color: 'white' }}>普通模式</h3>
<p>不导入已存在的接口</p>
<br />
<h3 style={{ color: 'white' }}>智能合并</h3>
<p>
已存在的接口将合并返回数据的 response适用于导入了 swagger
数据保留对数据结构的改动
</p>
<br />
<h3 style={{ color: 'white' }}>完全覆盖</h3>
<p>不保留旧数据完全使用新数据适用于接口定义完全交给后端定义</p>
</div>
}
>
<Icon type="question-circle-o" />
</Tooltip>{' '}
</span>
<Select value={this.state.dataSync} onChange={this.onChange}>
<Option value="normal">普通模式</Option>
<Option value="good">智能合并</Option>
<Option value="merge">完全覆盖</Option>
</Select>
{/* <Switch checked={this.state.dataSync} onChange={this.onChange} /> */}
</div>
{this.state.curImportType === 'swagger' && (
<div className="dataSync">
<span className="label">
开启url导入&nbsp;
<Tooltip title="swagger url 导入">
<Icon type="question-circle-o" />
</Tooltip>{' '}
&nbsp;&nbsp;
</span>
<Switch checked={this.state.isSwaggerUrl} onChange={this.handleUrlChange} />
</div>
)}
{this.state.isSwaggerUrl ? (
<div className="import-content url-import-content">
<Input
placeholder="http://demo.swagger.io/v2/swagger.json"
onChange={e => this.swaggerUrlInput(e.target.value)}
/>
<Button
type="primary"
className="url-btn"
onClick={this.onUrlUpload}
loading={this.state.showLoading}
>
上传
</Button>
</div>
) : (
<div className="import-content">
<Spin spinning={this.state.showLoading} tip="上传中...">
<Dragger {...uploadMess}>
<p className="ant-upload-drag-icon">
<Icon type="inbox" />
</p>
<p className="ant-upload-text">点击或者拖拽文件到上传区域</p>
<p
className="ant-upload-hint"
onClick={e => {
e.stopPropagation();
}}
dangerouslySetInnerHTML={{
__html: this.state.curImportType
? importDataModule[this.state.curImportType].desc
: null
}}
/>
</Dragger>
</Spin>
</div>
)}
</div>
<div
className="dataImportCon"
style={{
marginLeft: '20px',
display: Object.keys(exportDataModule).length > 0 ? '' : 'none'
}}
>
<div>
<h3>数据导出</h3>
</div>
<div className="dataImportTile">
<Select placeholder="请选择导出数据的方式" onChange={this.handleExportType}>
{Object.keys(exportDataModule).map(name => {
return (
<Option key={name} value={name}>
{exportDataModule[name].name}
</Option>
);
})}
</Select>
</div>
<div className="dataExport">
<RadioGroup defaultValue="all" onChange={this.handleChange}>
<Radio value="all">全部接口</Radio>
<Radio value="open">公开接口</Radio>
</RadioGroup>
</div>
<div className="export-content">
{this.state.curExportType ? (
<div>
<p className="export-desc">{exportDataModule[this.state.curExportType].desc}</p>
<a
target="_blank"
rel="noopener noreferrer"
href={exportHref}>
<Button className="export-button" type="primary" size="large">
{' '}
导出{' '}
</Button>
</a>
<Checkbox
checked={this.state.isWiki}
onChange={this.handleWikiChange}
className="wiki-btn"
disabled={this.state.curExportType === 'json'}
>
添加wiki&nbsp;
<Tooltip title="开启后 html 和 markdown 数据导出会带上wiki数据">
<Icon type="question-circle-o" />
</Tooltip>{' '}
</Checkbox>
</div>
) : (
<Button disabled className="export-button" type="primary" size="large">
{' '}
导出{' '}
</Button>
)}
</div>
</div>
</div>
</div>
</div>
);
}
}
export default ProjectData;

View File

@@ -0,0 +1,103 @@
.postman-dataImport{
display: flex;
.dataImportCon{
min-width: 304px;
background-color: #ececec;
padding: 16px;
border-radius: 4px;
.ant-upload-drag{
padding: 16px;
background-color: white;
}
.dataImportTile{
color: #2395f1;
padding: 16px 0px;
font-weight: 500;
width: 100%;
.ant-select{
width: 100%;
}
}
.dataExport{
padding-bottom: 16px;
font-weight: 500;
width: 100%;
}
.dataSync{
padding-top: 16px;
font-weight: 500;
width: 100%;
.label{
padding-right: 8px;
width: 150px;
display: inline-block;
}
.label:after {
content: ":";
margin: 0 8px 0 2px;
position: relative;
top: -.5px;
}
}
.import-content {
margin-top: 16px;
height: 180px;
}
.url-import-content {
text-align: center;
.url-btn{
margin-top: 16px;
}
}
.export-content{
text-align: center;
}
.export-desc{
padding-bottom: 15px;
}
.export-button{
width: 100px;
height:35px;
}
.wiki-btn {
margin-left: 8px;
}
}
}
.postman-dataImport-modal{
.postman-dataImport-modal-content{
max-height: 600px;
min-width: 534px;
overflow-y: scroll;
padding-top: 8px;
}
.postman-dataImport-show-diff{
padding: 4px 0;
}
.info{
font-weight: 400;
font-size: 16px;
padding-top: 24px;
}
}
.dataImport-confirm{
.ant-modal-content .ant-confirm-btns{
margin-top: 10px;
}
}

View File

@@ -0,0 +1,382 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import './index.scss';
import { Icon, Row, Col, Form, Input, Select, Button, AutoComplete, Tooltip } from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
import constants from 'client/constants/variable.js';
const initMap = {
header: [
{
name: '',
value: ''
}
],
cookie: [
{
name: '',
value: ''
}
],
global: [
{
name: '',
value: ''
}
]
};
class ProjectEnvContent extends Component {
static propTypes = {
projectMsg: PropTypes.object,
form: PropTypes.object,
onSubmit: PropTypes.func,
handleEnvInput: PropTypes.func
};
initState(curdata) {
let header = [
{
name: '',
value: ''
}
];
let cookie = [
{
name: '',
value: ''
}
];
let global = [
{
name: '',
value: ''
}
];
const curheader = curdata.header;
const curGlobal = curdata.global;
if (curheader && curheader.length !== 0) {
curheader.forEach(item => {
if (item.name === 'Cookie') {
let cookieStr = item.value;
if (cookieStr) {
cookieStr = cookieStr.split(';').forEach(c => {
if (c) {
c = c.split('=');
cookie.unshift({
name: c[0] ? c[0].trim() : '',
value: c[1] ? c[1].trim() : ''
});
}
});
}
} else {
header.unshift(item);
}
});
}
if (curGlobal && curGlobal.length !== 0) {
curGlobal.forEach(item => {
global.unshift(item);
});
}
return { header, cookie, global };
}
constructor(props) {
super(props);
this.state = Object.assign({}, initMap);
}
addHeader = (value, index, name) => {
let nextHeader = this.state[name][index + 1];
if (nextHeader && typeof nextHeader === 'object') {
return;
}
let newValue = {};
let data = { name: '', value: '' };
newValue[name] = [].concat(this.state[name], data);
this.setState(newValue);
};
delHeader = (key, name) => {
let curValue = this.props.form.getFieldValue(name);
let newValue = {};
newValue[name] = curValue.filter((val, index) => {
return index !== key;
});
this.props.form.setFieldsValue(newValue);
this.setState(newValue);
};
handleInit(data) {
this.props.form.resetFields();
let newValue = this.initState(data);
this.setState({ ...newValue });
}
UNSAFE_componentWillReceiveProps(nextProps) {
let curEnvName = this.props.projectMsg.name;
let nextEnvName = nextProps.projectMsg.name;
if (curEnvName !== nextEnvName) {
this.handleInit(nextProps.projectMsg);
}
}
handleOk = e => {
e.preventDefault();
const { form, onSubmit, projectMsg } = this.props;
form.validateFields((err, values) => {
if (!err) {
let header = values.header.filter(val => {
return val.name !== '';
});
let cookie = values.cookie.filter(val => {
return val.name !== '';
});
let global = values.global.filter(val => {
return val.name !== '';
});
if (cookie.length > 0) {
header.push({
name: 'Cookie',
value: cookie.map(item => item.name + '=' + item.value).join(';')
});
}
let assignValue = {};
assignValue.env = Object.assign(
{ _id: projectMsg._id },
{
name: values.env.name,
domain: values.env.protocol + values.env.domain,
header: header,
global
}
);
onSubmit(assignValue);
}
});
};
render() {
const { projectMsg } = this.props;
const { getFieldDecorator } = this.props.form;
const headerTpl = (item, index) => {
const headerLength = this.state.header.length - 1;
return (
<Row gutter={2} key={index}>
<Col span={10}>
<FormItem>
{getFieldDecorator('header[' + index + '].name', {
validateTrigger: ['onChange', 'onBlur'],
initialValue: item.name || ''
})(
<AutoComplete
style={{ width: '200px' }}
allowClear={true}
dataSource={constants.HTTP_REQUEST_HEADER}
placeholder="请输入header名称"
onChange={() => this.addHeader(item, index, 'header')}
filterOption={(inputValue, option) =>
option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
}
/>
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem>
{getFieldDecorator('header[' + index + '].value', {
validateTrigger: ['onChange', 'onBlur'],
initialValue: item.value || ''
})(<Input placeholder="请输入参数内容" style={{ width: '90%', marginRight: 8 }} />)}
</FormItem>
</Col>
<Col span={2} className={index === headerLength ? ' env-last-row' : null}>
{/* 新增的项中,只有最后一项没有有删除按钮 */}
<Icon
className="dynamic-delete-button delete"
type="delete"
onClick={e => {
e.stopPropagation();
this.delHeader(index, 'header');
}}
/>
</Col>
</Row>
);
};
const commonTpl = (item, index, name) => {
const length = this.state[name].length - 1;
return (
<Row gutter={2} key={index}>
<Col span={10}>
<FormItem>
{getFieldDecorator(`${name}[${index}].name`, {
validateTrigger: ['onChange', 'onBlur'],
initialValue: item.name || ''
})(
<Input
placeholder={`请输入 ${name} Name`}
style={{ width: '200px' }}
onChange={() => this.addHeader(item, index, name)}
/>
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem>
{getFieldDecorator(`${name}[${index}].value`, {
validateTrigger: ['onChange', 'onBlur'],
initialValue: item.value || ''
})(<Input placeholder="请输入参数内容" style={{ width: '90%', marginRight: 8 }} />)}
</FormItem>
</Col>
<Col span={2} className={index === length ? ' env-last-row' : null}>
{/* 新增的项中,只有最后一项没有有删除按钮 */}
<Icon
className="dynamic-delete-button delete"
type="delete"
onClick={e => {
e.stopPropagation();
this.delHeader(index, name);
}}
/>
</Col>
</Row>
);
};
const envTpl = data => {
return (
<div>
<h3 className="env-label">环境名称</h3>
<FormItem required={false}>
{getFieldDecorator('env.name', {
validateTrigger: ['onChange', 'onBlur'],
initialValue: data.name === '新环境' ? '' : data.name || '',
rules: [
{
required: false,
whitespace: true,
validator(rule, value, callback) {
if (value) {
if (value.length === 0) {
callback('请输入环境名称');
} else if (!/\S/.test(value)) {
callback('请输入环境名称');
} else {
return callback();
}
} else {
callback('请输入环境名称');
}
}
}
]
})(
<Input
onChange={e => this.props.handleEnvInput(e.target.value)}
placeholder="请输入环境名称"
style={{ width: '90%', marginRight: 8 }}
/>
)}
</FormItem>
<h3 className="env-label">环境域名</h3>
<FormItem required={false}>
{getFieldDecorator('env.domain', {
validateTrigger: ['onChange', 'onBlur'],
initialValue: data.domain ? data.domain.split('//')[1] : '',
rules: [
{
required: false,
whitespace: true,
validator(rule, value, callback) {
if (value) {
if (value.length === 0) {
callback('请输入环境域名!');
} else if (/\s/.test(value)) {
callback('环境域名不允许出现空格!');
} else {
return callback();
}
} else {
callback('请输入环境域名!');
}
}
}
]
})(
<Input
placeholder="请输入环境域名"
style={{ width: '90%', marginRight: 8 }}
addonBefore={getFieldDecorator('env.protocol', {
initialValue: data.domain ? data.domain.split('//')[0] + '//' : 'http://',
rules: [
{
required: true
}
]
})(
<Select>
<Option value="http://">{'http://'}</Option>
<Option value="https://">{'https://'}</Option>
</Select>
)}
/>
)}
</FormItem>
<h3 className="env-label">Header</h3>
{this.state.header.map((item, index) => {
return headerTpl(item, index);
})}
<h3 className="env-label">Cookie</h3>
{this.state.cookie.map((item, index) => {
return commonTpl(item, index, 'cookie');
})}
<h3 className="env-label">
global
<a
target="_blank"
rel="noopener noreferrer"
href="https://hellosean1025.github.io/yapi/documents/project.html#%E9%85%8D%E7%BD%AE%E7%8E%AF%E5%A2%83"
style={{ marginLeft: 8 }}
>
<Tooltip title="点击查看文档">
<Icon type="question-circle-o" style={{fontSize: '13px'}}/>
</Tooltip>
</a>
</h3>
{this.state.global.map((item, index) => {
return commonTpl(item, index, 'global');
})}
</div>
);
};
return (
<div>
{envTpl(projectMsg)}
<div className="btnwrap-changeproject">
<Button
className="m-btn btn-save"
icon="save"
type="primary"
size="large"
onClick={this.handleOk}
>
</Button>
</div>
</div>
);
}
}
export default Form.create()(ProjectEnvContent);

View File

@@ -0,0 +1,228 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import './index.scss';
import { Icon, Layout, Tooltip, message, Row, Popconfirm } from 'antd';
const { Content, Sider } = Layout;
import ProjectEnvContent from './ProjectEnvContent.js';
import { connect } from 'react-redux';
import { updateEnv, getProject, getEnv } from '../../../../reducer/modules/project';
import EasyDragSort from '../../../../components/EasyDragSort/EasyDragSort.js';
@connect(
state => {
return {
projectMsg: state.project.currProject
};
},
{
updateEnv,
getProject,
getEnv
}
)
class ProjectEnv extends Component {
static propTypes = {
projectId: PropTypes.number,
updateEnv: PropTypes.func,
getProject: PropTypes.func,
projectMsg: PropTypes.object,
onOk: PropTypes.func,
getEnv: PropTypes.func
};
constructor(props) {
super(props);
this.state = {
env: [],
_id: null,
currentEnvMsg: {},
delIcon: null,
currentKey: -2
};
}
initState(curdata, id) {
let newValue = {};
newValue['env'] = [].concat(curdata);
newValue['_id'] = id;
this.setState({
...this.state,
...newValue
});
}
async UNSAFE_componentWillMount() {
this._isMounted = true;
await this.props.getProject(this.props.projectId);
const { env, _id } = this.props.projectMsg;
this.initState(env, _id);
this.handleClick(0, env[0]);
}
componentWillUnmount() {
this._isMounted = false;
}
handleClick = (key, data) => {
this.setState({
currentEnvMsg: data,
currentKey: key
});
};
// 增加环境变量项
addParams = (name, data) => {
let newValue = {};
data = { name: '新环境', domain: '', header: [] };
newValue[name] = [].concat(data, this.state[name]);
this.setState(newValue);
this.handleClick(0, data);
};
// 删除提示信息
showConfirm(key, name) {
let assignValue = this.delParams(key, name);
this.onSave(assignValue);
}
// 删除环境变量项
delParams = (key, name) => {
let curValue = this.state.env;
let newValue = {};
newValue[name] = curValue.filter((val, index) => {
return index !== key;
});
this.setState(newValue);
this.handleClick(0, newValue[name][0]);
newValue['_id'] = this.state._id;
return newValue;
};
enterItem = key => {
this.setState({ delIcon: key });
};
// 保存设置
async onSave(assignValue) {
await this.props
.updateEnv(assignValue)
.then(res => {
if (res.payload.data.errcode == 0) {
this.props.getProject(this.props.projectId);
this.props.getEnv(this.props.projectId);
message.success('修改成功! ');
if(this._isMounted) {
this.setState({ ...assignValue });
}
}
})
.catch(() => {
message.error('环境设置不成功 ');
});
}
// 提交保存信息
onSubmit = (value, index) => {
let assignValue = {};
assignValue['env'] = [].concat(this.state.env);
assignValue['env'].splice(index, 1, value['env']);
assignValue['_id'] = this.state._id;
this.onSave(assignValue);
this.props.onOk && this.props.onOk(assignValue['env'], index);
};
// 动态修改环境名称
handleInputChange = (value, currentKey) => {
let newValue = [].concat(this.state.env);
newValue[currentKey].name = value || '新环境';
this.setState({ env: newValue });
};
// 侧边栏拖拽
handleDragMove = name => {
return (data, from, to) => {
let newValue = {
[name]: data
};
this.setState(newValue);
newValue['_id'] = this.state._id;
this.handleClick(to, newValue[name][to]);
this.onSave(newValue);
};
};
render() {
const { env, currentKey } = this.state;
const envSettingItems = env.map((item, index) => {
return (
<Row
key={index}
className={'menu-item ' + (index === currentKey ? 'menu-item-checked' : '')}
onClick={() => this.handleClick(index, item)}
onMouseEnter={() => this.enterItem(index)}
>
<span className="env-icon-style">
<span className="env-name" style={{ color: item.name === '新环境' && '#2395f1' }}>
{item.name}
</span>
<Popconfirm
title="您确认删除此环境变量?"
onConfirm={e => {
e.stopPropagation();
this.showConfirm(index, 'env');
}}
okText="确定"
cancelText="取消"
>
<Icon
type="delete"
className="interface-delete-icon"
style={{
display: this.state.delIcon == index && env.length - 1 !== 0 ? 'block' : 'none'
}}
/>
</Popconfirm>
</span>
</Row>
);
});
return (
<div className="m-env-panel">
<Layout className="project-env">
<Sider width={195} style={{ background: '#fff' }}>
<div style={{ height: '100%', borderRight: 0 }}>
<Row className="first-menu-item menu-item">
<div className="env-icon-style">
<h3>
环境列表&nbsp;<Tooltip placement="top" title="在这里添加项目的环境配置">
<Icon type="question-circle-o" />
</Tooltip>
</h3>
<Tooltip title="添加环境变量">
<Icon type="plus" onClick={() => this.addParams('env')} />
</Tooltip>
</div>
</Row>
<EasyDragSort data={() => env} onChange={this.handleDragMove('env')}>
{envSettingItems}
</EasyDragSort>
</div>
</Sider>
<Layout className="env-content">
<Content style={{ background: '#fff', padding: 24, margin: 0, minHeight: 280 }}>
<ProjectEnvContent
projectMsg={this.state.currentEnvMsg}
onSubmit={e => this.onSubmit(e, currentKey)}
handleEnvInput={e => this.handleInputChange(e, currentKey)}
/>
</Content>
</Layout>
</Layout>
</div>
);
}
}
export default ProjectEnv;

View File

@@ -0,0 +1,93 @@
.m-env-panel {
// padding-top: 8px;
min-height: 4.68rem;
margin-top: 0;
background-color: #fff;
}
.project-env{
min-height: 4.68rem;
.env-icon-style{
display: flex;
justify-content: space-between;
align-items: center;
.anticon{
font-size: 15px;
}
}
.menu-item{
padding: 0 16px;
font-size: 13px;
line-height: 42px;
height: 42px;
overflow: hidden;
text-overflow: ellipsis;
cursor: pointer;
}
.menu-item-checked{
background-color: #eef7fe;
color: #2395f1;
font-size: 14px;
margin-right: -1px;
border-right: 2px solid #2395f1;
}
.first-menu-item{
background-color: #eceef1;
}
.delete{
font-size: 20px;
top: 8px;
}
.env-content{
border-left: 1px solid #ccc;
}
.ant-menu-item-disabled{
cursor: pointer;
}
.m-empty-prompt{
display: flex;
height: 400px;
span{
margin: auto;
font-size: 16px;
.anticon {
padding-right: 16px;
font-size: 24px;
}
}
}
.env-label{
padding-bottom: 8px;
a {
color: #636363;
}
}
.env-last-row {
display: none;
}
.env-name{
width: 150px;
overflow: hidden;
text-overflow: ellipsis;
}
.btnwrap-changeproject {
text-align: center;
padding: .16rem 0;
background: #fff;
background-color: #fff;
margin: 0 -.4rem;
background-size: 4px 4px;
}
}

View File

@@ -0,0 +1,444 @@
import React, { PureComponent as Component } from 'react';
import {
Table,
Card,
Badge,
Select,
Button,
Modal,
Row,
Col,
message,
Popconfirm,
Switch,
Tooltip
} from 'antd';
import PropTypes from 'prop-types';
import { fetchGroupMsg } from '../../../../reducer/modules/group';
import { connect } from 'react-redux';
import ErrMsg from '../../../../components/ErrMsg/ErrMsg.js';
import { fetchGroupMemberList } from '../../../../reducer/modules/group.js';
import {
fetchProjectList,
getProjectMemberList,
getProject,
addMember,
delMember,
changeMemberRole,
changeMemberEmailNotice
} from '../../../../reducer/modules/project.js';
import UsernameAutoComplete from '../../../../components/UsernameAutoComplete/UsernameAutoComplete.js';
import '../Setting.scss';
const Option = Select.Option;
const arrayAddKey = arr => {
return arr.map((item, index) => {
return {
...item,
key: index
};
});
};
@connect(
state => {
return {
projectMsg: state.project.currProject,
uid: state.user.uid,
projectList: state.project.projectList
};
},
{
fetchGroupMemberList,
getProjectMemberList,
addMember,
delMember,
fetchGroupMsg,
changeMemberRole,
getProject,
fetchProjectList,
changeMemberEmailNotice
}
)
class ProjectMember extends Component {
constructor(props) {
super(props);
this.state = {
groupMemberList: [],
projectMemberList: [],
groupName: '',
role: '',
visible: false,
dataSource: [],
inputUids: [],
inputRole: 'dev',
modalVisible: false,
selectProjectId: 0
};
}
static propTypes = {
match: PropTypes.object,
projectId: PropTypes.number,
projectMsg: PropTypes.object,
uid: PropTypes.number,
addMember: PropTypes.func,
delMember: PropTypes.func,
changeMemberRole: PropTypes.func,
getProject: PropTypes.func,
fetchGroupMemberList: PropTypes.func,
fetchGroupMsg: PropTypes.func,
getProjectMemberList: PropTypes.func,
fetchProjectList: PropTypes.func,
projectList: PropTypes.array,
changeMemberEmailNotice: PropTypes.func
};
showAddMemberModal = () => {
this.setState({
visible: true
});
};
showImportMemberModal = async () => {
await this.props.fetchProjectList(this.props.projectMsg.group_id);
this.setState({
modalVisible: true
});
};
// 重新获取列表
reFetchList = () => {
this.props.getProjectMemberList(this.props.match.params.id).then(res => {
this.setState({
projectMemberList: arrayAddKey(res.payload.data.data),
visible: false,
modalVisible: false
});
});
};
handleOk = () => {
this.addMembers(this.state.inputUids);
};
// 增 - 添加成员
addMembers = memberUids => {
this.props
.addMember({
id: this.props.match.params.id,
member_uids: memberUids,
role: this.state.inputRole
})
.then(res => {
if (!res.payload.data.errcode) {
const { add_members, exist_members } = res.payload.data.data;
const addLength = add_members.length;
const existLength = exist_members.length;
this.setState({
inputRole: 'dev',
inputUids: []
});
message.success(`添加成功! 已成功添加 ${addLength} 人,其中 ${existLength} 人已存在`);
this.reFetchList(); // 添加成功后重新获取分组成员列表
}
});
};
// 添加成员时 选择新增成员权限
changeNewMemberRole = value => {
this.setState({
inputRole: value
});
};
// 删 - 删除分组成员
deleteConfirm = member_uid => {
return () => {
const id = this.props.match.params.id;
this.props.delMember({ id, member_uid }).then(res => {
if (!res.payload.data.errcode) {
message.success(res.payload.data.errmsg);
this.reFetchList(); // 添加成功后重新获取分组成员列表
}
});
};
};
// 改 - 修改成员权限
changeUserRole = e => {
const id = this.props.match.params.id;
const role = e.split('-')[0];
const member_uid = e.split('-')[1];
this.props.changeMemberRole({ id, member_uid, role }).then(res => {
if (!res.payload.data.errcode) {
message.success(res.payload.data.errmsg);
this.reFetchList(); // 添加成功后重新获取分组成员列表
}
});
};
// 修改用户是否接收消息通知
changeEmailNotice = async (notice, member_uid) => {
const id = this.props.match.params.id;
await this.props.changeMemberEmailNotice({ id, member_uid, notice });
this.reFetchList(); // 添加成功后重新获取项目成员列表
};
// 关闭模态框
handleCancel = () => {
this.setState({
visible: false
});
};
// 关闭批量导入模态框
handleModalCancel = () => {
this.setState({
modalVisible: false
});
};
// 处理选择项目
handleChange = key => {
this.setState({
selectProjectId: key
});
};
// 确定批量导入模态框
handleModalOk = async () => {
// 获取项目中的成员列表
const menberList = await this.props.getProjectMemberList(this.state.selectProjectId);
const memberUidList = menberList.payload.data.data.map(item => {
return item.uid;
});
this.addMembers(memberUidList);
};
onUserSelect = uids => {
this.setState({
inputUids: uids
});
};
async UNSAFE_componentWillMount() {
const groupMemberList = await this.props.fetchGroupMemberList(this.props.projectMsg.group_id);
const groupMsg = await this.props.fetchGroupMsg(this.props.projectMsg.group_id);
const projectMemberList = await this.props.getProjectMemberList(this.props.match.params.id);
this.setState({
groupMemberList: groupMemberList.payload.data.data,
groupName: groupMsg.payload.data.data.group_name,
projectMemberList: arrayAddKey(projectMemberList.payload.data.data),
role: this.props.projectMsg.role
});
}
render() {
const isEmailChangeEable = this.state.role === 'owner' || this.state.role === 'admin';
const columns = [
{
title:
this.props.projectMsg.name + ' 项目成员 (' + this.state.projectMemberList.length + ') 人',
dataIndex: 'username',
key: 'username',
render: (text, record) => {
return (
<div className="m-user">
<img src={'/api/user/avatar?uid=' + record.uid} className="m-user-img" />
<p className="m-user-name">{text}</p>
<Tooltip placement="top" title="消息通知">
<span>
<Switch
size="small"
checkedChildren="开"
unCheckedChildren="关"
checked={record.email_notice}
disabled={!(isEmailChangeEable || record.uid === this.props.uid)}
onChange={e => this.changeEmailNotice(e, record.uid)}
/>
</span>
</Tooltip>
</div>
);
}
},
{
title:
this.state.role === 'owner' || this.state.role === 'admin' ? (
<div className="btn-container">
<Button className="btn" type="primary" icon="plus" onClick={this.showAddMemberModal}>
添加成员
</Button>
<Button className="btn" icon="plus" onClick={this.showImportMemberModal}>
批量导入成员
</Button>
</div>
) : (
''
),
key: 'action',
className: 'member-opration',
render: (text, record) => {
if (this.state.role === 'owner' || this.state.role === 'admin') {
return (
<div>
<Select
value={record.role + '-' + record.uid}
className="select"
onChange={this.changeUserRole}
>
<Option value={'owner-' + record.uid}>组长</Option>
<Option value={'dev-' + record.uid}>开发者</Option>
<Option value={'guest-' + record.uid}>访客</Option>
</Select>
<Popconfirm
placement="topRight"
title="你确定要删除吗? "
onConfirm={this.deleteConfirm(record.uid)}
okText="确定"
cancelText=""
>
<Button type="danger" icon="delete" className="btn-danger" />
</Popconfirm>
</div>
);
} else {
// 非管理员可以看到权限 但无法修改
if (record.role === 'owner') {
return '组长';
} else if (record.role === 'dev') {
return '开发者';
} else if (record.role === 'guest') {
return '访客';
} else {
return '';
}
}
}
}
];
// 获取当前分组下的所有项目名称
const children = this.props.projectList.map((item, index) => (
<Option key={index} value={'' + item._id}>
{item.name}
</Option>
));
return (
<div className="g-row">
<div className="m-panel">
{this.state.visible ? (
<Modal
title="添加成员"
visible={this.state.visible}
onOk={this.handleOk}
onCancel={this.handleCancel}
>
<Row gutter={6} className="modal-input">
<Col span="5">
<div className="label usernamelabel">用户名: </div>
</Col>
<Col span="15">
<UsernameAutoComplete callbackState={this.onUserSelect} />
</Col>
</Row>
<Row gutter={6} className="modal-input">
<Col span="5">
<div className="label usernamelabel">权限: </div>
</Col>
<Col span="15">
<Select defaultValue="dev" className="select" onChange={this.changeNewMemberRole}>
<Option value="owner">组长</Option>
<Option value="dev">开发者</Option>
<Option value="guest">访客</Option>
</Select>
</Col>
</Row>
</Modal>
) : (
''
)}
<Modal
title="批量导入成员"
visible={this.state.modalVisible}
onOk={this.handleModalOk}
onCancel={this.handleModalCancel}
>
<Row gutter={6} className="modal-input">
<Col span="5">
<div className="label usernamelabel">项目名: </div>
</Col>
<Col span="15">
<Select
showSearch
style={{ width: 200 }}
placeholder="请选择项目名称"
optionFilterProp="children"
onChange={this.handleChange}
>
{children}
</Select>
</Col>
</Row>
</Modal>
<Table
columns={columns}
dataSource={this.state.projectMemberList}
pagination={false}
locale={{ emptyText: <ErrMsg type="noMemberInProject" /> }}
className="setting-project-member"
/>
<Card
bordered={false}
title={
this.state.groupName + ' 分组成员 ' + '(' + this.state.groupMemberList.length + ') 人'
}
hoverable={true}
className="setting-group"
>
{this.state.groupMemberList.length ? (
this.state.groupMemberList.map((item, index) => {
return (
<div key={index} className="card-item">
<img
src={
location.protocol +
'//' +
location.host +
'/api/user/avatar?uid=' +
item.uid
}
className="item-img"
/>
<p className="item-name">
{item.username}
{item.uid === this.props.uid ? (
<Badge
count={'我'}
style={{
backgroundColor: '#689bd0',
fontSize: '13px',
marginLeft: '8px',
borderRadius: '4px'
}}
/>
) : null}
</p>
{item.role === 'owner' ? <p className="item-role">组长</p> : null}
{item.role === 'dev' ? <p className="item-role">开发者</p> : null}
{item.role === 'guest' ? <p className="item-role">访客</p> : null}
</div>
);
})
) : (
<ErrMsg type="noMemberInGroup" />
)}
</Card>
</div>
</div>
);
}
}
export default ProjectMember;

View File

@@ -0,0 +1,520 @@
import React, { PureComponent as Component } from 'react';
import {
Form,
Input,
Switch,
Select,
Icon,
Tooltip,
Button,
Row,
Col,
message,
Card,
Radio,
Alert,
Modal,
Popover
} from 'antd';
import PropTypes from 'prop-types';
import {
updateProject,
delProject,
getProject,
upsetProject
} from '../../../../reducer/modules/project';
import { fetchGroupMsg } from '../../../../reducer/modules/group';
import { fetchGroupList } from '../../../../reducer/modules/group.js';
import { setBreadcrumb } from '../../../../reducer/modules/user';
import { connect } from 'react-redux';
const { TextArea } = Input;
import { withRouter } from 'react-router';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;
import constants from '../../../../constants/variable.js';
const confirm = Modal.confirm;
import { nameLengthLimit, entries, trim, htmlFilter } from '../../../../common';
import '../Setting.scss';
import _ from 'underscore';
import ProjectTag from './ProjectTag.js';
// layout
const formItemLayout = {
labelCol: {
lg: { offset: 1, span: 3 },
xs: { span: 24 },
sm: { span: 6 }
},
wrapperCol: {
lg: { span: 19 },
xs: { span: 24 },
sm: { span: 14 }
},
className: 'form-item'
};
const Option = Select.Option;
@connect(
state => {
return {
projectList: state.project.projectList,
groupList: state.group.groupList,
projectMsg: state.project.currProject,
currGroup: state.group.currGroup
};
},
{
updateProject,
delProject,
getProject,
fetchGroupMsg,
upsetProject,
fetchGroupList,
setBreadcrumb
}
)
@withRouter
class ProjectMessage extends Component {
constructor(props) {
super(props);
this.state = {
protocol: 'http://',
projectMsg: {},
showDangerOptions: false
};
}
static propTypes = {
projectId: PropTypes.number,
form: PropTypes.object,
updateProject: PropTypes.func,
delProject: PropTypes.func,
getProject: PropTypes.func,
history: PropTypes.object,
fetchGroupMsg: PropTypes.func,
upsetProject: PropTypes.func,
groupList: PropTypes.array,
projectList: PropTypes.array,
projectMsg: PropTypes.object,
fetchGroupList: PropTypes.func,
currGroup: PropTypes.object,
setBreadcrumb: PropTypes.func
};
// 确认修改
handleOk = e => {
e.preventDefault();
const { form, updateProject, projectMsg, groupList } = this.props;
form.validateFields((err, values) => {
if (!err) {
let { tag } = this.tag.state;
// let tag = this.refs.tag;
tag = tag.filter(val => {
return val.name !== '';
});
let assignValue = Object.assign(projectMsg, values, { tag });
values.protocol = this.state.protocol.split(':')[0];
const group_id = assignValue.group_id;
const selectGroup = _.find(groupList, item => {
return item._id == group_id;
});
updateProject(assignValue)
.then(res => {
if (res.payload.data.errcode == 0) {
this.props.getProject(this.props.projectId);
message.success('修改成功! ');
// 如果如果项目所在的分组位置发生改变
this.props.fetchGroupMsg(group_id);
// this.props.history.push('/group');
let projectName = htmlFilter(assignValue.name);
this.props.setBreadcrumb([
{
name: selectGroup.group_name,
href: '/group/' + group_id
},
{
name: projectName
}
]);
}
})
.catch(() => {});
form.resetFields();
}
});
};
tagSubmit = tag => {
this.tag = tag;
};
showConfirm = () => {
let that = this;
confirm({
title: '确认删除 ' + that.props.projectMsg.name + ' 项目吗?',
content: (
<div style={{ marginTop: '10px', fontSize: '13px', lineHeight: '25px' }}>
<Alert
message="警告:此操作非常危险,会删除该项目下面所有接口,并且无法恢复!"
type="warning"
banner
/>
<div style={{ marginTop: '16px' }}>
<p style={{ marginBottom: '8px' }}>
<b>请输入项目名称确认此操作:</b>
</p>
<Input id="project_name" size="large" />
</div>
</div>
),
onOk() {
let groupName = trim(document.getElementById('project_name').value);
if (that.props.projectMsg.name !== groupName) {
message.error('项目名称有误');
return new Promise((resolve, reject) => {
reject('error');
});
} else {
that.props.delProject(that.props.projectId).then(res => {
if (res.payload.data.errcode == 0) {
message.success('删除成功!');
that.props.history.push('/group/' + that.props.projectMsg.group_id);
}
});
}
},
iconType: 'delete',
onCancel() {}
});
};
// 修改项目头像的背景颜色
changeProjectColor = e => {
const { _id, color, icon } = this.props.projectMsg;
this.props.upsetProject({ id: _id, color: e.target.value || color, icon }).then(res => {
if (res.payload.data.errcode === 0) {
this.props.getProject(this.props.projectId);
}
});
};
// 修改项目头像的图标
changeProjectIcon = e => {
const { _id, color, icon } = this.props.projectMsg;
this.props.upsetProject({ id: _id, color, icon: e.target.value || icon }).then(res => {
if (res.payload.data.errcode === 0) {
this.props.getProject(this.props.projectId);
}
});
};
// 点击“查看危险操作”按钮
toggleDangerOptions = () => {
// console.log(this.state.showDangerOptions);
this.setState({
showDangerOptions: !this.state.showDangerOptions
});
};
async UNSAFE_componentWillMount() {
await this.props.fetchGroupList();
await this.props.fetchGroupMsg(this.props.projectMsg.group_id);
}
render() {
const { getFieldDecorator } = this.props.form;
const { projectMsg, currGroup } = this.props;
const mockUrl =
location.protocol +
'//' +
location.hostname +
(location.port !== '' ? ':' + location.port : '') +
`/mock/${projectMsg._id}${projectMsg.basepath}+$接口请求路径`;
let initFormValues = {};
const {
name,
basepath,
desc,
project_type,
group_id,
switch_notice,
strice,
is_json5,
tag
} = projectMsg;
initFormValues = {
name,
basepath,
desc,
project_type,
group_id,
switch_notice,
strice,
is_json5,
tag
};
const colorArr = entries(constants.PROJECT_COLOR);
const colorSelector = (
<RadioGroup onChange={this.changeProjectColor} value={projectMsg.color} className="color">
{colorArr.map((item, index) => {
return (
<RadioButton
key={index}
value={item[0]}
style={{ backgroundColor: item[1], color: '#fff', fontWeight: 'bold' }}
>
{item[0] === projectMsg.color ? <Icon type="check" /> : null}
</RadioButton>
);
})}
</RadioGroup>
);
const iconSelector = (
<RadioGroup onChange={this.changeProjectIcon} value={projectMsg.icon} className="icon">
{constants.PROJECT_ICON.map(item => {
return (
<RadioButton key={item} value={item} style={{ fontWeight: 'bold' }}>
<Icon type={item} />
</RadioButton>
);
})}
</RadioGroup>
);
const selectDisbaled = projectMsg.role === 'owner' || projectMsg.role === 'admin';
return (
<div>
<div className="m-panel">
<Row className="project-setting">
<Col xs={6} lg={{ offset: 1, span: 3 }} className="setting-logo">
<Popover
placement="bottom"
title={colorSelector}
content={iconSelector}
trigger="click"
overlayClassName="change-project-container"
>
<Icon
type={projectMsg.icon || 'star-o'}
className="ui-logo"
style={{
backgroundColor:
constants.PROJECT_COLOR[projectMsg.color] || constants.PROJECT_COLOR.blue
}}
/>
</Popover>
</Col>
<Col xs={18} sm={15} lg={19} className="setting-intro">
<h2 className="ui-title">
{(currGroup.group_name || '') + ' / ' + (projectMsg.name || '')}
</h2>
{/* <p className="ui-desc">{projectMsg.desc}</p> */}
</Col>
</Row>
<hr className="breakline" />
<Form>
<FormItem {...formItemLayout} label="项目ID">
<span>{this.props.projectMsg._id}</span>
</FormItem>
<FormItem {...formItemLayout} label="项目名称">
{getFieldDecorator('name', {
initialValue: initFormValues.name,
rules: nameLengthLimit('项目')
})(<Input />)}
</FormItem>
<FormItem {...formItemLayout} label="所属分组">
{getFieldDecorator('group_id', {
initialValue: initFormValues.group_id + '',
rules: [
{
required: true,
message: '请选择项目所属的分组!'
}
]
})(
<Select disabled={!selectDisbaled}>
{this.props.groupList.map((item, index) => (
<Option value={item._id.toString()} key={index}>
{item.group_name}
</Option>
))}
</Select>
)}
</FormItem>
<FormItem
{...formItemLayout}
label={
<span>
接口基本路径&nbsp;
<Tooltip title="基本路径为空表示根路径">
<Icon type="question-circle-o" />
</Tooltip>
</span>
}
>
{getFieldDecorator('basepath', {
initialValue: initFormValues.basepath,
rules: [
{
required: false,
message: '请输入基本路径! '
}
]
})(<Input />)}
</FormItem>
<FormItem
{...formItemLayout}
label={
<span>
MOCK地址&nbsp;
<Tooltip title="具体使用方法请查看文档">
<Icon type="question-circle-o" />
</Tooltip>
</span>
}
>
<Input disabled value={mockUrl} onChange={() => {}} />
</FormItem>
<FormItem {...formItemLayout} label="描述">
{getFieldDecorator('desc', {
initialValue: initFormValues.desc,
rules: [
{
required: false
}
]
})(<TextArea rows={8} />)}
</FormItem>
<FormItem
{...formItemLayout}
label={
<span>
tag 信息&nbsp;
<Tooltip title="定义 tag 信息,过滤接口">
<Icon type="question-circle-o" />
</Tooltip>
</span>
}
>
<ProjectTag tagMsg={tag} ref={this.tagSubmit} />
{/* <Tag tagMsg={tag} ref={this.tagSubmit} /> */}
</FormItem>
<FormItem
{...formItemLayout}
label={
<span>
mock严格模式&nbsp;
<Tooltip title="开启后 mock 请求会对 querybody form 的必须字段和 json schema 进行校验">
<Icon type="question-circle-o" />
</Tooltip>
</span>
}
>
{getFieldDecorator('strice', {
valuePropName: 'checked',
initialValue: initFormValues.strice
})(<Switch checkedChildren="开" unCheckedChildren="关" />)}
</FormItem>
<FormItem
{...formItemLayout}
label={
<span>
开启json5&nbsp;
<Tooltip title="开启后可在接口 body 和返回值中写 json 字段">
<Icon type="question-circle-o" />
</Tooltip>
</span>
}
>
{getFieldDecorator('is_json5', {
valuePropName: 'checked',
initialValue: initFormValues.is_json5
})(<Switch checkedChildren="开" unCheckedChildren="关" />)}
</FormItem>
<FormItem {...formItemLayout} label="默认开启消息通知">
{getFieldDecorator('switch_notice', {
valuePropName: 'checked',
initialValue: initFormValues.switch_notice
})(<Switch checkedChildren="开" unCheckedChildren="关" />)}
</FormItem>
<FormItem {...formItemLayout} label="权限">
{getFieldDecorator('project_type', {
rules: [
{
required: true
}
],
initialValue: initFormValues.project_type
})(
<RadioGroup>
<Radio value="private" className="radio">
<Icon type="lock" />私有<br />
<span className="radio-desc">只有组长和项目开发者可以索引并查看项目信息</span>
</Radio>
<br />
{projectMsg.role === 'admin' && <Radio value="public" className="radio">
<Icon type="unlock" />公开<br />
<span className="radio-desc">任何人都可以索引并查看项目信息</span>
</Radio>}
</RadioGroup>
)}
</FormItem>
</Form>
<div className="btnwrap-changeproject">
<Button
className="m-btn btn-save"
icon="save"
type="primary"
size="large"
onClick={this.handleOk}
>
</Button>
</div>
{/* 只有组长和管理员有权限删除项目 */}
{projectMsg.role === 'owner' || projectMsg.role === 'admin' ? (
<div className="danger-container">
<div className="title">
<h2 className="content">
<Icon type="exclamation-circle-o" /> 危险操作
</h2>
<Button onClick={this.toggleDangerOptions}>
<Icon type={this.state.showDangerOptions ? 'up' : 'down'} />
</Button>
</div>
{this.state.showDangerOptions ? (
<Card hoverable={true} className="card-danger">
<div className="card-danger-content">
<h3>删除项目</h3>
<p>项目一旦删除将无法恢复数据请慎重操作</p>
<p>只有组长和管理员有权限删除项目</p>
</div>
<Button
type="danger"
ghost
className="card-danger-btn"
onClick={this.showConfirm}
>
删除
</Button>
</Card>
) : null}
</div>
) : null}
</div>
</div>
);
}
}
export default Form.create()(ProjectMessage);

View File

@@ -0,0 +1,116 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Icon, Row, Col, Input } from 'antd';
import './ProjectTag.scss';
class ProjectTag extends Component {
static propTypes = {
tagMsg: PropTypes.array,
tagSubmit: PropTypes.func
};
constructor(props) {
super(props);
this.state = {
tag: [{ name: '', desc: '' }]
};
}
initState(curdata) {
let tag = [
{
name: '',
desc: ''
}
];
if (curdata && curdata.length !== 0) {
curdata.forEach(item => {
tag.unshift(item);
});
}
return { tag };
}
componentDidMount() {
this.handleInit(this.props.tagMsg);
}
handleInit(data) {
let newValue = this.initState(data);
this.setState({ ...newValue });
}
addHeader = (val, index, name, label) => {
let newValue = {};
newValue[name] = [].concat(this.state[name]);
newValue[name][index][label] = val;
let nextData = this.state[name][index + 1];
if (!(nextData && typeof nextData === 'object')) {
let data = { name: '', desc: '' };
newValue[name] = [].concat(this.state[name], data);
}
this.setState(newValue);
};
delHeader = (key, name) => {
let curValue = this.state[name];
let newValue = {};
newValue[name] = curValue.filter((val, index) => {
return index !== key;
});
this.setState(newValue);
};
handleChange = (val, index, name, label) => {
let newValue = this.state;
newValue[name][index][label] = val;
this.setState(newValue);
};
render() {
const commonTpl = (item, index, name) => {
const length = this.state[name].length - 1;
return (
<Row key={index} className="tag-item">
<Col span={6} className="item-name">
<Input
placeholder={`请输入 ${name} 名称`}
// style={{ width: '200px' }}
value={item.name || ''}
onChange={e => this.addHeader(e.target.value, index, name, 'name')}
/>
</Col>
<Col span={12}>
<Input
placeholder="请输入tag 描述信息"
style={{ width: '90%', marginRight: 8 }}
onChange={e => this.handleChange(e.target.value, index, name, 'desc')}
value={item.desc || ''}
/>
</Col>
<Col span={2} className={index === length ? ' tag-last-row' : null}>
{/* 新增的项中,只有最后一项没有有删除按钮 */}
<Icon
className="dynamic-delete-button delete"
type="delete"
onClick={e => {
e.stopPropagation();
this.delHeader(index, name);
}}
/>
</Col>
</Row>
);
};
return (
<div className="project-tag">
{this.state.tag.map((item, index) => {
return commonTpl(item, index, 'tag');
})}
</div>
);
}
}
export default ProjectTag;

View File

@@ -0,0 +1,18 @@
.project-tag {
.item-name {
margin-right: 16px;
}
.delete {
font-size: 16px;
}
.tag-item {
margin-bottom: 8px;
}
.tag-last-row {
display: none;
}
}

View File

@@ -0,0 +1,136 @@
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Form, Switch, Button, Icon, Tooltip, message } from 'antd';
import AceEditor from '../../../../components/AceEditor/AceEditor';
const FormItem = Form.Item;
import { updateProjectMock, getProject } from '../../../../reducer/modules/project';
const formItemLayout = {
labelCol: {
sm: { span: 4 }
},
wrapperCol: {
sm: { span: 16 }
}
};
const tailFormItemLayout = {
wrapperCol: {
sm: {
span: 16,
offset: 11
}
}
};
@connect(
state => {
return {
projectMsg: state.project.currProject
};
},
{
updateProjectMock,
getProject
}
)
@Form.create()
export default class ProjectMock extends Component {
static propTypes = {
form: PropTypes.object,
match: PropTypes.object,
projectId: PropTypes.number,
updateProjectMock: PropTypes.func,
projectMsg: PropTypes.object,
getProject: PropTypes.func
};
constructor(props) {
super(props);
this.state = {
is_mock_open: false,
project_mock_script: ''
};
}
handleSubmit = async () => {
let params = {
id: this.props.projectId,
project_mock_script: this.state.project_mock_script,
is_mock_open: this.state.is_mock_open
};
let result = await this.props.updateProjectMock(params);
if (result.payload.data.errcode === 0) {
message.success('保存成功');
await this.props.getProject(this.props.projectId);
} else {
message.success('保存失败, ' + result.payload.data.errmsg);
}
};
UNSAFE_componentWillMount() {
this.setState({
is_mock_open: this.props.projectMsg.is_mock_open,
project_mock_script: this.props.projectMsg.project_mock_script
});
}
// 是否开启
onChange = v => {
this.setState({
is_mock_open: v
});
};
handleMockJsInput = e => {
this.setState({
project_mock_script: e.text
});
};
render() {
return (
<div className="m-panel">
<Form>
<FormItem
label={
<span>
是否开启&nbsp;<a
target="_blank"
rel="noopener noreferrer"
href="https://hellosean1025.github.io/yapi/documents/project.html#%E5%85%A8%E5%B1%80mock"
>
<Tooltip title="点击查看文档">
<Icon type="question-circle-o" />
</Tooltip>
</a>
</span>
}
{...formItemLayout}
>
<Switch
checked={this.state.is_mock_open}
onChange={this.onChange}
checkedChildren="开"
unCheckedChildren="关"
/>
</FormItem>
<FormItem label="Mock脚本" {...formItemLayout}>
<AceEditor
data={this.state.project_mock_script}
onChange={this.handleMockJsInput}
style={{ minHeight: '500px' }}
/>
</FormItem>
<FormItem {...tailFormItemLayout}>
<Button type="primary" htmlType="submit" onClick={this.handleSubmit}>
保存
</Button>
</FormItem>
</Form>
</div>
);
}
}

View File

@@ -0,0 +1,106 @@
import React, { PureComponent as Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Form, Button, message } from 'antd';
const FormItem = Form.Item;
import './project-request.scss';
import AceEditor from 'client/components/AceEditor/AceEditor';
import { updateProjectScript, getProject } from '../../../../reducer/modules/project';
@connect(
state => {
return {
projectMsg: state.project.currProject
};
},
{
updateProjectScript,
getProject
}
)
@Form.create()
export default class ProjectRequest extends Component {
static propTypes = {
projectMsg: PropTypes.object,
updateProjectScript: PropTypes.func,
getProject: PropTypes.func,
projectId: PropTypes.number
};
UNSAFE_componentWillMount() {
this.setState({
pre_script: this.props.projectMsg.pre_script,
after_script: this.props.projectMsg.after_script
});
}
handleSubmit = async () => {
let result = await this.props.updateProjectScript({
id: this.props.projectId,
pre_script: this.state.pre_script,
after_script: this.state.after_script
});
if (result.payload.data.errcode === 0) {
message.success('保存成功');
await this.props.getProject(this.props.projectId);
} else {
message.success('保存失败, ' + result.payload.data.errmsg);
}
};
render() {
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 6 }
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 16 }
}
};
const tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0
},
sm: {
span: 16,
offset: 8
}
}
};
const { pre_script, after_script } = this.state;
return (
<div className="project-request">
<Form onSubmit={this.handleSubmit}>
<FormItem {...formItemLayout} label="Pre-request Script(请求参数处理脚本)">
<AceEditor
data={pre_script}
onChange={editor => this.setState({ pre_script: editor.text })}
fullScreen={true}
className="request-editor"
/>
</FormItem>
<FormItem {...formItemLayout} label="Pre-response Script(响应数据处理脚本)">
<AceEditor
data={after_script}
onChange={editor => this.setState({ after_script: editor.text })}
fullScreen={true}
className="request-editor"
/>
</FormItem>
<FormItem {...tailFormItemLayout}>
<Button onClick={this.handleSubmit} type="primary">
保存
</Button>
</FormItem>
</Form>
</div>
);
}
}

View File

@@ -0,0 +1,10 @@
.project-request{
background: #fff;
padding: 15px;
.request-editor{
min-height: 300px;
margin-top: 10px;
background-color: #eee;
}
}

View File

@@ -0,0 +1,99 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import './ProjectToken.scss';
import { getToken, updateToken } from '../../../../reducer/modules/project';
import { connect } from 'react-redux';
import { Icon, Tooltip, message, Modal } from 'antd';
import copy from 'copy-to-clipboard';
const confirm = Modal.confirm;
@connect(
state => {
return {
token: state.project.token
};
},
{
getToken,
updateToken
}
)
class ProjectToken extends Component {
static propTypes = {
projectId: PropTypes.number,
getToken: PropTypes.func,
token: PropTypes.string,
updateToken: PropTypes.func,
curProjectRole: PropTypes.string
};
async componentDidMount() {
await this.props.getToken(this.props.projectId);
}
copyToken = () => {
copy(this.props.token);
message.success('已经成功复制到剪切板');
};
updateToken = () => {
let that = this;
confirm({
title: '重新生成key',
content: '重新生成之后之前的key将无法使用确认重新生成吗',
okText: '确认',
cancelText: '取消',
async onOk() {
await that.props.updateToken(that.props.projectId);
message.success('更新成功');
},
onCancel() {}
});
};
render() {
return (
<div className="project-token">
<h2 className="token-title">工具标识</h2>
<div className="message">
每个项目都有唯一的标识token用户可以使用这个token值来请求项目 openapi.
</div>
<div className="token">
<span>
token: <span className="token-message">{this.props.token}</span>
</span>
<Tooltip title="复制">
<Icon className="token-btn" type="copy" onClick={this.copyToken} />
</Tooltip>
{this.props.curProjectRole === 'admin' || this.props.curProjectRole === 'owner' ? (
<Tooltip title="刷新">
<Icon className="token-btn" type="reload" onClick={this.updateToken} />
</Tooltip>
) : null}
</div>
<div className="blockquote">
为确保项目内数据的安全性和私密性请勿轻易将该token暴露给项目组外用户
</div>
<br />
<h2 className="token-title">open接口</h2>
<p><a target="_blank" rel="noopener noreferrer" href="https://hellosean1025.github.io/yapi/openapi.html">详细接口文档</a></p>
<div>
<ul className="open-api">
<li>/api/open/run_auto_test []</li>
<li>/api/open/import_data []</li>
<li>/api/interface/add []</li>
<li>/api/interface/save []</li>
<li>/api/interface/up []</li>
<li>/api/interface/get []</li>
<li>/api/interface/list []</li>
<li>/api/interface/list_menu []</li>
<li>/api/interface/add_cat []</li>
<li>/api/interface/getCatMenu []</li>
</ul>
</div>
</div>
);
}
}
export default ProjectToken;

View File

@@ -0,0 +1,70 @@
.project-token {
background: #fff;
padding: 15px;
min-height: 4.68rem;
.token{
padding: 16px;
font-size: 16px;
font-weight: 500;
}
.token-message{
padding: 8px;
margin-right: 8px;
background-color: #f5f5f5;
}
.open-api{
margin-top: 10px;
margin-left: 20px;
li{
margin-bottom: 10px;
}
}
.message{
padding: 16px 0 0 16px;
font-size: 14px;
}
.token-title{
font-size: 16px;
// background-color: #eee;
// border-radius: 4px;
// margin-bottom: 15px;
font-weight: 400;
margin-bottom: 0.16rem;
border-left: 3px solid #2395f1;
padding-left: 8px;
}
.blockquote{
border-left: 4px solid #ff561b;
// background-color: #f8f8f8;
padding: .12rem .24rem;
position: relative;
margin-left: 16px;
}
.blockquote:before {
content: '!';
display: block;
position: absolute;
left: -.12rem;
top: .12rem;
width: 20px;
height: 20px;
background-color: #ff561b;
color: #fff;
border-radius: 50%;
text-align: center;
font-family: 'Dosis', 'Source Sans Pro', 'Helvetica Neue', Arial, sans-serif;
}
.token-btn{
margin-right: 8px;
}
}

View File

@@ -0,0 +1,62 @@
import React, { PureComponent as Component } from 'react';
import { Tabs } from 'antd';
import PropTypes from 'prop-types';
import ProjectMessage from './ProjectMessage/ProjectMessage.js';
import ProjectEnv from './ProjectEnv/index.js';
import ProjectRequest from './ProjectRequest/ProjectRequest';
import ProjectToken from './ProjectToken/ProjectToken';
import ProjectMock from './ProjectMock/index.js';
import { connect } from 'react-redux';
const TabPane = Tabs.TabPane;
const plugin = require('client/plugin.js');
const routers = {}
import './Setting.scss';
@connect(state => {
return {
curProjectRole: state.project.currProject.role
};
})
class Setting extends Component {
static propTypes = {
match: PropTypes.object,
curProjectRole: PropTypes.string
};
render() {
const id = this.props.match.params.id;
plugin.emitHook('sub_setting_nav', routers);
return (
<div className="g-row">
<Tabs type="card" className="has-affix-footer tabs-large">
<TabPane tab="项目配置" key="1">
<ProjectMessage projectId={+id} />
</TabPane>
<TabPane tab="环境配置" key="2">
<ProjectEnv projectId={+id} />
</TabPane>
<TabPane tab="请求配置" key="3">
<ProjectRequest projectId={+id} />
</TabPane>
{this.props.curProjectRole !== 'guest' ? (
<TabPane tab="token配置" key="4">
<ProjectToken projectId={+id} curProjectRole={this.props.curProjectRole} />
</TabPane>
) : null}
<TabPane tab="全局mock脚本" key="5">
<ProjectMock projectId={+id} />
</TabPane>
{Object.keys(routers).map(key=>{
const C = routers[key].component;
return <TabPane tab={routers[key].name} key={routers[key].name}>
<C projectId={+id} />
</TabPane>
})}
</Tabs>
</div>
);
}
}
export default Setting;

View File

@@ -0,0 +1,227 @@
.form-item {
margin-bottom: .16rem;
}
.breakline {
margin-top: .18rem;
margin-bottom: .18rem;
border: 0;
border-top: 1px solid #eeeeee;
}
.card-danger {
border-color: #ff561b;
border-radius: 4px;
.ant-card-body {
display: flex;
align-items: center;
padding: .24rem !important;
}
.card-danger-content {
flex: 1;
}
.card-danger-btn {
flex-grow: 0;
flex-shrink: 1;
}
}
.setting-project-member {
.btn{
margin-left: 8px;
}
.m-user-name {
padding-right: 16px;
}
}
.setting-group {
margin-top: .48rem;
border-radius: 2px;
border-bottom: 1px solid #eee;
.ant-card-head {
background-color: #eee;
padding: 0 .08rem !important;
}
.ant-card-head-title {
font-size: .12rem;
float: inherit;
}
.ant-card-body {
padding: 0 !important;
}
.card-item {
padding: .1rem .15rem;
position: relative;
.item-img {
width: .2rem;
height: .2rem;
margin-right: .08rem;
vertical-align: middle;
}
.item-name {
position: absolute;
left: .43rem;
top: 50%;
transform: translateY(-50%);
}
.item-role {
position: absolute;
right: .15rem;
top: 50%;
transform: translateY(-50%);
}
}
.card-item + .card-item {
border-top: 1px solid #eee;
}
}
.project-setting {
.setting-logo {
text-align: right;
padding: .24rem;
cursor: pointer;
}
.setting-intro {
padding: .24rem;
height: 1.48rem;
display: flex;
align-items: center;
flex-wrap: wrap;
.ui-title {
font-size: .32rem;
font-weight: normal;
width: 100%;
}
.ui-desc {
font-size: .16rem;
}
}
.ui-logo {
width: 1rem;
height: 1rem;
border-radius: 50%;
font-size: .5rem;
color: #fff;
background-color: #2395f1;
line-height: 1rem;
box-shadow: 0 4px 6px rgba(50,50,93,.11), 0 1px 3px rgba(0,0,0,.08);
position: relative;
&:after {
opacity: 0;
content: '点击修改';
display: block;
transition: all .4s;
position: absolute;
left: 0;
top: 0;
border-radius: 50%;
font-size: .14rem;
color: #fff;
width: 100%;
height: 100%;
background-color: rgba(0,0,0, .25);
}
&:hover:after {
opacity: 1;
}
}
}
.change-project-container {
max-width: 320px;
.ant-popover-inner {
text-align: center;
}
.ant-popover-title {
padding: 8px .16rem;
height: auto;
}
.ant-radio-button-wrapper {
font-size: 16px;
border: none;
&:first-child {
border: none;
}
&:not(:first-child)::before {
display: none !important;
}
}
.ant-radio-button-wrapper-checked {
box-shadow: none;
color: #fff;
background-color: #2395f1;
border-radius: 4px;
}
.color {
// .ant-radio-button-wrapper {
// &:first-child {
// border: none;
// }
// }
.ant-radio-button-wrapper-checked {
border-radius: 0;
&:hover {
border: none;
box-shadow: none;
}
}
}
}
.danger-container {
margin-top: .48rem;
}
.btnwrap-changeproject {
text-align: center;
padding: .16rem 0;
background: #fff;
background-color: #fff;
margin: 0 -.4rem;
// background-image: linear-gradient(45deg, #d9d9d9 25%, transparent 0),linear-gradient(45deg, transparent 75%, #d9d9d9 0);
background-size: 4px 4px;
.btn-save {
font-size: .15rem;
font-weight: 200;
letter-spacing: 1px;
border: none;
box-shadow: 0 4px 6px rgba(50, 50, 93, 0.11), 0 1px 3px rgba(0, 0, 0, 0.08);
transform: translateY(0);
transition: all .2s;
&:hover {
transform: translateY(-1px);
}
&:active {
transform: translateY(1px);
}
}
}
.project-env{
// 环境配置中首个item的删除按钮定位调整
.ant-row-flex {
display: flex;
flex-flow: row wrap;
height: 60px;
}
}
// 危险操作
.danger-container {
.title {
margin-bottom: .48rem;
text-align: center;
.content {
color: rgba(39, 56, 72, 0.65);
margin-bottom: .16rem;
}
}
}
.radio.ant-radio-wrapper{
line-height: unset
}