~emersion/gamja

856dd021e2e62c1e298dc99fe87ee9f0c0f26150 — Simon Ser 5 months ago b289fd1
composer: auto-complete word at carret position
1 files changed, 30 insertions(+), 9 deletions(-)

M components/composer.js
M components/composer.js => components/composer.js +30 -9
@@ 30,30 30,51 @@ export default class Composer extends Component {
	}

	handleInputKeyDown(event) {
		let input = event.target;

		if (!this.props.autocomplete || event.key !== "Tab") {
			return;
		}

		if (input.selectionStart !== input.selectionEnd) {
			return;
		}

		event.preventDefault();

		let carretIndex = input.selectionStart;
		let text = this.state.text;
		let i;
		for (i = text.length - 1; i >= 0; i--) {
			if (text[i] === " ") {
		let wordStart;
		for (wordStart = carretIndex - 1; wordStart >= 0; wordStart--) {
			if (text[wordStart] === " ") {
				break;
			}
		}
		let prefix = text.slice(i + 1);
		if (!prefix) {
			return;
		wordStart++;

		let wordEnd;
		for (wordEnd = carretIndex; wordEnd < text.length; wordEnd++) {
			if (text[wordEnd] === " ") {
				break;
			}
		}

		event.preventDefault();
		let word = text.slice(wordStart, wordEnd);
		if (!word) {
			return;
		}

		let repl = this.props.autocomplete(prefix);
		let repl = this.props.autocomplete(word);
		if (!repl) {
			return;
		}

		text = text.slice(0, i + 1) + repl;
		text = text.slice(0, wordStart) + repl + text.slice(wordEnd);

		input.value = text;
		input.selectionStart = wordStart + repl.length;
		input.selectionEnd = input.selectionStart;

		this.setState({ text });
	}