Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Customise the general context plugin's selector modal. (#163) #165

Merged
merged 1 commit into from
Dec 17, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
210 changes: 210 additions & 0 deletions src/routes/Plugin/PluginRuleHandle/GeneralContextRuleHandle.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import React, { Component } from "react";
import { Tabs, Form, Select, Row, Col, Input, Button } from "antd";
import styles from "../index.less";
import { getIntlContent } from "../../../utils/IntlUtils";
import { titleCase, guid } from "../../../utils/utils";

const FormItem = Form.Item;
const { Option } = Select;
const { TabPane } = Tabs;

const handlers = ["dubbo", "grpc", "sofa", "motan"];
const contextType = ["addGeneralContext", "transmitHeaderToGeneralContext"];

export default class GeneralContextRuleHandle extends Component {
constructor(props) {
super(props);
props.onRef(this);
const { handle } = props;
const keys = {};
const handleData = {};
handlers.forEach(v => {
keys[v] = [];
});
// format handle
try {
const handleJSON = JSON.parse(handle);
handlers.forEach(handleName => {
if (Array.isArray(handleJSON[handleName])) {
keys[handleName] = handleJSON[handleName].map(data => {
const Guid = guid();
if (!handleData[handleName]) {
handleData[handleName] = {};
}
handleData[handleName][Guid] = data;
return Guid;
});
} else {
keys[handleName] = [guid()];
}
});
} catch (e) {
handlers.forEach(handleName => {
keys[handleName] = [guid()];
});
}
this.keys = keys;
this.handleData = handleData;
this.state = {
currentType: handlers[0]
};
}

handleAddRow = handler => {
const {
form: { setFieldsValue, getFieldValue }
} = this.props;
const keys = Object.assign({}, getFieldValue("keys"));
keys[handler].push(guid());
setFieldsValue({ keys });
};

handleDeleteRow = (handler, key) => {
const {
form: { setFieldsValue, getFieldValue }
} = this.props;
const keys = Object.assign({}, getFieldValue("keys"));
if (keys[handler].length === 1) {
return;
}
keys[handler] = keys[handler].filter(v => v !== key);
setFieldsValue({ keys });
};

getData = values => {
const { handle, keys } = values;
const handleData = {};
handlers.forEach(v => {
handleData[v] = keys[v].map(key => handle[v][key]);
});
return JSON.stringify(handleData);
};

render() {
const { handleData } = this;
const { currentType } = this.state;
const { form } = this.props;
const { getFieldDecorator, getFieldValue } = form;
getFieldDecorator("keys", {
initialValue: this.keys
});
const keys = getFieldValue("keys");

return (
<div className={styles.handleWrap} style={{ padding: "0px 40px" }}>
<div className={styles.header}>
<h3 style={{ width: 60, marginTop: 10 }}>
{getIntlContent("SHENYU.COMMON.DEAL")}:{" "}
</h3>
</div>
<Tabs
style={{ marginLeft: 10, width: "100%" }}
defaultActiveKey={currentType}
onChange={this.handleTabChange}
>
{handlers.map(handler => (
<TabPane tab={titleCase(handler)} key={handler}>
{keys[handler].map((key, keyIndex) => (
<Row gutter={16} key={key}>
<Col span={7}>
<FormItem>
{getFieldDecorator(
`handle['${handler}']['${key}']['generalContextType']`,
{
initialValue:
handleData?.[handler]?.[key]?.generalContextType
}
)(
<Select
placeholder={`${titleCase(
`Select ${handler} Context Type`
)}`}
>
{contextType.map(v => (
<Option value={v} key={v} title={v}>
{v}
</Option>
))}
</Select>
)}
</FormItem>
</Col>
<Col span={6}>
<FormItem>
{getFieldDecorator(
`handle['${handler}']['${key}']['generalContextKey']`,
{
initialValue:
handleData?.[handler]?.[key]?.generalContextKey
}
)(
<Input
placeholder={`${titleCase(
`Set ${handler} Context Key`
)}`}
/>
)}
</FormItem>
</Col>
<Col span={6}>
<FormItem>
{getFieldDecorator(
`handle['${handler}']['${key}']['generalContextValue']`,
{
initialValue:
handleData?.[handler]?.[key]?.generalContextValue
}
)(
<Input
placeholder={`${titleCase(
`Set ${handler} Context Value`
)}`}
/>
)}
</FormItem>
</Col>
<Col span={5}>
<FormItem>
<Button
type="danger"
style={{ marginRight: 16 }}
onClick={() => this.handleDeleteRow(handler, key)}
>
{getIntlContent("SHENYU.COMMON.DELETE.NAME")}
</Button>
{keyIndex === 0 && (
<Button
onClick={() => this.handleAddRow(handler)}
type="primary"
>
{getIntlContent("SHENYU.COMMON.ADD")}
</Button>
)}
</FormItem>
</Col>
</Row>
))}
</TabPane>
))}
</Tabs>
</div>
);
}
}
2 changes: 2 additions & 0 deletions src/routes/Plugin/PluginRuleHandle/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@ import RequestRuleHandle from "./RequestRuleHandle";
import HystrixRuleHandle from "./HystrixRuleHandle";
import ParamPluginRuleHandle from "./ParamPluginRuleHandle";
import ResponseRuleHandle from "./ResponseRuleHandle";
import GeneralContextRuleHandle from "./GeneralContextRuleHandle";

export default {
request: RequestRuleHandle,
generalContext: GeneralContextRuleHandle,
modifyResponse: ResponseRuleHandle,
hystrix: HystrixRuleHandle,
paramMapping: ParamPluginRuleHandle
Expand Down
80 changes: 49 additions & 31 deletions src/utils/utils.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
Expand All @@ -16,18 +15,17 @@
* limitations under the License.
*/

import { parse, stringify } from 'qs';
import { parse, stringify } from "qs";

export function fixedZero(val) {
return val * 1 < 10 ? `0${val}` : val;
}


export function getPlainNode(nodeList, parentPath = '') {
export function getPlainNode(nodeList, parentPath = "") {
const arr = [];
nodeList.forEach(node => {
const item = node;
item.path = `${parentPath}/${item.path || ''}`.replace(/\/+/g, '/');
item.path = `${parentPath}/${item.path || ""}`.replace(/\/+/g, "/");
item.exact = true;
if (item.children && !item.component) {
arr.push(...getPlainNode(item.children, item.path));
Expand All @@ -45,43 +43,46 @@ function accMul(arg1, arg2) {
let m = 0;
const s1 = arg1.toString();
const s2 = arg2.toString();
m += s1.split('.').length > 1 ? s1.split('.')[1].length : 0;
m += s2.split('.').length > 1 ? s2.split('.')[1].length : 0;
return (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) / 10 ** m;
m += s1.split(".").length > 1 ? s1.split(".")[1].length : 0;
m += s2.split(".").length > 1 ? s2.split(".")[1].length : 0;
return (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) / 10 ** m;
}

export function digitUppercase(n) {
const fraction = ['角', '分'];
const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
const unit = [['元', '万', '亿'], ['', '拾', '佰', '仟', '万']];
const fraction = ["角", "分"];
const digit = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
const unit = [["元", "万", "亿"], ["", "拾", "佰", "仟", "万"]];
let num = Math.abs(n);
let s = '';
let s = "";
fraction.forEach((item, index) => {
s += (digit[Math.floor(accMul(num, 10 * 10 ** index)) % 10] + item).replace(/零./, '');
s += (digit[Math.floor(accMul(num, 10 * 10 ** index)) % 10] + item).replace(
/零./,
""
);
});
s = s || '整';
s = s || "整";
num = Math.floor(num);
for (let i = 0; i < unit[0].length && num > 0; i += 1) {
let p = '';
let p = "";
for (let j = 0; j < unit[1].length && num > 0; j += 1) {
p = digit[num % 10] + unit[1][j] + p;
num = Math.floor(num / 10);
}
s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
s = p.replace(/(零.)*零$/, "").replace(/^$/, "零") + unit[0][i] + s;
}

return s
.replace(/(零.)*零元/, '元')
.replace(/(零.)+/g, '零')
.replace(/^整$/, '零元整');
.replace(/(零.)*零元/, "元")
.replace(/(零.)+/g, "零")
.replace(/^整$/, "零元整");
}

function getRelation(str1, str2) {
if (str1 === str2) {
console.warn('Two path are equal!'); // eslint-disable-line
console.warn("Two path are equal!"); // eslint-disable-line
}
const arr1 = str1.split('/');
const arr2 = str2.split('/');
const arr1 = str1.split("/");
const arr2 = str2.split("/");
if (arr2.every((item, index) => item === arr1[index])) {
return 1;
} else if (arr1.every((item, index) => item === arr2[index])) {
Expand Down Expand Up @@ -116,27 +117,29 @@ export function getRoutes(path, routerData) {
routePath => routePath.indexOf(path) === 0 && routePath !== path
);
// Replace path to '' eg. path='user' /user/name => name
routes = routes.map(item => item.replace(path, ''));
routes = routes.map(item => item.replace(path, ""));
// Get the route to be rendered to remove the deep rendering
const renderArr = getRenderArr(routes);
// Conversion and stitching parameters
const renderRoutes = renderArr.map(item => {
const exact = !routes.some(route => route !== item && getRelation(route, item) === 1);
const exact = !routes.some(
route => route !== item && getRelation(route, item) === 1
);
return {
exact,
...routerData[`${path}${item}`],
key: `${path}${item}`,
path: `${path}${item}`,
path: `${path}${item}`
};
});
return renderRoutes;
}

export function getPageQuery() {
return parse(window.location.href.split('?')[1]);
return parse(window.location.href.split("?")[1]);
}

export function getQueryPath(path = '', query = {}) {
export function getQueryPath(path = "", query = {}) {
const search = stringify(query);
if (search.length) {
return `${path}?${search}`;
Expand All @@ -158,11 +161,26 @@ export function isUrl(path) {
* @param {function} func
* @param {string} tree children attribute
*/
export function filterTree(treeNode, func = () => {}, treeChildrenAtrr = "children") {
export function filterTree(
treeNode,
func = () => {},
treeChildrenAtrr = "children"
) {
func(treeNode);
if (treeNode[treeChildrenAtrr] && treeNode[treeChildrenAtrr].length > 0) {
treeNode[treeChildrenAtrr].forEach((e) => {
filterTree(e, func);
})
treeNode[treeChildrenAtrr].forEach(e => {
filterTree(e, func);
});
}
}

export function titleCase(str) {
return str.toLowerCase().replace(/( |^)[a-z]/g, L => L.toUpperCase());
}

export function guid() {
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
return `${S4() + S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`;
}