Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/add on arrow release #145

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,10 @@ Receives `direction` (`left`, `right`, `up`, `down`), `extraProps` (see below) a
This callback HAS to return `true` if you want to proceed with the default directional navigation behavior, or `false`
if you want to block the navigation in the specified direction.

##### `onArrowRelease` (function)
Callback that is called when the component is focused and Arrow key is released.
Receives `direction` (`left`, `right`, `up`, `down`), `extraProps` (see below) as argument.

##### `onFocus` (function)
Callback that is called when component gets focus.
Receives `FocusableComponentLayout`, `extraProps` and `FocusDetails` as arguments.
Expand Down
81 changes: 81 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ function Menu({ focusKey: focusKeyParam }: MenuProps) {
onEnterPress: () => {},
onEnterRelease: () => {},
onArrowPress: () => true,
onArrowRelease: () => {},
onFocus: () => {},
onBlur: () => {},
extraProps: { foo: 'bar' }
Expand Down Expand Up @@ -383,6 +384,85 @@ const ScrollingRows = styled.div`
flex-grow: 1;
`;

interface ProgressBarWrapperProps {
focused: boolean;
}

interface ProgressBarProgressProps {
percent: number;
focused: boolean;
}

const ProgressBarWrapper = styled.div<ProgressBarWrapperProps>`
position: absolute;
bottom: 95px;
right: 100px;
width: 540px;
height: 24px;
background-color: gray;
border-radius: 21px;
border-color: white;
border-style: solid;
border-width: ${({ focused }) => (focused ? '6px' : 0)};
box-sizing: border-box;
`;

const ProgressBarProgress = styled.div<ProgressBarProgressProps>`
width: ${({ percent }) => `${percent}%`};
height: 100%;
background-color: ${({ focused }) =>
focused ? 'deepskyblue' : 'dodgerblue'};
border-radius: 21px;
`;

const defaultPercent = 10;
const seekPercent = 10;
const delayedTime = 100;
const DIRECTION_RIGHT = 'right';

function ProgressBar() {
const [percent, setPercent] = useState(defaultPercent);
const timerRef = useRef<NodeJS.Timer | null>(null);
const { ref, focused } = useFocusable({
onArrowPress: (direction: string) => {
if (direction === DIRECTION_RIGHT && timerRef.current === null) {
timerRef.current = setInterval(() => {
setPercent((prevPercent) =>
prevPercent >= 100 ? prevPercent : prevPercent + seekPercent
);
}, delayedTime);
return true;
}
return true;
},
onArrowRelease: (direction: string) => {
if (direction === DIRECTION_RIGHT) {
clearInterval(timerRef.current);
timerRef.current = null;
}
}
});
useEffect(() => {
if (!focused) {
setPercent(defaultPercent);
}
}, [focused]);
useEffect(
() => () => {
if (timerRef.current !== null) {
clearInterval(timerRef.current);
timerRef.current = null;
}
},
[]
);
return (
<ProgressBarWrapper ref={ref} focused={focused}>
<ProgressBarProgress percent={percent} focused={focused} />
</ProgressBarWrapper>
);
}

function Content() {
const { ref, focusKey } = useFocusable();

Expand Down Expand Up @@ -415,6 +495,7 @@ function Content() {
? selectedAsset.title
: 'Press "Enter" to select an asset'}
</SelectedItemTitle>
<ProgressBar />
</SelectedItemWrapper>
<ScrollingRows ref={ref}>
<div>
Expand Down
67 changes: 50 additions & 17 deletions src/SpatialNavigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ interface FocusableComponent {
onEnterPress: (details?: KeyPressDetails) => void;
onEnterRelease: () => void;
onArrowPress: (direction: string, details: KeyPressDetails) => boolean;
onArrowRelease: (direction: string) => void;
onFocus: (layout: FocusableComponentLayout, details: FocusDetails) => void;
onBlur: (layout: FocusableComponentLayout, details: FocusDetails) => void;
onUpdateFocus: (focused: boolean) => void;
Expand All @@ -106,6 +107,7 @@ interface FocusableComponentUpdatePayload {
onEnterPress: (details?: KeyPressDetails) => void;
onEnterRelease: () => void;
onArrowPress: (direction: string, details: KeyPressDetails) => boolean;
onArrowRelease: (direction: string) => void;
onFocus: (layout: FocusableComponentLayout, details: FocusDetails) => void;
onBlur: (layout: FocusableComponentLayout, details: FocusDetails) => void;
}
Expand Down Expand Up @@ -155,9 +157,9 @@ const getChildClosestToOrigin = (
const comparator =
writingDirection === WritingDirection.LTR
? ({ layout }: FocusableComponent) =>
Math.abs(layout.left) + Math.abs(layout.top)
Math.abs(layout.left) + Math.abs(layout.top)
: ({ layout }: FocusableComponent) =>
Math.abs(window.innerWidth - layout.right) + Math.abs(layout.top);
Math.abs(window.innerWidth - layout.right) + Math.abs(layout.top);

const childrenClosestToOrigin = sortBy(children, comparator);

Expand Down Expand Up @@ -272,22 +274,22 @@ class SpatialNavigationService {
const itemStart = isVertical
? layout.top
: writingDirection === WritingDirection.LTR
? layout.left
: layout.right;
? layout.left
: layout.right;

const itemEnd = isVertical
? layout.bottom
: writingDirection === WritingDirection.LTR
? layout.right
: layout.left;
? layout.right
: layout.left;

return isIncremental
? isSibling
? itemStart
: itemEnd
: isSibling
? itemEnd
: itemStart;
? itemEnd
: itemStart;
}

/**
Expand Down Expand Up @@ -405,7 +407,7 @@ class SpatialNavigationService {
const intersectionLength = Math.max(
0,
Math.min(refCoordinateB, siblingCoordinateB) -
Math.max(refCoordinateA, siblingCoordinateA)
Math.max(refCoordinateA, siblingCoordinateA)
);

return intersectionLength >= thresholdDistance;
Expand Down Expand Up @@ -830,6 +832,14 @@ class SpatialNavigationService {
if (eventType === KEY_ENTER && this.focusKey) {
this.onEnterRelease();
}

if (this.focusKey && (
eventType === DIRECTION_LEFT ||
eventType === DIRECTION_RIGHT ||
eventType === DIRECTION_UP ||
eventType === DIRECTION_DOWN)) {
this.onArrowRelease(eventType)
}
};

window.addEventListener('keyup', this.keyUpEventListener);
Expand Down Expand Up @@ -921,6 +931,28 @@ class SpatialNavigationService {
);
}

onArrowRelease(direction: string) {
const component = this.focusableComponents[this.focusKey];

/* Guard against last-focused component being unmounted at time of onArrowRelease (e.g due to UI fading out) */
if (!component) {
this.log('onArrowRelease', 'noComponent');

return;
}

/* Suppress onArrowRelease if the last-focused item happens to lose its 'focused' status. */
if (!component.focusable) {
this.log('onArrowRelease', 'componentNotFocusable');

return;
}

if (component.onArrowRelease) {
component.onArrowRelease(direction);
}
}

/**
* Move focus by direction, if you can't use buttons or focusing by key.
*
Expand Down Expand Up @@ -1039,12 +1071,12 @@ class SpatialNavigationService {
? siblingCutoffCoordinate >= currentCutoffCoordinate // vertical next
: siblingCutoffCoordinate <= currentCutoffCoordinate // vertical previous
: this.writingDirection === WritingDirection.LTR
? isIncrementalDirection
? siblingCutoffCoordinate >= currentCutoffCoordinate // horizontal LTR next
: siblingCutoffCoordinate <= currentCutoffCoordinate // horizontal LTR previous
: isIncrementalDirection
? siblingCutoffCoordinate <= currentCutoffCoordinate // horizontal RTL next
: siblingCutoffCoordinate >= currentCutoffCoordinate; // horizontal RTL previous
? isIncrementalDirection
? siblingCutoffCoordinate >= currentCutoffCoordinate // horizontal LTR next
: siblingCutoffCoordinate <= currentCutoffCoordinate // horizontal LTR previous
: isIncrementalDirection
? siblingCutoffCoordinate <= currentCutoffCoordinate // horizontal RTL next
: siblingCutoffCoordinate >= currentCutoffCoordinate; // horizontal RTL previous
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please make sure to run Prettier on your code. All these small changes will be changed back next time we run Prettier. We will automate it with Husky in the future, but for now please only include changes that are relevant to your feature :)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @asgvard
Thanks for your review :) I just reverted these unrelated changes. Could you take another quick look to see if everything is good to merge?
Regarding adding Husky, I have used it before in another project and it is really convenient. Can I try and create another issue and PR to deal with it 😀 ?

}

return false;
Expand Down Expand Up @@ -1128,8 +1160,7 @@ class SpatialNavigationService {
// eslint-disable-next-line no-console
console.log(
`%c${functionName}%c${debugString}`,
`background: ${
DEBUG_FN_COLORS[this.logIndex % DEBUG_FN_COLORS.length]
`background: ${DEBUG_FN_COLORS[this.logIndex % DEBUG_FN_COLORS.length]
}; color: black; padding: 1px 5px;`,
'background: #333; color: #BADA55; padding: 1px 5px;',
...rest
Expand Down Expand Up @@ -1275,6 +1306,7 @@ class SpatialNavigationService {
onEnterPress,
onEnterRelease,
onArrowPress,
onArrowRelease,
onFocus,
onBlur,
saveLastFocusedChild,
Expand All @@ -1295,6 +1327,7 @@ class SpatialNavigationService {
onEnterPress,
onEnterRelease,
onArrowPress,
onArrowRelease,
onFocus,
onBlur,
onUpdateFocus,
Expand Down
11 changes: 6 additions & 5 deletions src/__tests__/SpatialNavigation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,11 +129,12 @@ describe('SpatialNavigation', () => {
} as unknown as HTMLElement,
isFocusBoundary: false,
focusable: true,
onEnterPress: () => {},
onEnterRelease: () => {},
onFocus: () => {},
onBlur: () => {},
onArrowPress: () => true
onEnterPress: () => { },
onEnterRelease: () => { },
onFocus: () => { },
onBlur: () => { },
onArrowPress: () => true,
onArrowRelease: () => { },
});

SpatialNavigation.navigateByDirection('right', {});
Expand Down
Loading