Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for left/right arrows to move terminal line cursor #37

Merged
merged 6 commits into from
May 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 49 additions & 6 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,63 @@ export interface Props {

const Terminal = ({name, prompt, height = "600px", colorMode, onInput, children, startingInputValue = ""}: Props) => {
const [currentLineInput, setCurrentLineInput] = useState('');
const [cursorPos, setCursorPos] = useState(0);

const scrollIntoViewRef = useRef<HTMLDivElement>(null)

const updateCurrentLineInput = (event: ChangeEvent<HTMLInputElement>) => {
setCurrentLineInput(event.target.value);
}

// Calculates the total width in pixels of the characters to the right of the cursor.
// Create a temporary span element to measure the width of the characters.
const calculateInputWidth = (inputElement: HTMLInputElement, chars: string) => {
const span = document.createElement('span');
span.style.visibility = 'hidden';
span.style.position = 'absolute';
span.style.fontSize = window.getComputedStyle(inputElement).fontSize;
span.style.fontFamily = window.getComputedStyle(inputElement).fontFamily;
span.innerText = chars;
document.body.appendChild(span);
const width = span.getBoundingClientRect().width;
document.body.removeChild(span);
// Return the negative width, since the cursor position is to the left of the input suffix
return -width;
};

const clamp = (value: number, min: number, max: number) => {
if(value > max) return max;
if(value < min) return min;
return value;
}

const handleInputKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'ArrowLeft') {
event.preventDefault();
}
if (onInput != null && event.key === 'Enter') {
if(!onInput) {
return;
};
if (event.key === 'Enter') {
onInput(currentLineInput);
setCursorPos(0);
setCurrentLineInput('');
} else if (["ArrowLeft", "ArrowRight", "ArrowDown", "ArrowUp", "Delete"].includes(event.key)) {
const inputElement = document.getElementById('hidden') as HTMLInputElement;
let charsToRightOfCursor = "";
let cursorIndex = currentLineInput.length - (inputElement.selectionStart || 0);
jonmbake marked this conversation as resolved.
Show resolved Hide resolved
cursorIndex = clamp(cursorIndex, 0, currentLineInput.length);

if(event.key === 'ArrowLeft') {
if(cursorIndex > currentLineInput.length - 1) cursorIndex --;
charsToRightOfCursor = currentLineInput.slice(currentLineInput.length -1 - cursorIndex);
}
else if (event.key === 'ArrowRight' || event.key === 'Delete') {
charsToRightOfCursor = currentLineInput.slice(currentLineInput.length - cursorIndex + 1);
}
else if (event.key === 'ArrowUp') {
charsToRightOfCursor = currentLineInput.slice(0)
}

const inputWidth = calculateInputWidth(inputElement, charsToRightOfCursor);
setCursorPos(inputWidth);
}
}

Expand Down Expand Up @@ -77,10 +120,10 @@ const Terminal = ({name, prompt, height = "600px", colorMode, onInput, children,
<div className={ classes.join(' ') } data-terminal-name={ name }>
<div className="react-terminal" style={ { height } }>
{ children }
{ onInput && <div className="react-terminal-line react-terminal-input react-terminal-active-input" data-terminal-prompt={ prompt || '$' } key="terminal-line-prompt" >{ currentLineInput }</div> }
{ onInput && <div className="react-terminal-line react-terminal-input react-terminal-active-input" data-terminal-prompt={ prompt || '$' } key="terminal-line-prompt" >{ currentLineInput }<span id="cursor" style={{ left: `${cursorPos+1}px` }}></span></div> }
<div ref={ scrollIntoViewRef }></div>
</div>
<input className="terminal-hidden-input" placeholder="Terminal Hidden Input" value={ currentLineInput } autoFocus={ onInput != null } onChange={ updateCurrentLineInput } onKeyDown={ handleInputKeyDown }/>
<input id="hidden" className="terminal-hidden-input" placeholder="Terminal Hidden Input" value={ currentLineInput } autoFocus={ onInput != null } onChange={ updateCurrentLineInput } onKeyDown={ handleInputKeyDown }/>
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll check this, but there have been a bug introduced here when multiple terminals are rendered by using an id attr. @jerwolff I think we may want to use a ref to look this el up, instead of using id.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh yeah that's a good point, I should be using a ref. I can work on that.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You may be able to avoid using both a ref and id, and instead use event.currentTarget in #handleInputKeyDown.

</div>
);
}
Expand Down
11 changes: 7 additions & 4 deletions src/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,13 @@
content: attr(data-terminal-prompt);
}

.react-terminal-wrapper:focus-within .react-terminal-active-input:after {
content: '▋';
font-family: monospace;
margin-left: 0.2em;
.react-terminal-wrapper:focus-within .react-terminal-active-input #cursor {
position: relative;
display: inline-block;
width: 0.55em;
height: 1em;
top: 0.225em;
background: #fff;
-webkit-animation: blink 1s infinite;
animation: blink 1s infinite;
}
Expand Down