Skip to content

Commit

Permalink
add logic to navigate ticker list with arrow keys
Browse files Browse the repository at this point in the history
  • Loading branch information
iamping committed Jan 19, 2025
1 parent 126b052 commit 842b4a4
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
29 changes: 28 additions & 1 deletion src/components/app/data-table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import { useAtom, useSetAtom } from 'jotai';
import { columnStateAtom, dropdownFnAtom, filterStateAtom, rowCountAtom, tickerAtom } from '../../state/atom';
import { Panel, PanelGroup, PanelResizeHandle } from 'react-resizable-panels';
import { HistoricalChart } from './historical-chart';
import { useEventListener } from 'usehooks-ts';

// table columns
const columnHelper = createColumnHelper<Stock>();
Expand Down Expand Up @@ -301,7 +302,8 @@ export const DataTable: FC<DataTableProps> = ({ data }) => {

const resetPageIndex = useCallback(() => {
listRef.current?.scrollToIndex({
index: 0
index: 0,
offset: -100
});
}, []);

Expand All @@ -327,6 +329,30 @@ export const DataTable: FC<DataTableProps> = ({ data }) => {
const gridTemplateColumnsStyle: CSSProperties = { gridTemplateColumns: `repeat(${numColumns}, auto)` };
const gridColumnStyle: CSSProperties = { gridColumn: `1 / ${numColumns + 1}` };

useEventListener('keydown', (event) => {
const availableRowsLength = table.getRowModel().rows.length;
if (ticker.length > 0) {
switch (event.key) {
case 'ArrowUp': {
const activeRowIndex = table.getRowModel().rows.findIndex((item) => item.original.ticker === ticker);
if (activeRowIndex > 0) {
const previousTicker = table.getRowModel().rows[activeRowIndex - 1].original.ticker;
setTicker(previousTicker);
}
break;
}
case 'ArrowDown': {
const activeRowIndex = table.getRowModel().rows.findIndex((item) => item.original.ticker === ticker);
if (activeRowIndex < availableRowsLength - 1) {
const nextTicker = table.getRowModel().rows[activeRowIndex + 1].original.ticker;
setTicker(nextTicker);
}
break;
}
}
}
});

return (
<>
<PanelGroup autoSaveId="panel-group" direction="horizontal">
Expand Down Expand Up @@ -359,6 +385,7 @@ export const DataTable: FC<DataTableProps> = ({ data }) => {
<Show when={numRows > 0}>
<ViewportList
initialPrerender={50}
itemSize={30}
ref={listRef}
viewportRef={parentRef}
items={table.getRowModel().rows}>
Expand Down
5 changes: 5 additions & 0 deletions src/components/app/search-box.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,11 @@ export const SearchBox = () => {
inputRef.current?.select();
}, 50);
}
if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
setTimeout(() => {
inputRef.current?.select();
}, 50);
}
setTimeout(() => {
inputRef.current?.focus();
}, 0);
Expand Down

0 comments on commit 842b4a4

Please sign in to comment.