You're right, there's an issue with the focus behavior. Let me fix that:
I've fixed the focus issue in the edit mode. Now when you edit letters, the focus will stay where you expect it to be, and you can navigate naturally through the board. Here's what I changed:
const prevEditingRef = useRef(isEditing)This allows us to compare the current editing state with the previous one, so we can detect when we're first entering edit mode.
I completely rewrote the effect that handles edit mode changes:
useEffect(() => {
if (isEditing !== undefined && isEditing !== prevEditingRef.current) {
setEditMode(isEditing)
// Only set focus to first cell when first entering edit mode
if (isEditing && !prevEditingRef.current) {
setFocusPosition([0, 0])
}
// Handle saving when exiting edit mode
else if (!isEditing && prevEditingRef.current && onSaveEdit) {
const validBoard = editBoard.map((row) => row.map((cell) => (cell.trim() === "" ? "e" : cell)))
onSaveEdit(validBoard)
}
prevEditingRef.current = isEditing
}
}, [isEditing, onSaveEdit])Key changes:
editBoard and editMode from the dependency arrayThe focus now only changes when:
Now the edit mode should work as expected:
The focus no longer resets to the first cell when you edit a letter, making the editing experience much more natural and intuitive.
I'll implement auto-advance to the next cell after typing a letter:
I've implemented auto-advance functionality that automatically moves the focus to the next cell after typing a letter. Here's what I added:
// Get the next cell position (left-to-right, then top-to-bottom)
const getNextCellPosition = (rowIndex: number, colIndex: number): [number, number] => {
const rows = board.length
const cols = board[0]?.length || 0
// Move to the next column
let nextCol = colIndex + 1
let nextRow = rowIndex
// If we're at the end of a row, move to the next row
if (nextCol >= cols) {
nextCol = 0
nextRow = (nextRow + 1) % rows
}
return [nextRow, nextCol]
}This function calculates the next cell position in a left-to-right, top-to-bottom order. When it reaches the end of a row, it wraps to the beginning of the next row. When it reaches the end of the board, it wraps back to the beginning.
const handleLetterChange = (rowIndex: number, colIndex: number, value: string) => {
// Take the last character typed (or empty string if backspace/delete was used)
const letter = value.length > 0 ? value.toLowerCase().slice(-1) : ""
const newBoard = editBoard.map((row, r) => row.map((cell, c) => (r === rowIndex && c === colIndex ? letter : cell)))
setEditBoard(newBoard)
// If a letter was entered (not deleted), advance to the next cell
if (letter) {
const nextPosition = getNextCellPosition(rowIndex, colIndex)
setFocusPosition(nextPosition)
}
}The key addition is the conditional check if (letter) that:
getNextCellPosition function to determine where to go nextThis makes editing the board much faster and more efficient, especially when you want to replace multiple letters in sequence.