Feat: [前台]:完成编辑功能。拖拽功能部分完成

This commit is contained in:
fanxb 2019-07-17 17:33:00 +08:00
parent 4699c5a509
commit 7e491ab10e
5 changed files with 506 additions and 379 deletions

View File

@ -13,7 +13,37 @@ export default class AddModal extends React.Component {
};
}
addOne = () => {
submit = () => {
const { currentEditNode } = this.props;
if (currentEditNode == null) {
this.addOne();
} else {
this.editOne(currentEditNode);
}
};
/**
* 编辑一个节点
* @param {*} node
*/
editOne(node) {
const { addName, addValue } = this.state;
const body = {
name: addName,
url: addValue
};
httpUtil.post("/bookmark/updateOne", body).then(() => {
message.success("编辑成功");
node.name = addName;
node.url = addValue;
this.close();
});
}
/**
* 新增一个节点
*/
addOne() {
const { currentAddFolder, addToTree, closeModal } = this.props;
const path = currentAddFolder == null ? "" : currentAddFolder.path + "." + currentAddFolder.bookmarkId;
if (this.state.addType === 2) {
@ -40,7 +70,7 @@ export default class AddModal extends React.Component {
closeModal();
});
}
};
}
close = () => {
const { closeModal } = this.props;
@ -49,8 +79,9 @@ export default class AddModal extends React.Component {
};
render() {
const { isShowModal } = this.props;
const { isShowModal, currentEditNode } = this.props;
const { addType, addName, addValue } = this.state;
const type = currentEditNode == null ? "add" : "edit";
const formItemLayout = {
labelCol: {
xs: { span: 4 },
@ -72,21 +103,23 @@ export default class AddModal extends React.Component {
fileList: []
};
return (
<Modal destroyOnClose title="新增" visible={isShowModal} onCancel={this.close} footer={false}>
<Modal destroyOnClose title={type === "add" ? "新增" : "编辑"} visible={isShowModal} onCancel={this.close} footer={false}>
<Form {...formItemLayout}>
<Form.Item label="类别">
<Radio.Group defaultValue={0} onChange={e => this.setState({ addType: e.target.value })}>
<Radio value={0}>书签</Radio>
<Radio value={1}>文件夹</Radio>
<Radio value={2}>上传书签html</Radio>
</Radio.Group>
</Form.Item>
{addType < 2 ? (
{type === "add" ? (
<Form.Item label="类别">
<Radio.Group defaultValue={0} onChange={e => this.setState({ addType: e.target.value })}>
<Radio value={0}>书签</Radio>
<Radio value={1}>文件夹</Radio>
<Radio value={2}>上传书签html</Radio>
</Radio.Group>
</Form.Item>
) : null}
{addType < 2 || type === "edit" ? (
<Form.Item label="名称">
<Input type="text" onChange={e => this.setState({ addName: e.target.value })} value={addName} />
</Form.Item>
) : null}
{addType === 0 ? (
{(addType === 0 && type === "add") || (type === "edit" && currentEditNode.type === 0) ? (
<Form.Item label="URL">
<Input type="text" value={addValue} onChange={e => this.setState({ addValue: e.target.value })} />
</Form.Item>
@ -100,7 +133,7 @@ export default class AddModal extends React.Component {
</Upload>
) : null}
<div style={{ textAlign: "center", paddingTop: "1em" }}>
<Button type="primary" onClick={this.addOne}>
<Button type="primary" onClick={this.submit}>
提交
</Button>
</div>

View File

@ -1,6 +1,6 @@
import httpUtil from "../../../util/httpUtil";
import React from "react";
import { Modal, Button, Tooltip, Tree } from "antd";
import { Modal, Button, Tooltip, Tree, message } from "antd";
import styles from "./index.module.less";
import IconFont from "../../../components/IconFont";
const { TreeNode } = Tree;
@ -44,6 +44,16 @@ export function onCheck(keys, data) {
});
}
/**
* 编辑一个节点
* @param {*} node 节点对象
* @param {*} e
*/
function editNode(node, e) {
e.stopPropagation();
this.setState({ isShowModal: true, currentEditNode: node });
}
/**
* 渲染树节点中节点内容
* @param {*} item
@ -66,6 +76,7 @@ export function renderNodeContent(item) {
/>
) : null}
{item.type === 1 ? <Button size="small" type="primary" icon="plus" shape="circle" onClick={this.addOne.bind(this, item)} /> : null}
<Button size="small" type="primary" icon="edit" shape="circle" onClick={editNode.bind(this, item)} />
<Button size="small" type="danger" icon="delete" shape="circle" onClick={deleteOne.bind(this, item)} />
</div>
);
@ -179,3 +190,77 @@ function deleteTreeData(treeData, set) {
}
}
}
export function onDragEnter(info) {
// console.log(info);
}
/**
* 节点拖拽
* @param {*} info
*/
export function onDrop(info) {
const { treeData } = this.state;
const target = info.node.props.dataRef;
if (!info.dropToGap && target.type === "0") {
message.error("只能移动到文件夹中");
return;
}
const current = info.dragNode.props.dataRef;
const body = {
bookmarkId: current.bookmarkId,
sourcePath: current.path,
targetPath: "",
//-1 表示排在最后
sort: -1
};
const currentBelowList = current.path === "" ? treeData : getBelowList(treeData, current);
currentBelowList.splice(currentBelowList.indexOf(current), 1);
if (info.dropToGap) {
body.targetPath = target.path;
const targetBelowList = target.path === "" ? treeData : getBelowList(treeData, target);
const index = targetBelowList.indexOf(target);
if (info.dropPosition > index) {
body.sort = target.sort + 1;
insertToArray(current, index + 1, targetBelowList);
} else {
body.sort = target.sort;
insertToArray(current, index, targetBelowList);
}
current.sort = body.sort;
} else {
body.targetPath = target.path + "." + target.bookmarkId;
if (target.children) {
target.children.push(current);
}
}
this.setState({ treeData: [...treeData] });
}
/**
* 获取node所属list
* @param {*} tree 树结构
* @param {*} node node
*/
function getBelowList(treeList, node) {
for (let i in treeList) {
let item = treeList[i];
if (item.type === 1) {
if (item.path + "." + item.bookmarkId === node.path) {
return item.children;
} else if (item.children) {
return getBelowList(item.children, node);
}
}
}
}
function insertToArray(item, index, arr) {
const length = arr.length;
let i = length;
for (; i > index; i--) {
arr[i] = arr[i - 1];
arr[i].sort++;
}
arr[i] = item;
}

View File

@ -1,151 +1,160 @@
import React from "react";
import { Tree, Empty, Button } from "antd";
import MainLayout from "../../../layout/MainLayout";
import httpUtil from "../../../util/httpUtil";
import styles from "./index.module.less";
import { batchDelete, renderTreeNodes, onExpand, closeAll, onCheck } from "./function.js";
import AddModal from "./AddModal";
export default class OverView extends React.Component {
constructor(props) {
super(props);
this.state = {
treeData: [],
isEdit: false,
isLoading: true,
checkedKeys: [],
expandKeys: [],
//
isShowModal: false,
currentAddFolder: null
};
}
/**
* 初始化第一级书签
*/
componentDidMount() {
httpUtil
.get("/bookmark/currentUser/path?path=")
.then(res => {
this.setState({ treeData: res, isLoading: false });
})
.catch(() => this.setState({ isLoading: false }));
}
/**
* 异步加载
*/
loadData = e =>
new Promise(resolve => {
const item = e.props.dataRef;
const newPath = item.path + "." + item.bookmarkId;
httpUtil.get("/bookmark/currentUser/path?path=" + newPath).then(res => {
item.children = res;
this.setState({ treeData: [...this.state.treeData] });
resolve();
});
});
/**
* 节点选择
* @param {*} key
* @param {*} e
*/
treeNodeSelect(key, e) {
if (e.nativeEvent.delegateTarget.name === "copy") {
return;
}
const { expandKeys } = this.state;
const item = e.node.props.dataRef;
if (item.type === 0) {
window.open(item.url);
} else {
const id = item.bookmarkId.toString();
const index = expandKeys.indexOf(id);
index === -1 ? expandKeys.push(id) : expandKeys.splice(index, 1);
this.setState({ expandKeys: [...expandKeys] });
}
}
/**
* 将新增的数据加入到state中
*/
addToTree = node => {
const { currentAddFolder, treeData } = this.state;
if (currentAddFolder === null) {
treeData.push(node);
} else {
//children
if (currentAddFolder.children) {
currentAddFolder.children.push(node);
this.setState({ treeData: [...treeData] });
}
}
};
/**
* 关闭新增书签弹窗
*/
closeAddModal = () => {
this.setState({ isShowModal: false });
};
/**
* 新增书签
*/
addOne = (item, e) => {
e.stopPropagation();
this.setState({ currentAddFolder: item, isShowModal: true });
};
render() {
const { isLoading, isEdit, treeData, expandKeys, checkedKeys, isShowModal, currentAddFolder } = this.state;
return (
<MainLayout>
<div className={styles.main}>
<div className={styles.header}>
<div className={styles.left}>
<span className={styles.myTree}>我的书签树</span>
{isEdit ? <Button size="small" type="primary" icon="plus" shape="circle" onClick={this.addOne.bind(this, null)} /> : null}
{expandKeys.length > 0 ? (
<Button type="primary" size="small" onClick={closeAll.bind(this)}>
收起
</Button>
) : null}
</div>
<div className={styles.right}>
{isEdit ? (
<React.Fragment>
<Button size="small" type="danger" onClick={batchDelete.bind(this)}>
删除选中
</Button>
</React.Fragment>
) : null}
<Button size="small" type="primary" onClick={() => this.setState({ isEdit: !isEdit })}>
{isEdit ? "完成" : "编辑"}
</Button>
</div>
</div>
<Tree
showIcon
checkedKeys={checkedKeys}
onCheck={onCheck.bind(this)}
expandedKeys={expandKeys}
loadData={this.loadData}
onExpand={onExpand.bind(this)}
defaultExpandParent
checkable={isEdit}
onSelect={this.treeNodeSelect.bind(this)}
onDoubleClick={this.copyUrl}
blockNode
>
{renderTreeNodes.call(this, treeData)}
</Tree>
{isLoading === false && treeData.length === 0 ? <Empty description="还没有数据" /> : null}
<AddModal isShowModal={isShowModal} currentAddFolder={currentAddFolder} closeModal={this.closeAddModal} addToTree={this.addToTree} />
</div>
</MainLayout>
);
}
}
import React from "react";
import { Tree, Empty, Button } from "antd";
import MainLayout from "../../../layout/MainLayout";
import httpUtil from "../../../util/httpUtil";
import styles from "./index.module.less";
import { batchDelete, renderTreeNodes, onExpand, closeAll, onCheck, onDragEnter, onDrop } from "./function.js";
import AddModal from "./AddModal";
export default class OverView extends React.Component {
constructor(props) {
super(props);
this.state = {
treeData: [],
isEdit: false,
isLoading: true,
checkedKeys: [],
expandKeys: [],
///
isShowModal: false,
currentAddFolder: null,
currentEditNode: null
};
}
/**
* 初始化第一级书签
*/
componentDidMount() {
httpUtil
.get("/bookmark/currentUser/path?path=")
.then(res => {
this.setState({ treeData: res, isLoading: false });
})
.catch(() => this.setState({ isLoading: false }));
}
/**
* 异步加载
*/
loadData = e =>
new Promise(resolve => {
const item = e.props.dataRef;
const newPath = item.path + "." + item.bookmarkId;
httpUtil.get("/bookmark/currentUser/path?path=" + newPath).then(res => {
item.children = res;
this.setState({ treeData: [...this.state.treeData] });
resolve();
});
});
/**
* 节点选择
* @param {*} key
* @param {*} e
*/
treeNodeSelect(key, e) {
if (e.nativeEvent.delegateTarget && e.nativeEvent.delegateTarget.name === "copy") {
return;
}
const { expandKeys } = this.state;
const item = e.node.props.dataRef;
if (item.type === 0) {
window.open(item.url);
} else {
const id = item.bookmarkId.toString();
const index = expandKeys.indexOf(id);
index === -1 ? expandKeys.push(id) : expandKeys.splice(index, 1);
this.setState({ expandKeys: [...expandKeys] });
}
}
/**
* 将新增的数据加入到state中
*/
addToTree = node => {
const { currentAddFolder, treeData } = this.state;
if (currentAddFolder === null) {
treeData.push(node);
} else {
//children
if (currentAddFolder.children) {
currentAddFolder.children.push(node);
this.setState({ treeData: [...treeData] });
}
this.setState({ currentAddFolder: null });
}
};
/**
* 关闭新增书签弹窗
*/
closeAddModal = () => {
this.setState({ isShowModal: false, currentAddFolder: null, currentEditNode: null });
};
/**
* 新增书签
*/
addOne = (item, e) => {
e.stopPropagation();
this.setState({ currentAddFolder: item, isShowModal: true });
};
render() {
const { isLoading, isEdit, treeData, expandKeys, checkedKeys, isShowModal, currentAddFolder, currentEditNode } = this.state;
return (
<MainLayout>
<div className={styles.main}>
<div className={styles.header}>
<div className={styles.left}>
<span className={styles.myTree}>我的书签树</span>
{isEdit ? <Button size="small" type="primary" icon="plus" shape="circle" onClick={this.addOne.bind(this, null)} /> : null}
{expandKeys.length > 0 ? (
<Button type="primary" size="small" onClick={closeAll.bind(this)}>
收起
</Button>
) : null}
</div>
<div className={styles.right}>
{isEdit ? (
<React.Fragment>
<Button size="small" type="danger" onClick={batchDelete.bind(this)}>
删除选中
</Button>
</React.Fragment>
) : null}
<Button size="small" type="primary" onClick={() => this.setState({ isEdit: !isEdit })}>
{isEdit ? "完成" : "编辑"}
</Button>
</div>
</div>
<Tree
showIcon
checkedKeys={checkedKeys}
onCheck={onCheck.bind(this)}
expandedKeys={expandKeys}
loadData={this.loadData}
onExpand={onExpand.bind(this)}
checkable={isEdit}
onSelect={this.treeNodeSelect.bind(this)}
draggable
onDragEnter={onDragEnter.bind(this)}
onDrop={onDrop.bind(this)}
blockNode
>
{renderTreeNodes.call(this, treeData)}
</Tree>
{isLoading === false && treeData.length === 0 ? <Empty description="还没有数据" /> : null}
<AddModal
isShowModal={isShowModal}
currentAddFolder={currentAddFolder}
currentEditNode={currentEditNode}
closeModal={this.closeAddModal}
addToTree={this.addToTree}
/>
</div>
</MainLayout>
);
}
}

View File

@ -1,153 +1,153 @@
import React from "react";
import IconFont from "../../../components/IconFont";
import { Button, Input, message } from "antd";
import { LoginLayout, REGISTER_TYPE, RESET_PASSWORD_TYPE } from "../../../layout/LoginLayout";
import styles from "./index.module.less";
import axios from "../../../util/httpUtil";
export default class Register extends React.Component {
constructor(props) {
super(props);
console.log(props);
let type = props.location.pathname.split("/").reverse()[0];
this.state = {
current: type === "register" ? REGISTER_TYPE : RESET_PASSWORD_TYPE,
username: "",
email: "",
password: "",
repassword: "",
authCode: "",
authCodeText: "获取验证码",
isCountDown: false
};
}
componentWillUnmount() {
if (this.timer != null) {
clearInterval(this.timer);
}
}
/**
* 获取验证码
*/
getCode = () => {
if (this.state.isCountDown) {
return;
}
axios.get("/user/authCode?email=" + this.state.email).then(() => {
message.success("发送成功,请注意查收(检查垃圾箱)");
let count = 60;
this.setState({ authCodeText: `${count}s后重试`, isCountDown: true });
this.timer = setInterval(() => {
count--;
if (count === 0) {
this.setState({ isCountDown: false, authCodeText: "获取验证码" });
clearInterval(this.timer);
return;
}
this.setState({ authCodeText: `${count}s后重试` });
}, 1000);
});
};
changeData = e => {
this.setState({ [e.target.name]: e.target.value });
};
/**
* 提交表单
*/
submit = () => {
const { current, username, email, password, repassword, authCode } = this.state;
if (password !== repassword) {
message.error("两次密码不一致");
return;
}
let form = { username, email, password, authCode };
if (current === REGISTER_TYPE) {
axios
.put("/user", form)
.then(() => {
message.success("注册成功");
setTimeout(() => this.props.history.replace("/public/login"), 500);
})
.catch(error => message.error(error));
} else {
delete form.username;
axios
.post("/user/resetPassword", form)
.then(() => {
message.success("操作成功");
console.log(this.location);
setTimeout(() => this.props.history.replace("/public/login"), 500);
})
.catch(error => message.error(error));
}
};
render() {
const { current, username, email, password, repassword, authCode, authCodeText, isCountDown } = this.state;
return (
<LoginLayout type={current}>
<div className={styles.main}>
{current === REGISTER_TYPE ? (
<Input
type="text"
size="large"
name="username"
value={username}
onChange={this.changeData}
addonBefore={<IconFont type="icon-person" style={{ fontSize: "0.3rem" }} />}
placeholder="用户名"
/>
) : null}
<Input
type="email"
size="large"
name="email"
value={email}
onChange={this.changeData}
addonBefore={<IconFont type="icon-mail" style={{ fontSize: "0.3rem" }} />}
placeholder="邮箱"
/>
<Input
type="password"
size="large"
name="password"
value={password}
onChange={this.changeData}
addonBefore={<IconFont type="icon-password" style={{ fontSize: "0.3rem" }} />}
placeholder="密码"
/>
<Input
type="password"
size="large"
name="repassword"
value={repassword}
onChange={this.changeData}
addonBefore={<IconFont type="icon-password" style={{ fontSize: "0.3rem" }} />}
placeholder="重复密码"
/>
<Input
type="text"
size="large"
name="authCode"
value={authCode}
onChange={this.changeData}
addonBefore={<IconFont type="icon-yanzhengma54" style={{ fontSize: "0.3rem" }} />}
addonAfter={
<span style={{ cursor: isCountDown ? "" : "pointer" }} onClick={this.getCode}>
{authCodeText}
</span>
}
placeholder="验证码"
/>
<Button type="primary" className={styles.submit} onClick={this.submit} block>
{current === REGISTER_TYPE ? "注册" : "重置密码"}
</Button>
</div>
</LoginLayout>
);
}
}
import React from "react";
import IconFont from "../../../components/IconFont";
import { Button, Input, message } from "antd";
import { LoginLayout, REGISTER_TYPE, RESET_PASSWORD_TYPE } from "../../../layout/LoginLayout";
import styles from "./index.module.less";
import axios from "../../../util/httpUtil";
export default class Register extends React.Component {
constructor(props) {
super(props);
console.log(props);
let type = props.location.pathname.split("/").reverse()[0];
this.state = {
current: type === "register" ? REGISTER_TYPE : RESET_PASSWORD_TYPE,
username: "",
email: "",
password: "",
repassword: "",
authCode: "",
authCodeText: "获取验证码",
isCountDown: false
};
}
componentWillUnmount() {
if (this.timer != null) {
clearInterval(this.timer);
}
}
/**
* 获取验证码
*/
getCode = () => {
if (this.state.isCountDown) {
return;
}
let count = 60;
this.setState({ authCodeText: `${count}s后重试`, isCountDown: true });
axios.get("/user/authCode?email=" + this.state.email).then(() => {
message.success("发送成功,请注意查收(检查垃圾箱)");
this.timer = setInterval(() => {
count--;
if (count === 0) {
this.setState({ isCountDown: false, authCodeText: "获取验证码" });
clearInterval(this.timer);
return;
}
this.setState({ authCodeText: `${count}s后重试` });
}, 1000);
});
};
changeData = e => {
this.setState({ [e.target.name]: e.target.value });
};
/**
* 提交表单
*/
submit = () => {
const { current, username, email, password, repassword, authCode } = this.state;
if (password !== repassword) {
message.error("两次密码不一致");
return;
}
let form = { username, email, password, authCode };
if (current === REGISTER_TYPE) {
axios
.put("/user", form)
.then(() => {
message.success("注册成功");
setTimeout(() => this.props.history.replace("/public/login"), 500);
})
.catch(error => message.error(error));
} else {
delete form.username;
axios
.post("/user/resetPassword", form)
.then(() => {
message.success("操作成功");
console.log(this.location);
setTimeout(() => this.props.history.replace("/public/login"), 500);
})
.catch(error => message.error(error));
}
};
render() {
const { current, username, email, password, repassword, authCode, authCodeText, isCountDown } = this.state;
return (
<LoginLayout type={current}>
<div className={styles.main}>
{current === REGISTER_TYPE ? (
<Input
type="text"
size="large"
name="username"
value={username}
onChange={this.changeData}
addonBefore={<IconFont type="icon-person" style={{ fontSize: "0.3rem" }} />}
placeholder="用户名"
/>
) : null}
<Input
type="email"
size="large"
name="email"
value={email}
onChange={this.changeData}
addonBefore={<IconFont type="icon-mail" style={{ fontSize: "0.3rem" }} />}
placeholder="邮箱"
/>
<Input
type="password"
size="large"
name="password"
value={password}
onChange={this.changeData}
addonBefore={<IconFont type="icon-password" style={{ fontSize: "0.3rem" }} />}
placeholder="密码"
/>
<Input
type="password"
size="large"
name="repassword"
value={repassword}
onChange={this.changeData}
addonBefore={<IconFont type="icon-password" style={{ fontSize: "0.3rem" }} />}
placeholder="重复密码"
/>
<Input
type="text"
size="large"
name="authCode"
value={authCode}
onChange={this.changeData}
addonBefore={<IconFont type="icon-yanzhengma54" style={{ fontSize: "0.3rem" }} />}
addonAfter={
<span style={{ cursor: isCountDown ? "" : "pointer" }} onClick={this.getCode}>
{authCodeText}
</span>
}
placeholder="验证码"
/>
<Button type="primary" className={styles.submit} onClick={this.submit} block>
{current === REGISTER_TYPE ? "注册" : "重置密码"}
</Button>
</div>
</LoginLayout>
);
}
}

View File

@ -1,60 +1,60 @@
import { notification } from "antd";
import axios from "axios";
//定义http实例
const instance = axios.create({
baseURL: "/bookmark/api",
timeout: 15000
});
//实例添加请求拦截器
instance.interceptors.request.use(
req => {
req.headers["jwt-token"] = window.token;
return req;
},
error => {
console.log(error);
}
);
//实例添加响应拦截器
instance.interceptors.response.use(
function(res) {
const data = res.data;
if (data.code === 1) {
return data.data;
} else if (data.code === -2) {
return Promise.reject(data.message);
} else {
showError(data);
return Promise.reject(data.message);
}
},
function(error) {
console.log(error);
showError(error.response);
return Promise.reject(JSON.stringify(error));
}
);
function showError(response) {
let description,
message = "出问题啦";
if (response) {
description = response.message;
if (response.code === -1) {
let redirect = encodeURIComponent(window.location.pathname + window.location.search);
window.reactHistory.replace("/public/login?redirect=" + redirect);
}
} else {
description = "无网络连接";
}
notification.open({
message,
description,
duration: 2
});
}
export default instance;
import { notification } from "antd";
import axios from "axios";
//定义http实例
const instance = axios.create({
baseURL: "/bookmark/api",
timeout: 15000
});
//实例添加请求拦截器
instance.interceptors.request.use(
req => {
req.headers["jwt-token"] = window.token;
return req;
},
error => {
console.log(error);
}
);
//实例添加响应拦截器
instance.interceptors.response.use(
function(res) {
const data = res.data;
if (data.code === 1) {
return data.data;
} else if (data.code === -2) {
return Promise.reject(data.message);
} else {
showError(data);
return Promise.reject(data.message);
}
},
function(error) {
console.log(error);
showError(error.response);
return Promise.reject(JSON.stringify(error));
}
);
function showError(response) {
let description,
message = "出问题啦";
if (response) {
description = response.message;
if (response.code === -1) {
let redirect = encodeURIComponent(window.location.pathname + window.location.search);
window.reactHistory.replace("/public/login?redirect=" + redirect);
}
} else {
description = "无网络连接";
}
notification.open({
message,
description,
duration: 2
});
}
export default instance;