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

fix(date-picker): month and year picker scroller #3789

Open
wants to merge 20 commits into
base: canary
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
4895941
accordion tree
buchananwill Sep 18, 2024
7968f1a
Rename accordionTree.tsx to accordion-tree.tsx
buchananwill Sep 18, 2024
3b77e2e
Update accordion-tree.tsx
buchananwill Sep 18, 2024
5f35a84
fix(use-calendar-picker): fixed the UI month/year sync (#3785)
buchananwill Sep 22, 2024
66108cd
fix(use-calendar-picker): fixed the UI month/year sync (#3785)
buchananwill Sep 22, 2024
d6b00bc
fix(use-calendar-picker): added test for the fixed behaviour (#3785)
buchananwill Sep 23, 2024
e30ae3c
fix(use-calendar-picker): changeset (#3785)
buchananwill Sep 23, 2024
d4cc930
Delete .changeset/serious-snails-count.md
buchananwill Sep 23, 2024
cb2d7fe
Update sixty-weeks-help.md
buchananwill Sep 23, 2024
928237b
fix(use-calendar-picker): swapped the aria label for data-slot="heade…
buchananwill Sep 26, 2024
5bc25d5
fix(use-calendar-picker): added scrollTo(nextValue, list) into the ke…
buchananwill Sep 27, 2024
e6a2f99
fix(use-calendar-picker): prevent default behaviour for scroll keys
buchananwill Sep 27, 2024
0a2c4c9
fix(use-calendar-picker): add a key up event to further fix #3789
buchananwill Oct 2, 2024
5ec489b
fix(use-calendar-picker): changed the home/end values to 1 and 12
buchananwill Oct 2, 2024
151141c
fix(use-calendar-picker): sourced the mix/max values from the state
buchananwill Oct 3, 2024
cc5ca02
fix(use-calendar-picker): useCallback for the getBoundaryValue
buchananwill Oct 3, 2024
243befa
fix(use-calendar-picker): blocking repeat key strokes for home and end
buchananwill Oct 3, 2024
c3f924b
fix(use-calendar-picker): inlined arrow function
buchananwill Oct 3, 2024
b96542a
fix(use-calendar-picker): simplified control structure
buchananwill Oct 3, 2024
214385f
fix(use-calendar-picker): change the execution order to avoid stale l…
buchananwill Oct 3, 2024
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
6 changes: 6 additions & 0 deletions .changeset/sixty-weeks-help.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@nextui-org/calendar": patch
"@nextui-org/date-picker": patch
---

Added an aria and test label for the picker toggle.
3 changes: 2 additions & 1 deletion packages/components/calendar/src/calendar-picker-item.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,15 @@ import {mergeProps} from "@react-aria/utils";
const CalendarPickerItem = forwardRef<
HTMLButtonElement,
HTMLNextUIProps<"button"> & AriaButtonProps
>(({children, autoFocus, isDisabled, onKeyDown, ...otherProps}, ref) => {
>(({children, autoFocus, isDisabled, onKeyDown, onKeyUp, ...otherProps}, ref) => {
const domRef = useDOMRef(ref);

const {buttonProps: ariaButtonProps, isPressed} = useAriaButton(
{
elementType: "button",
isDisabled,
onKeyDown,
onKeyUp,
...otherProps,
} as AriaButtonProps,
domRef,
Expand Down
3 changes: 3 additions & 0 deletions packages/components/calendar/src/calendar-picker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export function CalendarPicker(props: CalendarPickerProps) {
isHeaderExpanded,
onPickerItemPressed,
onPickerItemKeyDown,
onPickerItemKeyUp,
} = useCalendarPicker(props);

const EmptyItem = useCallback(
Expand Down Expand Up @@ -89,6 +90,7 @@ export function CalendarPicker(props: CalendarPickerProps) {
data-value={month.value}
tabIndex={!isHeaderExpanded || state.focusedDate?.month !== month.value ? -1 : 0}
onKeyDown={(e) => onPickerItemKeyDown(e, month.value, "months")}
onKeyUp={(e) => onPickerItemKeyUp(e, month.value, "months")}
onPress={(e) => onPickerItemPressed(e, "months")}
>
{month.label}
Expand All @@ -110,6 +112,7 @@ export function CalendarPicker(props: CalendarPickerProps) {
data-value={year.value}
tabIndex={!isHeaderExpanded || state.focusedDate?.year !== year.value ? -1 : 0}
onKeyDown={(e) => onPickerItemKeyDown(e, year.value, "years")}
onKeyUp={(e) => onPickerItemKeyUp(e, year.value, "years")}
onPress={(e) => onPickerItemPressed(e, "years")}
>
{year.label}
Expand Down
166 changes: 99 additions & 67 deletions packages/components/calendar/src/use-calendar-picker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,19 @@ import type {PressEvent} from "@react-types/shared";

import {useDateFormatter} from "@react-aria/i18n";
import {HTMLNextUIProps} from "@nextui-org/system";
import {useCallback, useRef, useEffect} from "react";
import debounce from "lodash.debounce";
import {areRectsIntersecting} from "@nextui-org/react-utils";
import {useCallback, useEffect, useRef} from "react";
import scrollIntoView from "scroll-into-view-if-needed";

import {getMonthsInYear, getYearRange} from "./utils";
import {useCalendarContext} from "./calendar-context";
import useScrollEndCallback from "./use-scroll-end-callback";
import {useKeyRepeatBlocker} from "./use-key-repeat-blocker";

export type PickerValue = {
value: string;
label: string;
};

export interface CalendarPickerProps extends HTMLNextUIProps<"div"> {
date: CalendarDate;
currentMonth: CalendarDate;
Expand All @@ -23,7 +24,30 @@ export interface CalendarPickerProps extends HTMLNextUIProps<"div"> {
type ItemsRefMap = Map<number, HTMLElement>;
type CalendarPickerListType = "months" | "years";

const SCROLL_DEBOUNCE_TIME = 200;
const DEFAULT_BOUNDARY_VALUE = {
max: {months: 12, years: 2099},
min: {months: 1, years: 1900},
} as const;

const LISTENED_NAVIGATION_KEYS = [
"ArrowDown",
"ArrowUp",
"Home",
"End",
"PageUp",
"PageDown",
"Escape",
"Enter",
" ",
];

const OF_100_MILLISECONDS = 100;

const HOME_AND_END_NEED_DEFERRED_FOCUS = ["Home", "End"];

function needsDeferredFocus(e: React.KeyboardEvent<HTMLElement>) {
return HOME_AND_END_NEED_DEFERRED_FOCUS.includes(e.key);
}

export function useCalendarPicker(props: CalendarPickerProps) {
const {date, currentMonth} = props;
Expand Down Expand Up @@ -83,36 +107,6 @@ export function useCalendarPicker(props: CalendarPickerProps) {
}
}

const handleListScroll = useCallback(
(e: Event, highlightEl: HTMLElement | null, list: CalendarPickerListType) => {
if (!(e.target instanceof HTMLElement)) return;

const map = getItemsRefMap(list === "months" ? monthsItemsRef : yearsItemsRef);

const items = Array.from(map.values());

const item = items.find((itemEl) => {
const rect1 = itemEl.getBoundingClientRect();
const rect2 = highlightEl?.getBoundingClientRect();

if (!rect2) {
return false;
}

return areRectsIntersecting(rect1, rect2);
});

const itemValue = Number(item?.getAttribute("data-value"));

if (!itemValue) return;

let date = state.focusedDate.set(list === "months" ? {month: itemValue} : {year: itemValue});

state.setFocusedDate(date);
},
[state, isHeaderExpanded],
);

// scroll to the selected month/year when the component is mounted/opened/closed
useEffect(() => {
if (!isHeaderExpanded) return;
Expand All @@ -121,36 +115,6 @@ export function useCalendarPicker(props: CalendarPickerProps) {
scrollTo(date.year, "years", false);
}, [isHeaderExpanded]);

useEffect(() => {
// add scroll event listener to monthsListRef
const monthsList = monthsListRef.current;
const yearsList = yearsListRef.current;
const highlightEl = highlightRef.current;

if (!highlightEl) return;

const debouncedHandleMonthsScroll = debounce(
(e: Event) => handleListScroll(e, highlightEl, "months"),
SCROLL_DEBOUNCE_TIME,
);
const debouncedHandleYearsScroll = debounce(
(e: Event) => handleListScroll(e, highlightEl, "years"),
SCROLL_DEBOUNCE_TIME,
);

monthsList?.addEventListener("scroll", debouncedHandleMonthsScroll);
yearsList?.addEventListener("scroll", debouncedHandleYearsScroll);

return () => {
if (debouncedHandleMonthsScroll) {
monthsList?.removeEventListener("scroll", debouncedHandleMonthsScroll);
}
if (debouncedHandleYearsScroll) {
yearsList?.removeEventListener("scroll", debouncedHandleYearsScroll);
}
};
}, [handleListScroll]);

function scrollTo(value: number, list: CalendarPickerListType, smooth = true) {
const mapListRef = list === "months" ? monthsItemsRef : yearsItemsRef;
const listRef = list === "months" ? monthsListRef : yearsListRef;
Expand All @@ -160,6 +124,9 @@ export function useCalendarPicker(props: CalendarPickerProps) {
const node = map.get(value);

if (!node) return;
let date = state.focusedDate.set(list === "months" ? {month: value} : {year: value});

state.setFocusedDate(date);

// scroll picker list to the selected item
scrollIntoView(node, {
Expand All @@ -181,10 +148,32 @@ export function useCalendarPicker(props: CalendarPickerProps) {
[state],
);

const {onScrollEnd, abortRef} = useScrollEndCallback(OF_100_MILLISECONDS);
const {handleKeyDown, handleKeyUp, isKeyDown} = useKeyRepeatBlocker(
HOME_AND_END_NEED_DEFERRED_FOCUS,
);

// Destructure before useCallback to ring-fence the dependency
const {maxValue, minValue} = state;

const getBoundaryValue = useCallback(
(list: CalendarPickerListType, bound: "min" | "max") => {
let boundaryDate = bound === "min" ? minValue : maxValue;
const fromState = list === "months" ? boundaryDate?.month : boundaryDate?.year;

return fromState ?? DEFAULT_BOUNDARY_VALUE[bound][list];
},
[minValue, maxValue],
);

const onPickerItemKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLElement>, value: number, list: CalendarPickerListType) => {
const map = getItemsRefMap(list === "months" ? monthsItemsRef : yearsItemsRef);

if (LISTENED_NAVIGATION_KEYS.includes(e.key)) {
e.preventDefault();
}

const node = map.get(value);

if (!node) return;
Expand All @@ -199,10 +188,10 @@ export function useCalendarPicker(props: CalendarPickerProps) {
nextValue = value - 1;
break;
case "Home":
nextValue = 0;
nextValue = getBoundaryValue(list, "min");
break;
case "End":
nextValue = months.length - 1;
nextValue = getBoundaryValue(list, "max");
break;
case "PageUp":
nextValue = value - 3;
Expand All @@ -221,7 +210,49 @@ export function useCalendarPicker(props: CalendarPickerProps) {

const nextItem = map.get(nextValue);

nextItem?.focus();
if (needsDeferredFocus(e)) {
if (!isKeyDown(e.key)) {
scrollTo(nextValue, list);
if (abortRef.current) {
abortRef.current();
}
onScrollEnd(list === "months" ? monthsListRef.current : yearsListRef.current, () => {
nextItem?.focus();
});
handleKeyDown(e.key);
}
} else {
scrollTo(nextValue, list);
if (abortRef.current) {
abortRef.current();
}
nextItem?.focus();
}
},
[state, handleKeyDown, isKeyDown],
);

const onPickerItemKeyUp = useCallback(
(e: React.KeyboardEvent<HTMLElement>, value: number, list: CalendarPickerListType) => {
const listRef = list === "months" ? monthsListRef : yearsListRef;

if (LISTENED_NAVIGATION_KEYS.includes(e.key)) {
e.preventDefault();
}

// When the key up events fires we do a safety scroll to the element that fired it.
// Part of fixing issue #3789
if (e.currentTarget) {
if (needsDeferredFocus(e)) {
handleKeyUp(e.key);
} else {
scrollIntoView(e.currentTarget, {
scrollMode: "always",
behavior: "smooth",
boundary: listRef.current,
});
}
}
},
[state],
);
Expand All @@ -239,6 +270,7 @@ export function useCalendarPicker(props: CalendarPickerProps) {
isHeaderExpanded,
onPickerItemPressed,
onPickerItemKeyDown,
onPickerItemKeyUp,
};
}

Expand Down
51 changes: 51 additions & 0 deletions packages/components/calendar/src/use-key-repeat-blocker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import {useCallback, useRef} from "react";

// Type for the return API
interface UseKeyRepeatBlockerReturn {
handleKeyDown: (key: string) => void;
handleKeyUp: (key: string) => void;
isKeyDown: (key: string) => boolean;
}

export const useKeyRepeatBlocker = (blockedKeys: string[]): UseKeyRepeatBlockerReturn => {
// Ref to store the mutable map of key pressed states
const keyPressedRef = useRef<Record<string, boolean>>({});

// useCallback to ensure stable function references
const handleKeyDown = useCallback(
(key: string) => {
if (blockedKeys.includes(key)) {
// If the key is already pressed, do nothing
if (keyPressedRef.current[key]) {
return;
}

// Mark the key as pressed
keyPressedRef.current[key] = true;
}
},
[blockedKeys],
);

const handleKeyUp = useCallback(
(key: string) => {
if (blockedKeys.includes(key)) {
// Mark the key as not pressed
keyPressedRef.current[key] = false;
}
},
[blockedKeys],
);

// Function to check if a given key is already pressed
const isKeyDown = useCallback((key: string): boolean => {
return keyPressedRef.current[key];
}, []);

// Return the API
return {
handleKeyDown,
handleKeyUp,
isKeyDown,
};
};
Loading