1
0
mirror of https://github.com/haiwen/seahub.git synced 2025-07-17 16:52:09 +00:00
seahub/frontend/src/components/rename.js

104 lines
2.4 KiB
JavaScript
Raw Normal View History

2018-12-12 02:12:19 +00:00
import React from 'react';
import PropTypes from 'prop-types';
import { gettext } from '../utils/constants';
2023-09-05 12:21:24 +00:00
import { Utils } from '../utils/utils';
import toaster from './toast';
2018-12-12 02:12:19 +00:00
const propTypes = {
hasSuffix: PropTypes.bool,
2018-12-12 02:12:19 +00:00
name: PropTypes.string.isRequired,
onRenameConfirm: PropTypes.func.isRequired,
onRenameCancel: PropTypes.func.isRequired,
};
class Rename extends React.Component {
2018-12-12 02:12:19 +00:00
constructor(props) {
super(props);
this.state = {
name: props.name
};
2023-09-05 12:21:24 +00:00
this.inputRef = React.createRef();
2018-12-12 02:12:19 +00:00
}
componentDidMount() {
2023-09-05 12:21:24 +00:00
this.inputRef.current.focus();
if (this.props.hasSuffix) {
2018-12-12 02:12:19 +00:00
var endIndex = this.props.name.lastIndexOf('.');
2023-09-05 12:21:24 +00:00
this.inputRef.current.setSelectionRange(0, endIndex, 'forward');
2018-12-12 02:12:19 +00:00
} else {
2023-09-05 12:21:24 +00:00
this.inputRef.current.setSelectionRange(0, -1);
2018-12-12 02:12:19 +00:00
}
}
onChange = (e) => {
this.setState({name: e.target.value});
}
2023-09-05 12:21:24 +00:00
onKeyDown = (e) => {
if (e.keyCode === Utils.keyCodes.enter) {
2018-12-12 02:12:19 +00:00
this.onRenameConfirm(e);
2023-09-05 12:21:24 +00:00
} else if (e.keyCode === Utils.keyCodes.esc) {
this.onRenameCancel(e);
2018-12-12 02:12:19 +00:00
}
2023-09-05 12:21:24 +00:00
e.nativeEvent.stopImmediatePropagation();
2018-12-12 02:12:19 +00:00
}
onRenameConfirm = (e) => {
e.nativeEvent.stopImmediatePropagation();
let newName = this.state.name.trim();
if (newName === this.props.name) {
this.props.onRenameCancel();
return;
}
let { isValid, errMessage } = this.validateInput();
if (!isValid) {
toaster.danger(errMessage);
} else {
this.props.onRenameConfirm(newName);
}
2018-12-12 02:12:19 +00:00
}
onRenameCancel = (e) => {
e.nativeEvent.stopImmediatePropagation();
this.props.onRenameCancel();
}
validateInput = () => {
let newName = this.state.name.trim();
let isValid = true;
let errMessage = '';
if (!newName) {
isValid = false;
errMessage = gettext('Name is required.');
return { isValid, errMessage };
}
if (newName.indexOf('/') > -1) {
isValid = false;
errMessage = gettext('Name should not include ' + '\'/\'' + '.');
return { isValid, errMessage };
}
return { isValid, errMessage };
}
2018-12-12 02:12:19 +00:00
render() {
return (
<div className="rename-container">
<input
2023-09-05 12:21:24 +00:00
ref={this.inputRef}
value={this.state.name}
onChange={this.onChange}
2023-09-05 12:21:24 +00:00
onKeyDown={this.onKeyDown}
2018-12-12 02:12:19 +00:00
/>
</div>
);
}
}
Rename.propTypes = propTypes;
2018-12-12 02:12:19 +00:00
export default Rename;