Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import styles from "@/components/DatePicker/DatePicker.module.scss";
import MonthYearButton from "./MonthYearButton";

type Props = {
monthsShort: string[];
selectedMonth?: number;
onMonthClick: (month: number) => void;
};

const MonthGrid = (props: Props) => {
const { monthsShort, selectedMonth, onMonthClick } = props;

return (
<div className={styles.monthSelector} data-testid="DatePickerMonthsContainer">
{monthsShort.map((label, month) => (
<MonthYearButton key={month} label={label} onClick={() => onMonthClick(month)} selected={month === selectedMonth} />
))}
</div>
);
};

export default MonthGrid;
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import styles from "../../../DatePicker.module.scss";
import { useCallback, useContext, useState } from "react";
import { DatePickerContext } from "@/components/DatePicker/context/DatePickerProvider";
import Header from "@/components/DatePicker/components/Header/Header";
import MonthYearButton from "./MonthYearButton";
import MonthGrid from "./MonthGrid";

const MonthSelector = () => {
const { pickerDate, setPickerDate, setPicker, locale, onPickerChange, size } = useContext(DatePickerContext);
Expand All @@ -30,16 +30,11 @@ const MonthSelector = () => {
<>
<Header size={size} year={pickerDate.getFullYear().toString()} onPrevClick={prevClickHandler} onNextClick={nextClickHandler} />
<hr className={styles.divider} />
<div className={styles.monthSelector} data-testid="DatePickerMonthsContainer">
{locale.months.map((_, mIndex) => (
<MonthYearButton
key={mIndex}
label={locale.monthsShort[mIndex]}
onClick={() => handleMonthClick(mIndex)}
selected={pickerDate.getMonth() === mIndex && pickerDate.getFullYear() === activeDate.getFullYear()}
/>
))}
</div>
<MonthGrid
monthsShort={locale.monthsShort}
selectedMonth={pickerDate.getFullYear() === activeDate.getFullYear() ? pickerDate.getMonth() : undefined}
onMonthClick={handleMonthClick}
/>
</>
);
};
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import styles from "@/components/DatePicker/DatePicker.module.scss";
import MonthYearButton from "./MonthYearButton";

type Props = {
years: number[];
selectedYear?: number;
onYearClick: (year: number) => void;
};

const YearGrid = (props: Props) => {
const { years, selectedYear, onYearClick } = props;

return (
<div className={styles.yearSelector} data-testid="DatePickerYearsContainer">
{years.map(year => (
<MonthYearButton key={year} label={year} onClick={() => onYearClick(year)} selected={year === selectedYear} />
))}
</div>
);
};

export default YearGrid;
Original file line number Diff line number Diff line change
@@ -1,28 +1,15 @@
"use client";

import { useCallback, useContext, useEffect, useState } from "react";
import { useContext } from "react";
import { DatePickerContext } from "@/components/DatePicker/context/DatePickerProvider";
import { calculateYears } from "@/components/DatePicker/components/helper";
import Header from "@/components/DatePicker/components/Header/Header";
import MonthYearButton from "./MonthYearButton";
import YearGrid from "./YearGrid";
import useYearPage from "./useYearPage";
import styles from "@/components/DatePicker/DatePicker.module.scss";

const YearSelector = () => {
const { pickerDate, setPickerDate, setPicker, previousTab, onPickerChange, size } = useContext(DatePickerContext);
const [years, setYears] = useState<number[]>([]);
const displayedYearsCount = 16;

useEffect(() => {
setYears(calculateYears(pickerDate.getFullYear() - displayedYearsCount / 2, pickerDate.getFullYear() + displayedYearsCount / 2));
}, [pickerDate]);

const prevClickHandler = useCallback(() => {
setYears(calculateYears(years[0] - displayedYearsCount, years[0]));
}, [years]);

const nextClickHandler = useCallback(() => {
setYears(calculateYears(years[years.length - 1] + 1, years[years.length - 1] + displayedYearsCount + 1));
}, [years]);
const { years, showPrevPage, showNextPage } = useYearPage(pickerDate.getFullYear());

const handleYearClick = (year: number) => {
const newPickerDate = new Date(pickerDate.getTime());
Expand All @@ -34,19 +21,9 @@ const YearSelector = () => {

return (
<>
<Header
size={size}
year={`${pickerDate.getFullYear()}`}
onPrevClick={prevClickHandler}
onNextClick={nextClickHandler}
disableButtons
/>
<Header size={size} year={`${pickerDate.getFullYear()}`} onPrevClick={showPrevPage} onNextClick={showNextPage} disableButtons />
<hr className={styles.divider} />
<div className={styles.yearSelector} data-testid="DatePickerYearsContainer">
{years.map(year => (
<MonthYearButton label={year} onClick={() => handleYearClick(year)} selected={year === pickerDate.getFullYear()} key={year} />
))}
</div>
<YearGrid years={years} selectedYear={pickerDate.getFullYear()} onYearClick={handleYearClick} />
</>
);
};
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { calculateYears } from "@/components/DatePicker/components/helper";

const displayedYearsCount = 16;

const getFirstYear = (year: number) => year - displayedYearsCount / 2;

/**
* Holds the page of years shown in a year grid. The page is centered on the given year, and moves to it again only when the
* year leaves the page, so picking a year on the current page does not shift the grid.
*/
const useYearPage = (year: number) => {
const [firstYear, setFirstYear] = useState(() => getFirstYear(year));

useEffect(() => {
setFirstYear(first => (year >= first && year < first + displayedYearsCount ? first : getFirstYear(year)));
}, [year]);

const years = useMemo(() => calculateYears(firstYear, firstYear + displayedYearsCount), [firstYear]);
const showPrevPage = useCallback(() => setFirstYear(first => first - displayedYearsCount), []);
const showNextPage = useCallback(() => setFirstYear(first => first + displayedYearsCount), []);

return { years, showPrevPage, showNextPage };
};

export default useYearPage;
30 changes: 30 additions & 0 deletions src/lib/components/MonthPicker/MonthPicker.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import type { Meta, StoryObj } from "@storybook/nextjs";

import MonthPicker from "./MonthPicker";

const meta: Meta<typeof MonthPicker> = {
title: "Components/MonthPicker",
component: MonthPicker,
argTypes: {
value: { control: { type: "number", min: 0, max: 11 } },
variant: { table: { defaultValue: { summary: "borderless" } } },
size: { table: { defaultValue: { summary: "md" } } },
},
args: {
variant: "shadow",
},
};

export default meta;
type Story = StoryObj<typeof MonthPicker>;

export const Primary: Story = {
parameters: {
chromatic: { disableSnapshot: true },
},
};

export const PrimaryStaticForChromatic: Story = {
tags: ["!autodocs", "!dev"],
args: { value: 1 },
};
67 changes: 67 additions & 0 deletions src/lib/components/MonthPicker/MonthPicker.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { act, render } from "@testing-library/react";
import MonthPicker from "./MonthPicker";
import { t, runSnapshotDefaultsAndStandardPropsTest } from "../../../utils/testUtils";
import { StandardPropsWithRef } from "../../types";
import { getDateLocale } from "src/i18n/helper.ts";

describe("MonthPicker", () => {
const { monthsShort } = getDateLocale(t);

runSnapshotDefaultsAndStandardPropsTest((props: StandardPropsWithRef<HTMLDivElement>) => render(<MonthPicker {...props} />), {
assertDefaults: ({ getByTestId, getByText }) => {
// variant: borderless
expect(getByTestId("Picker")).toHaveClass("borderless");
// size: md
expect(getByTestId("Picker")).toHaveClass("md");
// locale: English
expect(getByText(monthsShort[0])).toBeInTheDocument();
},
});

it("should show only the twelve months", () => {
const { getByTestId, queryByText } = render(<MonthPicker />);

expect(getByTestId("DatePickerMonthsContainer").children).toHaveLength(12);
expect(queryByText("arrow_back")).not.toBeInTheDocument();
expect(queryByText("arrow_forward")).not.toBeInTheDocument();
});

it("should show the month in the value prop as selected", () => {
const { getByText } = render(<MonthPicker value={3} />);
expect(getByText(monthsShort[3])).toHaveClass("selected");
});

it("should call onMonthChange with the index of the clicked month and select it", () => {
const onMonthChange = jest.fn();
const { getByText } = render(<MonthPicker value={3} onMonthChange={onMonthChange} />);

act(() => getByText(monthsShort[0]).click());

expect(onMonthChange).toHaveBeenCalledTimes(1);
expect(onMonthChange).toHaveBeenCalledWith(0);
expect(getByText(monthsShort[0])).toHaveClass("selected");
expect(getByText(monthsShort[3])).not.toHaveClass("selected");
});

it("should not call onMonthChange when the selected month is clicked again", () => {
const onMonthChange = jest.fn();
const { getByText } = render(<MonthPicker value={3} onMonthChange={onMonthChange} />);

act(() => getByText(monthsShort[3]).click());
expect(onMonthChange).not.toHaveBeenCalled();
});

it("should select the new month when the value prop changes", () => {
const { rerender, getByText } = render(<MonthPicker value={3} />);

rerender(<MonthPicker value={7} />);
expect(getByText(monthsShort[7])).toHaveClass("selected");
expect(getByText(monthsShort[3])).not.toHaveClass("selected");
});

it("should show the month names in the locale prop", () => {
const locale = { monthsShort: ["M1", "M2", "M3", "M4", "M5", "M6", "M7", "M8", "M9", "M10", "M11", "M12"] };
const { getByText } = render(<MonthPicker locale={locale} />);
expect(getByText("M12")).toBeInTheDocument();
});
});
46 changes: 46 additions & 0 deletions src/lib/components/MonthPicker/MonthPicker.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"use client";

import { useEffect, useState } from "react";
import Picker from "../Motif/Pickers/Picker";
import MonthGrid from "@/components/DatePicker/components/DateSelector/MonthYear/MonthGrid";
import styles from "@/components/DatePicker/DatePicker.module.scss";
import { MonthPickerProps } from "./types";
import { PropsWithRef } from "../../types";
import usePropsWithThemeDefaults from "../../motif/hooks/usePropsWithThemeDefaults";
import { sanitizeModuleClasses } from "../../../utils/cssUtils";
import { useDateLocale } from "src/i18n/useDateLocale.ts";

const MonthPicker = (props: PropsWithRef<MonthPickerProps, HTMLDivElement>) => {
const {
size = "md",
variant = "borderless",
fluid,
value,
onMonthChange,
locale: propsLocale,
className,
style,
ref,
} = usePropsWithThemeDefaults("MonthPicker", props);
const locale = useDateLocale(propsLocale);
const [selectedMonth, setSelectedMonth] = useState(value);

useEffect(() => setSelectedMonth(value), [value]);

const handleMonthClick = (month: number) => {
if (month === selectedMonth) return;
setSelectedMonth(month);
onMonthChange?.(month);
};

return (
<Picker size={size} variant={variant} fluid={fluid} ref={ref} style={style} className={`mtf-MonthPicker ${className ?? ""}`.trim()}>
<div className={sanitizeModuleClasses(styles, "dateSelector", size, fluid && "fluid")}>
<MonthGrid monthsShort={locale.monthsShort} selectedMonth={selectedMonth} onMonthClick={handleMonthClick} />
</div>
</Picker>
);
};

MonthPicker.displayName = "MonthPicker";
export default MonthPicker;
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// Jest Snapshot v1, https://jestjs.io/docs/snapshot-testing

exports[`MonthPicker should render with only required props, have default prop values stated here, and have standard props; className, style and ref props working as expected 1`] = `
<div>
<div
class="Root md borderless mtf-MonthPicker"
data-testid="Picker"
>
<div
class="dateSelector md"
>
<div
class="monthSelector"
data-testid="DatePickerMonthsContainer"
>
<button
type="button"
>
Jan
</button>
<button
type="button"
>
Feb
</button>
<button
type="button"
>
Mar
</button>
<button
type="button"
>
Apr
</button>
<button
type="button"
>
May
</button>
<button
type="button"
>
Jun
</button>
<button
type="button"
>
Jul
</button>
<button
type="button"
>
Aug
</button>
<button
type="button"
>
Sep
</button>
<button
type="button"
>
Oct
</button>
<button
type="button"
>
Nov
</button>
<button
type="button"
>
Dec
</button>
</div>
</div>
</div>
</div>
`;
1 change: 1 addition & 0 deletions src/lib/components/MonthPicker/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from "./MonthPicker";
Loading
Loading