Skip to content

Instantly share code, notes, and snippets.

@htlin222
Created July 30, 2024 04:16
Show Gist options
  • Save htlin222/6fddd2dbc5132be9aa03432baab96230 to your computer and use it in GitHub Desktop.
Save htlin222/6fddd2dbc5132be9aa03432baab96230 to your computer and use it in GitHub Desktop.
import React, { useState, useRef, useEffect } from 'react';
const snippets = {
'if': 'if (condition) {\n \n}',
'fo': 'for (let i = 0; i < array.length; i++) {\n \n}',
'co': 'console.log();',
};
const TextEditor = () => {
const [text, setText] = useState('');
const [suggestion, setSuggestion] = useState('');
const [cursorPosition, setCursorPosition] = useState(0);
const textareaRef = useRef(null);
useEffect(() => {
const textarea = textareaRef.current;
textarea.setSelectionRange(cursorPosition, cursorPosition);
}, [cursorPosition]);
const handleChange = (e) => {
const newText = e.target.value;
setText(newText);
setCursorPosition(e.target.selectionStart);
const words = newText.slice(0, e.target.selectionStart).split(/\s/);
const lastWord = words[words.length - 1];
if (lastWord.length >= 2) {
const matchingSnippet = Object.keys(snippets).find(key => key.startsWith(lastWord));
setSuggestion(matchingSnippet ? snippets[matchingSnippet] : '');
} else {
setSuggestion('');
}
};
const handleKeyDown = (e) => {
if (e.key === 'Tab' && suggestion) {
e.preventDefault();
const beforeCursor = text.slice(0, cursorPosition);
const afterCursor = text.slice(cursorPosition);
const words = beforeCursor.split(/\s/);
const lastWord = words[words.length - 1];
const newText = beforeCursor.slice(0, -lastWord.length) + suggestion + afterCursor;
setText(newText);
setCursorPosition(cursorPosition - lastWord.length + suggestion.length);
setSuggestion('');
}
};
return (
<div className="p-4">
<textarea
ref={textareaRef}
value={text}
onChange={handleChange}
onKeyDown={handleKeyDown}
className="w-full h-64 p-2 border border-gray-300 rounded"
placeholder="Start typing..."
/>
{suggestion && (
<div className="mt-2 p-2 bg-gray-100 rounded">
Suggestion: {suggestion}
</div>
)}
</div>
);
};
export default TextEditor;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment