Skip to content

Commit

Permalink
refactor to shorten
Browse files Browse the repository at this point in the history
  • Loading branch information
bvandercar-vt committed Sep 11, 2024
1 parent 853422c commit 47238e8
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 16 deletions.
24 changes: 11 additions & 13 deletions src/DataRenderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ function quoteString(value: string, quoted = false) {
return value;
}

export function getButtonElements(outerElement: HTMLDivElement) {
export function getButtonElements(outerRef: React.RefObject<HTMLElement>) {
const outerElement = outerRef.current;
if (!outerElement) return;
return Array.from(outerElement.querySelectorAll<HTMLElement>('[role=button]'));
}

Expand Down Expand Up @@ -106,13 +108,10 @@ function ExpandableObject({
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
e.preventDefault();
const direction = e.key === 'ArrowUp' ? -1 : 1;
const outerElement = outerRef.current;
if (!outerElement) return;
const selectedElement = outerElement.querySelectorAll<HTMLElement>('[tabindex="0"]')[0];
if (!selectedElement) return;

const buttonElements = getButtonElements(outerElement);
const currentIndex = buttonElements.indexOf(selectedElement);
const buttonElements = getButtonElements(outerRef);
if (!buttonElements) return;
const currentIndex = buttonElements.findIndex((el) => el.tabIndex === 0);
if (currentIndex < 0) return;

const nextIndex = (currentIndex + direction + buttonElements.length) % buttonElements.length; // auto-wrap
Expand All @@ -123,12 +122,11 @@ function ExpandableObject({

const onClick = () => {
toggleExpanded();
const outerElement = outerRef.current;
if (!outerElement) return;
const buttonElement = expanderButtonRef.current;
if (!buttonElement) return;
const buttonElements = getButtonElements(outerElement);
const currentIndex = buttonElements.indexOf(buttonElement);
const buttonElements = getButtonElements(outerRef);
if (!buttonElements) return;
const currentButtonElement = expanderButtonRef.current;
if (!currentButtonElement) return;
const currentIndex = buttonElements.indexOf(currentButtonElement);
setTabbableButton(buttonElements, currentIndex);
};

Expand Down
5 changes: 2 additions & 3 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,8 @@ export const JsonView = ({

// on first render, set first button to tabIndex=0.
React.useEffect(() => {
const outerElement = outerRef.current;
if (!outerElement) return;
const buttonElements = getButtonElements(outerElement);
const buttonElements = getButtonElements(outerRef);
if (!buttonElements) return;
setTabbableButton(buttonElements, 0);
}, [outerRef]);

Expand Down

0 comments on commit 47238e8

Please sign in to comment.