Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Implement cursor navigation with navigation keys (#404)
* feat(type): Implement cursor navigation with ArrowLeft and ArrowRight * refactor(navigation-key): use a Number instead to hit all the lines * test(type): simplify snapshot * style(type): remove whitespace Co-authored-by: Jesu Castillo <castillojesuj@gmail.com> Closes #354
- Loading branch information
Showing
3 changed files
with
97 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
import {fireEvent} from '@testing-library/dom' | ||
|
||
import {setSelectionRangeIfNecessary} from '../utils' | ||
|
||
const keys = { | ||
ArrowLeft: { | ||
keyCode: 37, | ||
}, | ||
ArrowRight: { | ||
keyCode: 39, | ||
}, | ||
} | ||
|
||
function getSelectionRange(currentElement, key) { | ||
const {selectionStart, selectionEnd} = currentElement() | ||
const cursorChange = Number(key in keys) * (key === 'ArrowLeft' ? -1 : 1) | ||
return { | ||
selectionStart: selectionStart + cursorChange, | ||
selectionEnd: selectionEnd + cursorChange, | ||
} | ||
} | ||
|
||
function navigationKey(key) { | ||
const event = { | ||
key, | ||
keyCode: keys[key].keyCode, | ||
which: keys[key].keyCode, | ||
} | ||
|
||
return ({currentElement, eventOverrides}) => { | ||
fireEvent.keyDown(currentElement(), { | ||
...event, | ||
...eventOverrides, | ||
}) | ||
|
||
const range = getSelectionRange(currentElement, key) | ||
setSelectionRangeIfNecessary( | ||
currentElement(), | ||
range.selectionStart, | ||
range.selectionEnd, | ||
) | ||
|
||
fireEvent.keyUp(currentElement(), { | ||
...event, | ||
...eventOverrides, | ||
}) | ||
} | ||
} | ||
|
||
export {navigationKey} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters