gamja-old/components/composer.js

112 lines
2.3 KiB
JavaScript
Raw Normal View History

import { html, Component, createRef } from "../lib/index.js";
export default class Composer extends Component {
state = {
text: "",
};
textInput = createRef();
constructor(props) {
super(props);
this.handleInput = this.handleInput.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
2020-06-29 06:36:17 -04:00
this.handleInputKeyDown = this.handleInputKeyDown.bind(this);
this.handleWindowKeyDown = this.handleWindowKeyDown.bind(this);
}
handleInput(event) {
this.setState({ [event.target.name]: event.target.value });
if (this.props.readOnly && event.target.name === "text" && !event.target.value) {
event.target.blur();
}
}
handleSubmit(event) {
event.preventDefault();
this.props.onSubmit(this.state.text);
this.setState({ text: "" });
}
2020-06-29 06:36:17 -04:00
handleInputKeyDown(event) {
if (!this.props.autocomplete || event.key !== "Tab") {
return;
}
2021-06-10 12:11:11 -04:00
let text = this.state.text;
let i;
2020-06-29 06:36:17 -04:00
for (i = text.length - 1; i >= 0; i--) {
if (text[i] === " ") {
break;
}
}
2021-06-10 12:11:11 -04:00
let prefix = text.slice(i + 1);
2020-06-29 06:36:17 -04:00
if (!prefix) {
return;
}
event.preventDefault();
2021-06-10 12:11:11 -04:00
let repl = this.props.autocomplete(prefix);
2020-06-29 06:36:17 -04:00
if (!repl) {
return;
}
text = text.slice(0, i + 1) + repl;
this.setState({ text });
}
handleWindowKeyDown(event) {
2020-06-29 06:36:17 -04:00
if (document.activeElement === document.body && event.key === "/" && !this.state.text) {
event.preventDefault();
this.setState({ text: "/" }, () => {
this.focus();
});
}
}
componentDidMount() {
window.addEventListener("keydown", this.handleWindowKeyDown);
}
componentWillUnmount() {
window.removeEventListener("keydown", this.handleWindowKeyDown);
}
focus() {
if (!this.textInput.current) {
return;
}
document.activeElement.blur(); // in case we're read-only
this.textInput.current.focus();
}
render() {
2021-06-22 07:38:05 -04:00
let className = "";
if (this.props.readOnly && !this.state.text) {
className = "read-only";
}
return html`
2021-06-22 07:38:05 -04:00
<form
id="composer"
class=${className}
onInput=${this.handleInput}
onSubmit=${this.handleSubmit}
>
<input
type="text"
name="text"
ref=${this.textInput}
value=${this.state.text}
autocomplete="off"
placeholder="Type a message"
2021-05-31 12:16:49 -04:00
enterkeyhint="send"
onKeyDown=${this.handleInputKeyDown}
/>
</form>
`;
}
}