Skip to content

Commit

Permalink
use focus
Browse files Browse the repository at this point in the history
  • Loading branch information
davidmenendez committed Mar 28, 2023
1 parent b76f09e commit 3dee2dc
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 13 deletions.
32 changes: 21 additions & 11 deletions src/AddSelect/List/List.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,30 @@
import { prefix } from "../../constants";
import Row from "../Row";
import useFocus from "../../useFocus";

const List = ({
entries,
data,
...rest
}) => (
<div className={`${prefix}__list`}>
{entries.map(guid => (
<Row
key={guid}
{...data[guid]}
{...rest}
/>
))}
</div>
);
}) => {
const [focus, setFocus] = useFocus(entries.length);
return (
<div className={`${prefix}__list`}>
{entries.map((guid, index) => {
const entry = data[guid];
return (
<Row
key={guid}
setFocus={setFocus}
index={index}
focus={focus === index}
{...entry}
{...rest}
/>
)
})}
</div>
);
};

export default List;
23 changes: 21 additions & 2 deletions src/AddSelect/Row/Row.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useEffect, useRef, useCallback } from 'react';
import cx from 'classnames';
import { prefix } from "../../constants"
import {
Expand All @@ -11,16 +12,33 @@ const Row = ({
name,
selected,
setSelected,
parentId,
children,
parentHandler,
focus,
index,
setFocus,
parentId,
}) => {
const ref = useRef(null);

useEffect(() => {
if (focus) {
ref.current.focus();
}
}, [focus]);

const focusHandler = useCallback(() => {
console.log(name);
setFocus(index);
}, [name, index, setFocus]);

const onSelectKeyDown = ({ key }) => {
if (key === 'Enter') {
onSelectHandler();
}
};
const onSelectHandler = () => {
focusHandler();
setSelected(guid);
};

Expand All @@ -37,7 +55,8 @@ const Row = ({
})}
onClick={onSelectHandler}
onKeyDown={onSelectKeyDown}
tabIndex={0}
tabIndex={focus ? 0 : -1}
ref={ref}
>
<div className={`${prefix}__input-group`}>
{isSelected ? (
Expand Down
29 changes: 29 additions & 0 deletions src/useFocus.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { useCallback, useState, useEffect } from "react";

const useFocus = (size) => {
const [currentFocus, setCurrentFocus] = useState(0);

const handleKeyDown = useCallback(
e => {
if (e.keyCode === 40) { // Down arrow
e.preventDefault();
setCurrentFocus(currentFocus === size - 1 ? 0 : currentFocus + 1);
} else if (e.keyCode === 38) { // Up arrow
e.preventDefault();
setCurrentFocus(currentFocus === 0 ? size - 1 : currentFocus - 1);
}
},
[size, currentFocus, setCurrentFocus]
);

useEffect(() => {
document.addEventListener("keydown", handleKeyDown, false);
return () => {
document.removeEventListener("keydown", handleKeyDown, false);
};
}, [handleKeyDown]);

return [currentFocus, setCurrentFocus];
}

export default useFocus;

0 comments on commit 3dee2dc

Please sign in to comment.