🚨(lint) update file for prettier 3.0.0

Prettier 3.0.0 comes with new standards so we need to upgrade our files
to comply with it.
This commit is contained in:
Nathan Vasse
2023-07-18 15:43:56 +02:00
committed by NathanVss
parent 5f63c2a606
commit d85f9edac8
61 changed files with 421 additions and 419 deletions

View File

@@ -6,5 +6,5 @@ import { App } from "./App";
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode> <React.StrictMode>
<App /> <App />
</React.StrictMode> </React.StrictMode>,
); );

View File

@@ -33,7 +33,7 @@ describe("<Button/>", () => {
render( render(
<Button icon={<div>Icon</div>} iconPosition="right"> <Button icon={<div>Icon</div>} iconPosition="right">
Test button Test button
</Button> </Button>,
); );
const button = screen.getByText("Test button"); const button = screen.getByText("Test button");
const classes = Array.from(button.classList); const classes = Array.from(button.classList);
@@ -57,7 +57,7 @@ describe("<Button/>", () => {
render( render(
<Button onClick={handleClick} disabled={true}> <Button onClick={handleClick} disabled={true}>
Test button Test button
</Button> </Button>,
); );
const button = screen.getByRole("button", { name: "Test button" }); const button = screen.getByRole("button", { name: "Test button" });
expect(handleClick).not.toBeCalled(); expect(handleClick).not.toBeCalled();

View File

@@ -22,7 +22,7 @@ export const Button = forwardRef<HTMLButtonElement, Props>(
fullWidth, fullWidth,
...props ...props
}, },
ref ref,
) => { ) => {
const classes = [ const classes = [
"c__button", "c__button",
@@ -49,5 +49,5 @@ export const Button = forwardRef<HTMLButtonElement, Props>(
{!!icon && iconPosition === "right" && icon} {!!icon && iconPosition === "right" && icon}
</button> </button>
); );
} },
); );

View File

@@ -19,7 +19,7 @@ describe("<DataList/>", () => {
columns={[{ field: "firstName" }, { field: "lastName" }]} columns={[{ field: "firstName" }, { field: "lastName" }]}
rows={rows} rows={rows}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const table = screen.getByRole("table"); const table = screen.getByRole("table");

View File

@@ -42,7 +42,7 @@ describe("<SimpleDataGrid/>", () => {
]} ]}
rows={rows} rows={rows}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const table = screen.getByRole("table"); const table = screen.getByRole("table");
@@ -106,7 +106,7 @@ describe("<SimpleDataGrid/>", () => {
}, },
]} ]}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
// Verify first page rows. // Verify first page rows.
@@ -309,7 +309,7 @@ describe("<SimpleDataGrid/>", () => {
}, },
]} ]}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
// Verify first page rows are sorted by firstName ASC. // Verify first page rows are sorted by firstName ASC.
@@ -461,7 +461,7 @@ describe("<SimpleDataGrid/>", () => {
}, },
]} ]}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
// Make sure the sort is enabled on the first name column. // Make sure the sort is enabled on the first name column.
@@ -506,7 +506,7 @@ describe("<SimpleDataGrid/>", () => {
]} ]}
rows={rows} rows={rows}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
screen.getByRole("img", { name: /illustration of an empty table/i }); screen.getByRole("img", { name: /illustration of an empty table/i });
@@ -526,12 +526,12 @@ describe("<SimpleDataGrid/>", () => {
rows={rows} rows={rows}
isLoading={true} isLoading={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
// Verify that the empty state is not rendered. // Verify that the empty state is not rendered.
expect( expect(
screen.queryByRole("img", { name: /illustration of an empty table/i }) screen.queryByRole("img", { name: /illustration of an empty table/i }),
).toBeNull(); ).toBeNull();
expect(screen.queryByText(/this table is empty/i)).toBeNull(); expect(screen.queryByText(/this table is empty/i)).toBeNull();

View File

@@ -52,8 +52,8 @@ export const SimpleDataGrid = <T extends Row>({
setRealRows( setRealRows(
sortedRows.slice( sortedRows.slice(
(pagination.page - 1) * pagination.pageSize, (pagination.page - 1) * pagination.pageSize,
pagination.page * pagination.pageSize pagination.page * pagination.pageSize,
) ),
); );
} else { } else {
setRealRows(sortedRows); setRealRows(sortedRows);

View File

@@ -97,7 +97,7 @@ describe("<DataGrid/>", () => {
fetchMock.mockIf( fetchMock.mockIf(
"https://example.com/?page=1&sort=lastName&sortOrder=desc", "https://example.com/?page=1&sort=lastName&sortOrder=desc",
() => deferred.promise () => deferred.promise,
); );
render(<Component />); render(<Component />);
@@ -115,8 +115,8 @@ describe("<DataGrid/>", () => {
JSON.stringify({ JSON.stringify({
rows: database.slice(0, 10), rows: database.slice(0, 10),
count: database.length, count: database.length,
}) }),
) ),
); );
// Make sure the loader disappears. // Make sure the loader disappears.
@@ -124,8 +124,8 @@ describe("<DataGrid/>", () => {
expect( expect(
screen.queryByRole("status", { screen.queryByRole("status", {
name: "Loading data", name: "Loading data",
}) }),
).toBeNull() ).toBeNull(),
); );
// Make sure the rows are rendered. // Make sure the rows are rendered.
@@ -154,7 +154,7 @@ describe("<DataGrid/>", () => {
deferred = new Deferred(); deferred = new Deferred();
fetchMock.mockIf( fetchMock.mockIf(
"https://example.com/?page=2&sort=lastName&sortOrder=desc", "https://example.com/?page=2&sort=lastName&sortOrder=desc",
() => deferred.promise () => deferred.promise,
); );
// Go to page 2. // Go to page 2.
@@ -187,8 +187,8 @@ describe("<DataGrid/>", () => {
JSON.stringify({ JSON.stringify({
rows: database.slice(10, 20), rows: database.slice(10, 20),
count: database.length, count: database.length,
}) }),
) ),
); );
// Make sure the loader disappears. // Make sure the loader disappears.
@@ -196,8 +196,8 @@ describe("<DataGrid/>", () => {
expect( expect(
screen.queryByRole("status", { screen.queryByRole("status", {
name: "Loading data", name: "Loading data",
}) }),
).toBeNull() ).toBeNull(),
); );
// Make sure the rows are rendered. // Make sure the rows are rendered.
@@ -330,15 +330,15 @@ describe("<DataGrid/>", () => {
expect(tds.length).toBe(3); expect(tds.length).toBe(3);
expect(tds[0].textContent).toEqual(row.firstName); expect(tds[0].textContent).toEqual(row.firstName);
expect(Array.from(tds[0].classList)).toContain( expect(Array.from(tds[0].classList)).toContain(
"c__datagrid__row__cell--highlight" "c__datagrid__row__cell--highlight",
); );
expect(tds[1].textContent).toEqual(row.lastName); expect(tds[1].textContent).toEqual(row.lastName);
expect(Array.from(tds[1].classList)).not.toContain( expect(Array.from(tds[1].classList)).not.toContain(
"c__datagrid__row__cell--highlight" "c__datagrid__row__cell--highlight",
); );
expect(tds[2].textContent).toEqual(row.email); expect(tds[2].textContent).toEqual(row.email);
expect(Array.from(tds[2].classList)).toContain( expect(Array.from(tds[2].classList)).toContain(
"c__datagrid__row__cell--highlight" "c__datagrid__row__cell--highlight",
); );
}); });
}); });

View File

@@ -58,7 +58,7 @@ export const ClientSideWithoutPagination = () => {
email: faker.internet.email(), email: faker.internet.email(),
address: faker.location.streetAddress(), address: faker.location.streetAddress(),
})), })),
[] [],
); );
return ( return (
<CunninghamProvider> <CunninghamProvider>
@@ -110,7 +110,7 @@ export const ClientSideWithPagination = () => {
year: faker.date.past().getFullYear(), year: faker.date.past().getFullYear(),
price: +faker.commerce.price({ min: 5000, max: 5005 }), price: +faker.commerce.price({ min: 5000, max: 5005 }),
})), })),
[] [],
); );
const [rowSelection, setRowSelection] = useState({}); const [rowSelection, setRowSelection] = useState({});
@@ -163,7 +163,7 @@ export const FullServerSide = () => {
email: faker.internet.email(), email: faker.internet.email(),
address: faker.location.streetAddress(), address: faker.location.streetAddress(),
})), })),
[] [],
); );
const [rowSelection, setRowSelection] = useState({}); const [rowSelection, setRowSelection] = useState({});
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
@@ -194,14 +194,14 @@ export const FullServerSide = () => {
setTimeout(() => { setTimeout(() => {
// Set the pagination length. // Set the pagination length.
pagination.setPagesCount( pagination.setPagesCount(
Math.ceil(sortedDatabase.length / pagination.pageSize) Math.ceil(sortedDatabase.length / pagination.pageSize),
); );
// Select the rows to display on the current page. // Select the rows to display on the current page.
setRows( setRows(
sortedDatabase.slice( sortedDatabase.slice(
(pagination.page - 1) * pagination.pageSize, (pagination.page - 1) * pagination.pageSize,
pagination.page * pagination.pageSize pagination.page * pagination.pageSize,
) ),
); );
setIsLoading(false); setIsLoading(false);
}, 1000); }, 1000);
@@ -261,7 +261,7 @@ export const DataListOnly = () => {
title: faker.word.sample(), title: faker.word.sample(),
date: faker.date.past({ years: 1 }).toISOString(), date: faker.date.past({ years: 1 }).toISOString(),
})), })),
[] [],
); );
return ( return (

View File

@@ -84,11 +84,11 @@ export const DataGrid = <T extends Row>({
*/ */
const paginationState = useMemo( const paginationState = useMemo(
() => paginationToPaginationState(pagination), () => paginationToPaginationState(pagination),
[pagination] [pagination],
); );
const headlessSorting = useMemo( const headlessSorting = useMemo(
() => sortModelToSortingState(sortModel), () => sortModelToSortingState(sortModel),
[sortModel] [sortModel],
); );
/** /**
@@ -110,7 +110,7 @@ export const DataGrid = <T extends Row>({
// a TS error. // a TS error.
if (typeof newHeadlessSorting === "function") { if (typeof newHeadlessSorting === "function") {
onSortModelChange?.( onSortModelChange?.(
sortingStateToSortModel(newHeadlessSorting(headlessSorting)) sortingStateToSortModel(newHeadlessSorting(headlessSorting)),
); );
} }
}, },
@@ -183,7 +183,7 @@ export const DataGrid = <T extends Row>({
> >
{flexRender( {flexRender(
header.column.columnDef.header, header.column.columnDef.header,
header.getContext() header.getContext(),
)} )}
{header.column.getIsSorted() === "asc" && ( {header.column.getIsSorted() === "asc" && (
<span className="material-icons"> <span className="material-icons">
@@ -226,7 +226,7 @@ export const DataGrid = <T extends Row>({
> >
{flexRender( {flexRender(
cell.column.columnDef.cell, cell.column.columnDef.cell,
cell.getContext() cell.getContext(),
)} )}
</td> </td>
); );

View File

@@ -92,7 +92,7 @@ export const sortingStateToSortModel = (sorting: SortingState): SortModel => {
}; };
export const paginationToPaginationState = ( export const paginationToPaginationState = (
pagination?: PaginationProps pagination?: PaginationProps,
): PaginationState | undefined => { ): PaginationState | undefined => {
if (!pagination) { if (!pagination) {
return undefined; return undefined;

View File

@@ -48,14 +48,14 @@ describe("<Checkbox/>", () => {
render(<Checkbox label="Agree" state="success" text="Success text" />); render(<Checkbox label="Agree" state="success" text="Success text" />);
expect(screen.getByText("Success text")).toBeInTheDocument(); expect(screen.getByText("Success text")).toBeInTheDocument();
expect( expect(
document.querySelector(".c__field.c__field--success") document.querySelector(".c__field.c__field--success"),
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
it("renders with state=error", async () => { it("renders with state=error", async () => {
render(<Checkbox label="Agree" state="error" text="Error text" />); render(<Checkbox label="Agree" state="error" text="Error text" />);
expect(screen.getByText("Error text")).toBeInTheDocument(); expect(screen.getByText("Error text")).toBeInTheDocument();
expect( expect(
document.querySelector(".c__field.c__field--error") document.querySelector(".c__field.c__field--error"),
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
@@ -64,7 +64,7 @@ describe("<Checkbox/>", () => {
<CheckboxGroup> <CheckboxGroup>
<Checkbox label="Agree" /> <Checkbox label="Agree" />
<Checkbox label="Disagree" /> <Checkbox label="Disagree" />
</CheckboxGroup> </CheckboxGroup>,
); );
screen.getByRole("checkbox", { screen.getByRole("checkbox", {
name: "Agree", name: "Agree",
@@ -78,7 +78,7 @@ describe("<Checkbox/>", () => {
<CheckboxGroup text="Text"> <CheckboxGroup text="Text">
<Checkbox label="Agree" /> <Checkbox label="Agree" />
<Checkbox label="Disagree" /> <Checkbox label="Disagree" />
</CheckboxGroup> </CheckboxGroup>,
); );
expect(screen.getByText("Text")).toBeInTheDocument(); expect(screen.getByText("Text")).toBeInTheDocument();
}); });
@@ -87,11 +87,11 @@ describe("<Checkbox/>", () => {
<CheckboxGroup state="success" text="Success text"> <CheckboxGroup state="success" text="Success text">
<Checkbox label="Agree" /> <Checkbox label="Agree" />
<Checkbox label="Disagree" /> <Checkbox label="Disagree" />
</CheckboxGroup> </CheckboxGroup>,
); );
expect(screen.getByText("Success text")).toBeInTheDocument(); expect(screen.getByText("Success text")).toBeInTheDocument();
expect( expect(
document.querySelector(".c__checkbox__group.c__field.c__field--success") document.querySelector(".c__checkbox__group.c__field.c__field--success"),
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
it("renders with group state=error", async () => { it("renders with group state=error", async () => {
@@ -99,11 +99,11 @@ describe("<Checkbox/>", () => {
<CheckboxGroup state="error" text="Error text"> <CheckboxGroup state="error" text="Error text">
<Checkbox label="Agree" /> <Checkbox label="Agree" />
<Checkbox label="Disagree" /> <Checkbox label="Disagree" />
</CheckboxGroup> </CheckboxGroup>,
); );
expect(screen.getByText("Error text")).toBeInTheDocument(); expect(screen.getByText("Error text")).toBeInTheDocument();
expect( expect(
document.querySelector(".c__checkbox__group.c__field.c__field--error") document.querySelector(".c__checkbox__group.c__field.c__field--error"),
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
}); });

View File

@@ -100,7 +100,7 @@ const CalendarAux = forwardRef(
nextButtonProps, nextButtonProps,
calendarProps, calendarProps,
}: CalendarAuxProps, }: CalendarAuxProps,
ref: Ref<HTMLDivElement> ref: Ref<HTMLDivElement>,
) => { ) => {
const { t } = useCunningham(); const { t } = useCunningham();
@@ -118,7 +118,7 @@ const CalendarAux = forwardRef(
const monthItems: Array<Option> = useMemo(() => { const monthItems: Array<Option> = useMemo(() => {
// Note that in some calendar systems, such as the Hebrew, the number of months may differ between years. // Note that in some calendar systems, such as the Hebrew, the number of months may differ between years.
const numberOfMonths = state.focusedDate.calendar.getMonthsInYear( const numberOfMonths = state.focusedDate.calendar.getMonthsInYear(
state.focusedDate state.focusedDate,
); );
return range(1, numberOfMonths).map((monthNumber) => { return range(1, numberOfMonths).map((monthNumber) => {
const date = state.focusedDate.set({ month: monthNumber }); const date = state.focusedDate.set({ month: monthNumber });
@@ -134,15 +134,15 @@ const CalendarAux = forwardRef(
const yearItems: Array<Option> = useMemo(() => { const yearItems: Array<Option> = useMemo(() => {
const calendarCurrentUser = createCalendar( const calendarCurrentUser = createCalendar(
new Intl.DateTimeFormat().resolvedOptions().calendar new Intl.DateTimeFormat().resolvedOptions().calendar,
); );
const minDate = toCalendar( const minDate = toCalendar(
new CalendarDate(new GregorianCalendar(), minYear, 1, 1), new CalendarDate(new GregorianCalendar(), minYear, 1, 1),
calendarCurrentUser calendarCurrentUser,
); );
const maxDate = toCalendar( const maxDate = toCalendar(
new CalendarDate(new GregorianCalendar(), maxYear, 12, 31), new CalendarDate(new GregorianCalendar(), maxYear, 12, 31),
calendarCurrentUser calendarCurrentUser,
); );
return range(minDate.year, maxDate.year).map((yearNumber) => { return range(minDate.year, maxDate.year).map((yearNumber) => {
const date = state.focusedDate.set({ year: yearNumber }); const date = state.focusedDate.set({ year: yearNumber });
@@ -158,7 +158,7 @@ const CalendarAux = forwardRef(
const useDownshiftSelect = ( const useDownshiftSelect = (
key: string, key: string,
items: Array<Option> items: Array<Option>,
): UseSelectReturnValue<Option> => { ): UseSelectReturnValue<Option> => {
return useSelect({ return useSelect({
items, items,
@@ -192,12 +192,12 @@ const CalendarAux = forwardRef(
const getToggleButtonProps = ( const getToggleButtonProps = (
key: string, key: string,
items: Array<Option>, items: Array<Option>,
downshift: UseSelectReturnValue<Option> downshift: UseSelectReturnValue<Option>,
) => ({ ) => ({
...downshift.getToggleButtonProps(), ...downshift.getToggleButtonProps(),
onClick: () => { onClick: () => {
const selectedItem = items.find( const selectedItem = items.find(
(item) => item.value === state.focusedDate[key as keyof CalendarDate] (item) => item.value === state.focusedDate[key as keyof CalendarDate],
); );
if (selectedItem) { if (selectedItem) {
downshift.selectItem(selectedItem); downshift.selectItem(selectedItem);
@@ -205,7 +205,7 @@ const CalendarAux = forwardRef(
downshift.toggleMenu(); downshift.toggleMenu();
}, },
"aria-label": t( "aria-label": t(
`components.forms.date_picker.${key}_select_button_aria_label` `components.forms.date_picker.${key}_select_button_aria_label`,
), ),
}); });
@@ -228,7 +228,7 @@ const CalendarAux = forwardRef(
{...{ {...{
...prevButtonOtherProps, ...prevButtonOtherProps,
"aria-label": t( "aria-label": t(
"components.forms.date_picker.previous_month_button_aria_label" "components.forms.date_picker.previous_month_button_aria_label",
), ),
}} }}
disabled={isPrevButtonDisabled} disabled={isPrevButtonDisabled}
@@ -243,7 +243,7 @@ const CalendarAux = forwardRef(
{...getToggleButtonProps("month", monthItems, downshiftMonth)} {...getToggleButtonProps("month", monthItems, downshiftMonth)}
> >
{selectedMonthItemFormatter.format( {selectedMonthItemFormatter.format(
state.focusedDate.toDate(state.timeZone) state.focusedDate.toDate(state.timeZone),
)} )}
</Button> </Button>
<Button <Button
@@ -253,7 +253,7 @@ const CalendarAux = forwardRef(
{...{ {...{
...nextButtonOtherProps, ...nextButtonOtherProps,
"aria-label": t( "aria-label": t(
"components.forms.date_picker.next_month_button_aria_label" "components.forms.date_picker.next_month_button_aria_label",
), ),
}} }}
disabled={isNextButtonDisabled} disabled={isNextButtonDisabled}
@@ -272,7 +272,7 @@ const CalendarAux = forwardRef(
state.focusedDate.add({ years: -1 }).year state.focusedDate.add({ years: -1 }).year
} }
aria-label={t( aria-label={t(
"components.forms.date_picker.previous_year_button_aria_label" "components.forms.date_picker.previous_year_button_aria_label",
)} )}
/> />
<Button <Button
@@ -284,7 +284,7 @@ const CalendarAux = forwardRef(
{...getToggleButtonProps("year", yearItems, downshiftYear)} {...getToggleButtonProps("year", yearItems, downshiftYear)}
> >
{yearItemsFormatter.format( {yearItemsFormatter.format(
state.focusedDate.toDate(state.timeZone) state.focusedDate.toDate(state.timeZone),
)} )}
</Button> </Button>
<Button <Button
@@ -297,7 +297,7 @@ const CalendarAux = forwardRef(
state.maxValue.year < state.focusedDate.add({ years: 1 }).year state.maxValue.year < state.focusedDate.add({ years: 1 }).year
} }
aria-label={t( aria-label={t(
"components.forms.date_picker.next_year_button_aria_label" "components.forms.date_picker.next_year_button_aria_label",
)} )}
/> />
</div> </div>
@@ -310,7 +310,7 @@ const CalendarAux = forwardRef(
<DropdownValues options={yearItems} downShift={downshiftYear} /> <DropdownValues options={yearItems} downShift={downshiftYear} />
</div> </div>
); );
} },
); );
export const Calendar = (props: CalendarProps<DateValue>) => { export const Calendar = (props: CalendarProps<DateValue>) => {

View File

@@ -74,9 +74,9 @@ export const CalendarCell = ({ state, date }: CalendarCellProps) => {
isSelected, isSelected,
"c__calendar__wrapper__grid__week-row__button--today": isToday( "c__calendar__wrapper__grid__week-row__button--today": isToday(
date, date,
getLocalTimeZone() getLocalTimeZone(),
), ),
} },
)} )}
disabled={isDisabled} disabled={isDisabled}
{...buttonProps} {...buttonProps}

View File

@@ -29,7 +29,7 @@ export const CalendarGrid = ({
startDate: state.visibleRange.start, startDate: state.visibleRange.start,
endDate: endOfMonth(state.visibleRange.start), endDate: endOfMonth(state.visibleRange.start),
}, },
state state,
); );
const shortDayFormatter = useDateFormatter({ const shortDayFormatter = useDateFormatter({
@@ -61,7 +61,7 @@ export const CalendarGrid = ({
.getDatesInWeek(weekIndex) .getDatesInWeek(weekIndex)
.map( .map(
(date, i) => (date, i) =>
date && <CalendarCell key={i} state={state} date={date} /> date && <CalendarCell key={i} state={state} date={date} />,
)} )}
</tr> </tr>
))} ))}

View File

@@ -20,7 +20,7 @@ describe("<DatePicker/>", () => {
expect(calendar).toBeDefined(); expect(calendar).toBeDefined();
expect(calendar).not.toBeNull(); expect(calendar).not.toBeNull();
expect(Array.from(calendar!.classList)).contains( expect(Array.from(calendar!.classList)).contains(
"c__calendar__wrapper--opened" "c__calendar__wrapper--opened",
); );
}; };
@@ -28,7 +28,7 @@ describe("<DatePicker/>", () => {
const dateField = screen.queryByRole("presentation"); const dateField = screen.queryByRole("presentation");
expect(dateField).toBeTruthy(); expect(dateField).toBeTruthy();
expect(Array.from(dateField!.parentElement!.classList)).contains( expect(Array.from(dateField!.parentElement!.classList)).contains(
"c__date-picker__inner--collapsed" "c__date-picker__inner--collapsed",
); );
}; };
@@ -38,12 +38,12 @@ describe("<DatePicker/>", () => {
const expectDatesToBeEqual = ( const expectDatesToBeEqual = (
firstDate: Date | string | undefined | null, firstDate: Date | string | undefined | null,
secondDate: Date | string | undefined | null secondDate: Date | string | undefined | null,
) => { ) => {
expect(firstDate).toBeDefined(); expect(firstDate).toBeDefined();
expect(secondDate).toBeDefined(); expect(secondDate).toBeDefined();
expect(new Date(firstDate!).toLocaleDateString()).eq( expect(new Date(firstDate!).toLocaleDateString()).eq(
new Date(secondDate!).toLocaleDateString() new Date(secondDate!).toLocaleDateString(),
); );
}; };
@@ -72,7 +72,7 @@ describe("<DatePicker/>", () => {
const expectMenuToBeClosed = (menu: HTMLElement) => { const expectMenuToBeClosed = (menu: HTMLElement) => {
expect(Array.from(menu.classList)).not.contains( expect(Array.from(menu.classList)).not.contains(
"c__calendar__menu--opened" "c__calendar__menu--opened",
); );
}; };
@@ -88,7 +88,7 @@ describe("<DatePicker/>", () => {
render( render(
<CunninghamProvider> <CunninghamProvider>
<DatePicker label="Pick a date" name="datepicker" /> <DatePicker label="Pick a date" name="datepicker" />
</CunninghamProvider> </CunninghamProvider>,
); );
const [input, button] = await screen.findAllByRole("button"); const [input, button] = await screen.findAllByRole("button");
@@ -135,7 +135,7 @@ describe("<DatePicker/>", () => {
render( render(
<CunninghamProvider> <CunninghamProvider>
<DatePicker label="Pick a date" name="datepicker" /> <DatePicker label="Pick a date" name="datepicker" />
</CunninghamProvider> </CunninghamProvider>,
); );
const [input, toggleButton] = await screen.findAllByRole("button")!; const [input, toggleButton] = await screen.findAllByRole("button")!;
@@ -154,12 +154,12 @@ describe("<DatePicker/>", () => {
render( render(
<CunninghamProvider> <CunninghamProvider>
<DatePicker label="Pick a date" name="datepicker" /> <DatePicker label="Pick a date" name="datepicker" />
</CunninghamProvider> </CunninghamProvider>,
); );
// Get elements that should receive focus when no date is picked. // Get elements that should receive focus when no date is picked.
const [input, toggleButton] = await screen.findAllByRole("button")!; const [input, toggleButton] = await screen.findAllByRole("button")!;
const [monthSegment, daySegment, yearSegment] = await screen.findAllByRole( const [monthSegment, daySegment, yearSegment] = await screen.findAllByRole(
"spinbutton" "spinbutton",
)!; )!;
await user.keyboard("{Tab}"); await user.keyboard("{Tab}");
@@ -187,7 +187,7 @@ describe("<DatePicker/>", () => {
name="datepicker" name="datepicker"
defaultValue="2023-04-25" defaultValue="2023-04-25"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
// Get elements that should receive focus when a date is already picked. // Get elements that should receive focus when a date is already picked.
@@ -196,7 +196,7 @@ describe("<DatePicker/>", () => {
name: "Clear date", name: "Clear date",
}); });
const [monthSegment, daySegment, yearSegment] = await screen.findAllByRole( const [monthSegment, daySegment, yearSegment] = await screen.findAllByRole(
"spinbutton" "spinbutton",
)!; )!;
// Navigate through elements using Tab. // Navigate through elements using Tab.
@@ -224,7 +224,7 @@ describe("<DatePicker/>", () => {
render( render(
<CunninghamProvider> <CunninghamProvider>
<DatePicker label="Pick a date" name="datepicker" /> <DatePicker label="Pick a date" name="datepicker" />
</CunninghamProvider> </CunninghamProvider>,
); );
const [input, toggleButton] = await screen.findAllByRole("button"); const [input, toggleButton] = await screen.findAllByRole("button");
await user.click(input); await user.click(input);
@@ -235,8 +235,8 @@ describe("<DatePicker/>", () => {
// Select the first clickable grid-cell. // Select the first clickable grid-cell.
const gridCellButton = within( const gridCellButton = within(
gridCells.filter( gridCells.filter(
(gridCell) => !gridCell.getAttribute("aria-disabled") (gridCell) => !gridCell.getAttribute("aria-disabled"),
)![0] )![0],
).getByRole("button")!; ).getByRole("button")!;
// Pick a date. // Pick a date.
@@ -254,7 +254,7 @@ describe("<DatePicker/>", () => {
const selectedDate = within( const selectedDate = within(
screen.getByRole("gridcell", { screen.getByRole("gridcell", {
selected: true, selected: true,
})! })!,
) )
.getByRole("button")! .getByRole("button")!
.getAttribute("aria-label") .getAttribute("aria-label")
@@ -276,10 +276,10 @@ describe("<DatePicker/>", () => {
name="datepicker" name="datepicker"
defaultValue="2023-04-05" defaultValue="2023-04-05"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const [monthSegment, daySegment, yearSegment] = await screen.findAllByRole( const [monthSegment, daySegment, yearSegment] = await screen.findAllByRole(
"spinbutton" "spinbutton",
)!; )!;
// Select the first segment, month one. // Select the first segment, month one.
await user.click(monthSegment); await user.click(monthSegment);
@@ -312,10 +312,10 @@ describe("<DatePicker/>", () => {
defaultValue="2023-04-05" defaultValue="2023-04-05"
minValue="2022-12-03" minValue="2022-12-03"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const [monthSegment, daySegment, yearSegment] = await screen.findAllByRole( const [monthSegment, daySegment, yearSegment] = await screen.findAllByRole(
"spinbutton" "spinbutton",
)!; )!;
// Select the first segment, month one. // Select the first segment, month one.
await user.click(monthSegment); await user.click(monthSegment);
@@ -356,7 +356,7 @@ describe("<DatePicker/>", () => {
name="datepicker" name="datepicker"
defaultValue={defaultValue} defaultValue={defaultValue}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
// Get picked date. // Get picked date.
const dateFieldContent = screen.getByRole("presentation").textContent; const dateFieldContent = screen.getByRole("presentation").textContent;
@@ -377,10 +377,10 @@ describe("<DatePicker/>", () => {
defaultValue={defaultValue} defaultValue={defaultValue}
value={value} value={value}
/> />
</CunninghamProvider> </CunninghamProvider>,
) ),
).toThrow( ).toThrow(
"You cannot use both defaultValue and value props on DatePicker component" "You cannot use both defaultValue and value props on DatePicker component",
); );
}); });
@@ -396,12 +396,12 @@ describe("<DatePicker/>", () => {
name="datepicker" name="datepicker"
defaultValue={invalidDate} defaultValue={invalidDate}
/> />
</CunninghamProvider> </CunninghamProvider>,
) ),
).toThrow( ).toThrow(
"Invalid date format when initializing props on DatePicker component" "Invalid date format when initializing props on DatePicker component",
); );
} },
); );
it("clears date", async () => { it("clears date", async () => {
@@ -414,7 +414,7 @@ describe("<DatePicker/>", () => {
name="datepicker" name="datepicker"
defaultValue={defaultValue} defaultValue={defaultValue}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const clearButton = screen.getByRole("button", { const clearButton = screen.getByRole("button", {
name: "Clear date", name: "Clear date",
@@ -448,7 +448,7 @@ describe("<DatePicker/>", () => {
defaultValue="2023-01-01" defaultValue="2023-01-01"
minValue="2023-02-01" minValue="2023-02-01"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
await expectDatePickerStateToBe("invalid"); await expectDatePickerStateToBe("invalid");
}); });
@@ -462,7 +462,7 @@ describe("<DatePicker/>", () => {
defaultValue="2023-03-01" defaultValue="2023-03-01"
maxValue="2023-02-01" maxValue="2023-02-01"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
await expectDatePickerStateToBe("invalid"); await expectDatePickerStateToBe("invalid");
}); });
@@ -478,7 +478,7 @@ describe("<DatePicker/>", () => {
maxValue="2023-04-01" maxValue="2023-04-01"
minValue="2023-05-01" minValue="2023-05-01"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
await expectDatePickerStateToBe("invalid"); await expectDatePickerStateToBe("invalid");
}); });
@@ -517,7 +517,7 @@ describe("<DatePicker/>", () => {
expectCalendarToBeOpen(); expectCalendarToBeOpen();
const gridCell = within( const gridCell = within(
await screen.getByRole("gridcell", { name: "12" }) await screen.getByRole("gridcell", { name: "12" }),
).getByRole("button")!; ).getByRole("button")!;
// Select a new value in the calendar grid. // Select a new value in the calendar grid.
@@ -547,7 +547,7 @@ describe("<DatePicker/>", () => {
defaultValue="2023-03-01" defaultValue="2023-03-01"
disabled={true} disabled={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
await expectDatePickerStateToBe("disabled"); await expectDatePickerStateToBe("disabled");
@@ -559,13 +559,13 @@ describe("<DatePicker/>", () => {
// Make sure the clear button is not visible and disabled. // Make sure the clear button is not visible and disabled.
expect( expect(
screen.queryByRole("button", { name: "Clear date", hidden: true }) screen.queryByRole("button", { name: "Clear date", hidden: true }),
).toBeDisabled(); ).toBeDisabled();
// Make sure each segment of the date field is disabled. // Make sure each segment of the date field is disabled.
const dateFieldInputs = await screen.queryAllByRole("spinbutton"); const dateFieldInputs = await screen.queryAllByRole("spinbutton");
dateFieldInputs.forEach((dateFieldInput) => dateFieldInputs.forEach((dateFieldInput) =>
expect(dateFieldInput).toHaveAttribute("aria-disabled") expect(dateFieldInput).toHaveAttribute("aria-disabled"),
); );
}); });
@@ -578,7 +578,7 @@ describe("<DatePicker/>", () => {
name="datepicker" name="datepicker"
defaultValue="2023-03-01" defaultValue="2023-03-01"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const toggleButton = (await screen.findAllByRole("button"))![1]; const toggleButton = (await screen.findAllByRole("button"))![1];
await user.click(toggleButton); await user.click(toggleButton);
@@ -674,7 +674,7 @@ describe("<DatePicker/>", () => {
name="datepicker" name="datepicker"
defaultValue={defaultValue} defaultValue={defaultValue}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const toggleButton = (await screen.findAllByRole("button"))![1]; const toggleButton = (await screen.findAllByRole("button"))![1];
await user.click(toggleButton); await user.click(toggleButton);
@@ -712,7 +712,7 @@ describe("<DatePicker/>", () => {
name="datepicker" name="datepicker"
defaultValue={defaultValue} defaultValue={defaultValue}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const toggleButton = (await screen.findAllByRole("button"))![1]; const toggleButton = (await screen.findAllByRole("button"))![1];
await user.click(toggleButton); await user.click(toggleButton);
@@ -754,7 +754,7 @@ describe("<DatePicker/>", () => {
minValue={minValue} minValue={minValue}
maxValue={maxValue} maxValue={maxValue}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const toggleButton = (await screen.findAllByRole("button"))![1]; const toggleButton = (await screen.findAllByRole("button"))![1];
@@ -787,7 +787,7 @@ describe("<DatePicker/>", () => {
minValue={minValue} minValue={minValue}
maxValue={maxValue} maxValue={maxValue}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const toggleButton = (await screen.findAllByRole("button"))![1]; const toggleButton = (await screen.findAllByRole("button"))![1];
@@ -819,7 +819,7 @@ describe("<DatePicker/>", () => {
minValue={minValue} minValue={minValue}
maxValue={maxValue} maxValue={maxValue}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
// Open the calendar. // Open the calendar.
@@ -855,7 +855,9 @@ describe("<DatePicker/>", () => {
try { try {
const button = within(gridCell).getByRole("button")!; const button = within(gridCell).getByRole("button")!;
const value = new Date( const value = new Date(
button.getAttribute("aria-label")!.replace("First available date", "") button
.getAttribute("aria-label")!
.replace("First available date", ""),
); );
expect(value.getMonth() === minValue.getMonth()); expect(value.getMonth() === minValue.getMonth());
if (value.getDate() < minValue.getDate()) { if (value.getDate() < minValue.getDate()) {
@@ -866,7 +868,7 @@ describe("<DatePicker/>", () => {
} catch (e: any) { } catch (e: any) {
// Make sure outside grid-cells render any button element, even disabled. // Make sure outside grid-cells render any button element, even disabled.
expect(e.message).contains( expect(e.message).contains(
'Unable to find an accessible element with the role "button"' 'Unable to find an accessible element with the role "button"',
); );
} }
}); });
@@ -897,7 +899,7 @@ describe("<DatePicker/>", () => {
} catch (e: any) { } catch (e: any) {
// Make sure outside grid-cells render any button element, even disabled. // Make sure outside grid-cells render any button element, even disabled.
expect(e.message).contains( expect(e.message).contains(
'Unable to find an accessible element with the role "button"' 'Unable to find an accessible element with the role "button"',
); );
} }
}); });
@@ -913,7 +915,7 @@ describe("<DatePicker/>", () => {
name="datepicker" name="datepicker"
defaultValue={defaultValue} defaultValue={defaultValue}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const toggleButton = (await screen.findAllByRole("button"))![1]; const toggleButton = (await screen.findAllByRole("button"))![1];
await user.click(toggleButton); await user.click(toggleButton);
@@ -931,7 +933,7 @@ describe("<DatePicker/>", () => {
// Make sure the selected item matched the default value. // Make sure the selected item matched the default value.
let focusedMonth = monthDropdown.textContent?.replace( let focusedMonth = monthDropdown.textContent?.replace(
"arrow_drop_down", "arrow_drop_down",
"" "",
); );
expect(focusedMonth).eq("May"); expect(focusedMonth).eq("May");
@@ -964,7 +966,7 @@ describe("<DatePicker/>", () => {
name="datepicker" name="datepicker"
defaultValue={defaultValue} defaultValue={defaultValue}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const toggleButton = (await screen.findAllByRole("button"))![1]; const toggleButton = (await screen.findAllByRole("button"))![1];
await user.click(toggleButton); await user.click(toggleButton);
@@ -1011,7 +1013,7 @@ describe("<DatePicker/>", () => {
name="datepicker" name="datepicker"
defaultValue={defaultValue} defaultValue={defaultValue}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
// Open the calendar. // Open the calendar.
const toggleButton = (await screen.findAllByRole("button"))![1]; const toggleButton = (await screen.findAllByRole("button"))![1];
@@ -1025,7 +1027,7 @@ describe("<DatePicker/>", () => {
try { try {
const button = within(gridCell).getByRole("button"); const button = within(gridCell).getByRole("button");
const value = new Date( const value = new Date(
button.getAttribute("aria-label")!.replace("selected", "") button.getAttribute("aria-label")!.replace("selected", ""),
); );
expect(button).not.toBeDisabled(); expect(button).not.toBeDisabled();
expect(defaultValue.getMonth() === value.getMonth()); expect(defaultValue.getMonth() === value.getMonth());
@@ -1033,7 +1035,7 @@ describe("<DatePicker/>", () => {
} catch (e: any) { } catch (e: any) {
// Make sure outside grid-cells render any button element, even disabled. // Make sure outside grid-cells render any button element, even disabled.
expect(e.message).contains( expect(e.message).contains(
'Unable to find an accessible element with the role "button"' 'Unable to find an accessible element with the role "button"',
); );
} }
}); });
@@ -1051,7 +1053,7 @@ describe("<DatePicker/>", () => {
name="datepicker" name="datepicker"
defaultValue={defaultValue} defaultValue={defaultValue}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
// Open calendar. // Open calendar.
@@ -1084,7 +1086,7 @@ describe("<DatePicker/>", () => {
name="datepicker" name="datepicker"
defaultValue={defaultValue} defaultValue={defaultValue}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const toggleButton = (await screen.findAllByRole("button"))![1]; const toggleButton = (await screen.findAllByRole("button"))![1];
@@ -1115,7 +1117,7 @@ describe("<DatePicker/>", () => {
locale="hi-IN-u-ca-indian" locale="hi-IN-u-ca-indian"
defaultValue="2023-06-25" defaultValue="2023-06-25"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = (await screen.findAllByRole("button"))[0]; const input = (await screen.findAllByRole("button"))[0];
@@ -1160,7 +1162,7 @@ describe("<DatePicker/>", () => {
render( render(
<CunninghamProvider currentLocale="fr-FR"> <CunninghamProvider currentLocale="fr-FR">
<DatePicker label="Pick a date" defaultValue="2023-06-25" /> <DatePicker label="Pick a date" defaultValue="2023-06-25" />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = (await screen.findAllByRole("button"))[0]; const input = (await screen.findAllByRole("button"))[0];
@@ -1209,7 +1211,7 @@ describe("<DatePicker/>", () => {
defaultValue="2023-06-25" defaultValue="2023-06-25"
locale="hi-IN-u-ca-indian" locale="hi-IN-u-ca-indian"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = (await screen.findAllByRole("button"))[0]; const input = (await screen.findAllByRole("button"))[0];
@@ -1257,8 +1259,8 @@ describe("<DatePicker/>", () => {
render( render(
<CunninghamProvider> <CunninghamProvider>
<DatePicker label="Pick a date" locale="111" /> <DatePicker label="Pick a date" locale="111" />
</CunninghamProvider> </CunninghamProvider>,
) ),
).toThrow("Incorrect locale information provided"); ).toThrow("Incorrect locale information provided");
}); });
}); });

View File

@@ -26,7 +26,7 @@ export type DatePickerProps = DatePickerAuxSubProps & {
export const DatePicker = (props: DatePickerProps) => { export const DatePicker = (props: DatePickerProps) => {
if (props.defaultValue && props.value) { if (props.defaultValue && props.value) {
throw new Error( throw new Error(
"You cannot use both defaultValue and value props on DatePicker component" "You cannot use both defaultValue and value props on DatePicker component",
); );
} }
const ref = useRef<HTMLDivElement>(null); const ref = useRef<HTMLDivElement>(null);
@@ -48,12 +48,12 @@ export const DatePicker = (props: DatePickerProps) => {
const { fieldProps, calendarProps, ...pickerProps } = useDatePicker( const { fieldProps, calendarProps, ...pickerProps } = useDatePicker(
options, options,
pickerState, pickerState,
ref ref,
); );
const labelAsPlaceholder = useMemo( const labelAsPlaceholder = useMemo(
() => !isFocused && !pickerState.isOpen && !pickerState.value, () => !isFocused && !pickerState.isOpen && !pickerState.value,
[pickerState.value, pickerState.isOpen, isFocused] [pickerState.value, pickerState.isOpen, isFocused],
); );
const calendar = <Calendar {...calendarProps} />; const calendar = <Calendar {...calendarProps} />;

View File

@@ -65,7 +65,7 @@ const DatePickerAux = forwardRef(
optionalClassName, optionalClassName,
...props ...props
}: DatePickerAuxProps, }: DatePickerAuxProps,
ref: Ref<HTMLDivElement> ref: Ref<HTMLDivElement>,
) => { ) => {
const { t, currentLocale } = useCunningham(); const { t, currentLocale } = useCunningham();
const pickerRef = useRef<HTMLDivElement>(null); const pickerRef = useRef<HTMLDivElement>(null);
@@ -73,7 +73,7 @@ const DatePickerAux = forwardRef(
const isDateInvalid = useMemo( const isDateInvalid = useMemo(
() => () =>
pickerState.validationState === "invalid" || props.state === "error", pickerState.validationState === "invalid" || props.state === "error",
[pickerState.validationState, props.state] [pickerState.validationState, props.state],
); );
// onPress props don't exist on the <Button /> component. // onPress props don't exist on the <Button /> component.
@@ -133,7 +133,7 @@ const DatePickerAux = forwardRef(
"aria-label": t( "aria-label": t(
pickerState.isOpen pickerState.isOpen
? "components.forms.date_picker.toggle_button_aria_label_close" ? "components.forms.date_picker.toggle_button_aria_label_close"
: "components.forms.date_picker.toggle_button_aria_label_open" : "components.forms.date_picker.toggle_button_aria_label_open",
), ),
}} }}
color="tertiary" color="tertiary"
@@ -156,7 +156,7 @@ const DatePickerAux = forwardRef(
icon={<span className="material-icons">cancel</span>} icon={<span className="material-icons">cancel</span>}
onClick={onClear} onClick={onClear}
aria-label={t( aria-label={t(
"components.forms.date_picker.clear_button_aria_label" "components.forms.date_picker.clear_button_aria_label",
)} )}
disabled={disabled} disabled={disabled}
/> />
@@ -174,7 +174,7 @@ const DatePickerAux = forwardRef(
</Field> </Field>
</I18nProvider> </I18nProvider>
); );
} },
); );
export default DatePickerAux; export default DatePickerAux;

View File

@@ -9,12 +9,12 @@ import { Button } from ":/components/Button";
describe("<DateRangePicker/>", () => { describe("<DateRangePicker/>", () => {
const expectDatesToBeEqual = ( const expectDatesToBeEqual = (
firstDate: Date | string | undefined | null, firstDate: Date | string | undefined | null,
secondDate: Date | string | undefined | null secondDate: Date | string | undefined | null,
) => { ) => {
expect(firstDate).toBeDefined(); expect(firstDate).toBeDefined();
expect(secondDate).toBeDefined(); expect(secondDate).toBeDefined();
expect(new Date(firstDate!).toLocaleDateString()).eq( expect(new Date(firstDate!).toLocaleDateString()).eq(
new Date(secondDate!).toLocaleDateString() new Date(secondDate!).toLocaleDateString(),
); );
}; };
@@ -31,7 +31,7 @@ describe("<DateRangePicker/>", () => {
expect(dateFields.length).eq(2); expect(dateFields.length).eq(2);
dateFields.forEach((dateField) => { dateFields.forEach((dateField) => {
expect(Array.from(dateField.parentElement!.classList)).contains( expect(Array.from(dateField.parentElement!.classList)).contains(
"c__date-picker__inner--collapsed" "c__date-picker__inner--collapsed",
); );
}); });
}; };
@@ -48,7 +48,7 @@ describe("<DateRangePicker/>", () => {
expect(calendar).toBeDefined(); expect(calendar).toBeDefined();
expect(calendar).not.toBeNull(); expect(calendar).not.toBeNull();
expect(Array.from(calendar!.classList)).contains( expect(Array.from(calendar!.classList)).contains(
"c__calendar__wrapper--opened" "c__calendar__wrapper--opened",
); );
}; };
@@ -68,7 +68,7 @@ describe("<DateRangePicker/>", () => {
endLabel="Pick a date" endLabel="Pick a date"
name="datepicker" name="datepicker"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const [input, button] = await screen.findAllByRole("button"); const [input, button] = await screen.findAllByRole("button");
@@ -119,7 +119,7 @@ describe("<DateRangePicker/>", () => {
endLabel="End date" endLabel="End date"
name="datepicker" name="datepicker"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
// Get elements that should receive focus when no date is picked. // Get elements that should receive focus when no date is picked.
const [input, toggleButton] = await screen.findAllByRole("button")!; const [input, toggleButton] = await screen.findAllByRole("button")!;
@@ -151,7 +151,7 @@ describe("<DateRangePicker/>", () => {
name="datepicker" name="datepicker"
defaultValue={[start, end]} defaultValue={[start, end]}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
// Get picked date. // Get picked date.
const [startInput, endInput] = await screen.queryAllByRole("presentation"); const [startInput, endInput] = await screen.queryAllByRole("presentation");
@@ -170,7 +170,7 @@ describe("<DateRangePicker/>", () => {
name="datepicker" name="datepicker"
defaultValue={["2023-04-25", "2023-05-25"]} defaultValue={["2023-04-25", "2023-05-25"]}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
// Get elements that should receive focus when a date is already picked. // Get elements that should receive focus when a date is already picked.
@@ -225,7 +225,7 @@ describe("<DateRangePicker/>", () => {
endLabel="End date" endLabel="End date"
name="datepicker" name="datepicker"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const [input, toggleButton] = await screen.findAllByRole("button"); const [input, toggleButton] = await screen.findAllByRole("button");
await user.click(input); await user.click(input);
@@ -236,8 +236,8 @@ describe("<DateRangePicker/>", () => {
// Select the first clickable grid-cell. // Select the first clickable grid-cell.
const startGridCellButton = within( const startGridCellButton = within(
gridCells.filter( gridCells.filter(
(gridCell) => !gridCell.getAttribute("aria-disabled") (gridCell) => !gridCell.getAttribute("aria-disabled"),
)![0] )![0],
).getByRole("button")!; ).getByRole("button")!;
// Pick a start date. // Pick a start date.
@@ -249,8 +249,8 @@ describe("<DateRangePicker/>", () => {
// Select the second clickable grid-cell. // Select the second clickable grid-cell.
const endGridCellButton = within( const endGridCellButton = within(
gridCells.filter( gridCells.filter(
(gridCell) => !gridCell.getAttribute("aria-disabled") (gridCell) => !gridCell.getAttribute("aria-disabled"),
)![1] )![1],
).getByRole("button")!; ).getByRole("button")!;
// Pick an end date. // Pick an end date.
@@ -295,7 +295,7 @@ describe("<DateRangePicker/>", () => {
endLabel="End date" endLabel="End date"
name="datepicker" name="datepicker"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const [input, toggleButton] = await screen.findAllByRole("button"); const [input, toggleButton] = await screen.findAllByRole("button");
await user.click(input); await user.click(input);
@@ -306,8 +306,8 @@ describe("<DateRangePicker/>", () => {
// Select the first clickable grid-cell. // Select the first clickable grid-cell.
const gridCellButton = within( const gridCellButton = within(
gridCells.filter( gridCells.filter(
(gridCell) => !gridCell.getAttribute("aria-disabled") (gridCell) => !gridCell.getAttribute("aria-disabled"),
)![0] )![0],
).getByRole("button")!; ).getByRole("button")!;
// Pick a start date. // Pick a start date.
@@ -358,7 +358,7 @@ describe("<DateRangePicker/>", () => {
defaultValue={["2023-01-01", "2023-01-01"]} defaultValue={["2023-01-01", "2023-01-01"]}
name="datepicker" name="datepicker"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = (await screen.findAllByRole("button"))![0]; const input = (await screen.findAllByRole("button"))![0];
await user.click(input); await user.click(input);
@@ -419,7 +419,7 @@ describe("<DateRangePicker/>", () => {
name="datepicker" name="datepicker"
defaultValue={["2023-01-01", "2023-01-01"]} defaultValue={["2023-01-01", "2023-01-01"]}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = (await screen.findAllByRole("button"))![0]; const input = (await screen.findAllByRole("button"))![0];
await user.click(input); await user.click(input);
@@ -468,7 +468,7 @@ describe("<DateRangePicker/>", () => {
name="datepicker" name="datepicker"
defaultValue={["2023-01-01", "2023-01-01"]} defaultValue={["2023-01-01", "2023-01-01"]}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = (await screen.findAllByRole("button"))![0]; const input = (await screen.findAllByRole("button"))![0];
await user.click(input); await user.click(input);
@@ -516,7 +516,7 @@ describe("<DateRangePicker/>", () => {
endLabel="End date" endLabel="End date"
name="datepicker" name="datepicker"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
// Open calendar to display text segment // Open calendar to display text segment
@@ -575,7 +575,7 @@ describe("<DateRangePicker/>", () => {
endLabel="End date" endLabel="End date"
name="datepicker" name="datepicker"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
// Open calendar to display text segment // Open calendar to display text segment
@@ -640,10 +640,10 @@ describe("<DateRangePicker/>", () => {
defaultValue={["2022-05-25", "2022-05-26"]} defaultValue={["2022-05-25", "2022-05-26"]}
value={["2022-05-25", "2022-05-26"]} value={["2022-05-25", "2022-05-26"]}
/> />
</CunninghamProvider> </CunninghamProvider>,
) ),
).toThrow( ).toThrow(
"You cannot use both defaultValue and value props on DateRangePicker component" "You cannot use both defaultValue and value props on DateRangePicker component",
); );
}); });
@@ -662,10 +662,10 @@ describe("<DateRangePicker/>", () => {
name="datepicker" name="datepicker"
defaultValue={[start, end]} defaultValue={[start, end]}
/> />
</CunninghamProvider> </CunninghamProvider>,
) ),
).toThrow( ).toThrow(
"Invalid date format when initializing props on DatePicker component" "Invalid date format when initializing props on DatePicker component",
); );
}); });
@@ -679,7 +679,7 @@ describe("<DateRangePicker/>", () => {
name="datepicker" name="datepicker"
defaultValue={["2024-05-25", "2022-05-26"]} defaultValue={["2024-05-25", "2022-05-26"]}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
await expectDateRangePickerStateToBe("invalid"); await expectDateRangePickerStateToBe("invalid");
}); });
@@ -696,7 +696,7 @@ describe("<DateRangePicker/>", () => {
name="datepicker" name="datepicker"
defaultValue={[start, end]} defaultValue={[start, end]}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const clearButton = screen.getByRole("button", { const clearButton = screen.getByRole("button", {
@@ -707,7 +707,7 @@ describe("<DateRangePicker/>", () => {
// Date field's value should be set to a placeholder value. // Date field's value should be set to a placeholder value.
const [startInput, endInput] = await screen.queryAllByRole( const [startInput, endInput] = await screen.queryAllByRole(
"presentation" "presentation",
); );
expect(startInput.textContent).eq("mm/dd/yyyy"); expect(startInput.textContent).eq("mm/dd/yyyy");
expect(endInput.textContent).eq("mm/dd/yyyy"); expect(endInput.textContent).eq("mm/dd/yyyy");
@@ -720,8 +720,8 @@ describe("<DateRangePicker/>", () => {
expect(startGridCell.getAttribute("aria-selected")).toBeNull(); expect(startGridCell.getAttribute("aria-selected")).toBeNull();
expect( expect(
startGridCell.classList.contains( startGridCell.classList.contains(
"c__calendar__wrapper__grid__week-row__background--range--start" "c__calendar__wrapper__grid__week-row__background--range--start",
) ),
).toBe(false); ).toBe(false);
// Make sure end grid-cell is not selected anymore. // Make sure end grid-cell is not selected anymore.
@@ -731,8 +731,8 @@ describe("<DateRangePicker/>", () => {
expect(endGridCell.getAttribute("aria-selected")).toBeNull(); expect(endGridCell.getAttribute("aria-selected")).toBeNull();
expect( expect(
endGridCell.classList.contains( endGridCell.classList.contains(
"c__calendar__wrapper__grid__week-row__background--range--end" "c__calendar__wrapper__grid__week-row__background--range--end",
) ),
).toBe(false); ).toBe(false);
// Close the calendar. // Close the calendar.
@@ -741,7 +741,7 @@ describe("<DateRangePicker/>", () => {
// Make sure the empty date field is hidden when closing the calendar. // Make sure the empty date field is hidden when closing the calendar.
await expectDateFieldsToBeHidden(); await expectDateFieldsToBeHidden();
} },
); );
it.each([ it.each([
@@ -759,10 +759,10 @@ describe("<DateRangePicker/>", () => {
defaultValue={[start, end]} defaultValue={[start, end]}
minValue="2023-02-01" minValue="2023-02-01"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
await expectDateRangePickerStateToBe("invalid"); await expectDateRangePickerStateToBe("invalid");
} },
); );
it.each([ it.each([
@@ -780,10 +780,10 @@ describe("<DateRangePicker/>", () => {
defaultValue={[start, end]} defaultValue={[start, end]}
maxValue="2023-02-01" maxValue="2023-02-01"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
await expectDateRangePickerStateToBe("invalid"); await expectDateRangePickerStateToBe("invalid");
} },
); );
it("renders disabled", async () => { it("renders disabled", async () => {
@@ -796,7 +796,7 @@ describe("<DateRangePicker/>", () => {
defaultValue={["2023-01-01", "2023-01-01"]} defaultValue={["2023-01-01", "2023-01-01"]}
disabled={true} disabled={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
await expectDateRangePickerStateToBe("disabled"); await expectDateRangePickerStateToBe("disabled");
@@ -808,13 +808,13 @@ describe("<DateRangePicker/>", () => {
// Make sure the clear button is not visible and disabled. // Make sure the clear button is not visible and disabled.
expect( expect(
screen.queryByRole("button", { name: "Clear date", hidden: true }) screen.queryByRole("button", { name: "Clear date", hidden: true }),
).toBeDisabled(); ).toBeDisabled();
// Make sure each segment of the date field is disabled. // Make sure each segment of the date field is disabled.
const dateFieldInputs = await screen.queryAllByRole("spinbutton"); const dateFieldInputs = await screen.queryAllByRole("spinbutton");
dateFieldInputs.forEach((dateFieldInput) => dateFieldInputs.forEach((dateFieldInput) =>
expect(dateFieldInput).toHaveAttribute("aria-disabled") expect(dateFieldInput).toHaveAttribute("aria-disabled"),
); );
}); });
@@ -828,7 +828,7 @@ describe("<DateRangePicker/>", () => {
name="datepicker" name="datepicker"
defaultValue={["2023-01-01", "2023-01-01"]} defaultValue={["2023-01-01", "2023-01-01"]}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const toggleButton = (await screen.findAllByRole("button"))![1]; const toggleButton = (await screen.findAllByRole("button"))![1];
await user.click(toggleButton); await user.click(toggleButton);
@@ -846,7 +846,7 @@ describe("<DateRangePicker/>", () => {
name="datepicker" name="datepicker"
defaultValue={["2023-01-01", "2023-01-10"]} defaultValue={["2023-01-01", "2023-01-10"]}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
// Toggle button opens the calendar. // Toggle button opens the calendar.
const button = (await screen.findAllByRole("button"))![0]; const button = (await screen.findAllByRole("button"))![0];
@@ -860,7 +860,7 @@ describe("<DateRangePicker/>", () => {
selectedCells.forEach((selectedCell) => { selectedCells.forEach((selectedCell) => {
const cellButton = within(selectedCell).getByRole("button")!; const cellButton = within(selectedCell).getByRole("button")!;
expect(Array.from(cellButton!.classList)).contains( expect(Array.from(cellButton!.classList)).contains(
"c__calendar__wrapper__grid__week-row__button--selected" "c__calendar__wrapper__grid__week-row__button--selected",
); );
}); });
const commonClassName = const commonClassName =
@@ -868,14 +868,14 @@ describe("<DateRangePicker/>", () => {
// Make sure the start of selection has the start styling. // Make sure the start of selection has the start styling.
const startCellButton = within(selectedCells[0]).getByRole("button")!; const startCellButton = within(selectedCells[0]).getByRole("button")!;
expect(Array.from(startCellButton.parentElement!.classList)).contains( expect(Array.from(startCellButton.parentElement!.classList)).contains(
`${commonClassName}--start` `${commonClassName}--start`,
); );
// Make sure the end of selection has the end styling. // Make sure the end of selection has the end styling.
const endCellButton = within( const endCellButton = within(
selectedCells[selectedCells.length - 1] selectedCells[selectedCells.length - 1],
).getByRole("button")!; ).getByRole("button")!;
expect(Array.from(endCellButton.parentElement!.classList)).contains( expect(Array.from(endCellButton.parentElement!.classList)).contains(
`${commonClassName}--end` `${commonClassName}--end`,
); );
}); });
@@ -917,11 +917,11 @@ describe("<DateRangePicker/>", () => {
expectCalendarToBeOpen(); expectCalendarToBeOpen();
const startGridCell = within( const startGridCell = within(
await screen.getByRole("gridcell", { name: "12" }) await screen.getByRole("gridcell", { name: "12" }),
).getByRole("button")!; ).getByRole("button")!;
const endGridCell = within( const endGridCell = within(
await screen.getByRole("gridcell", { name: "14" }) await screen.getByRole("gridcell", { name: "14" }),
).getByRole("button")!; ).getByRole("button")!;
// Select a new value in the calendar grid. // Select a new value in the calendar grid.

View File

@@ -31,7 +31,7 @@ export const DateRangePicker = ({
}: DateRangePickerProps) => { }: DateRangePickerProps) => {
if (props.defaultValue && props.value) { if (props.defaultValue && props.value) {
throw new Error( throw new Error(
"You cannot use both defaultValue and value props on DateRangePicker component" "You cannot use both defaultValue and value props on DateRangePicker component",
); );
} }
const ref = useRef<HTMLDivElement>(null); const ref = useRef<HTMLDivElement>(null);
@@ -45,7 +45,7 @@ export const DateRangePicker = ({
props.onChange?.( props.onChange?.(
value?.start && value.end value?.start && value.end
? [value.start.toString(), value.end.toString()] ? [value.start.toString(), value.end.toString()]
: null : null,
); );
}, },
}; };
@@ -59,7 +59,7 @@ export const DateRangePicker = ({
!pickerState.isOpen && !pickerState.isOpen &&
!pickerState.value.start && !pickerState.value.start &&
!pickerState.value.end, !pickerState.value.end,
[pickerState.value, pickerState.isOpen, isFocused] [pickerState.value, pickerState.isOpen, isFocused],
); );
const calendar = <CalendarRange {...calendarProps} />; const calendar = <CalendarRange {...calendarProps} />;

View File

@@ -9,7 +9,7 @@ const expectDateToBeEqual = (
parsedDate: CalendarDate | DateValue | undefined, parsedDate: CalendarDate | DateValue | undefined,
expectedYear: number, expectedYear: number,
expectedMonth: number, expectedMonth: number,
expectedDay: number expectedDay: number,
) => { ) => {
expect(parsedDate).not.eq(undefined); expect(parsedDate).not.eq(undefined);
expect(parsedDate?.year === expectedYear); expect(parsedDate?.year === expectedYear);
@@ -40,7 +40,7 @@ describe("parseCalendarDate", () => {
const stringDate = `${year}-${month}-${day}`; const stringDate = `${year}-${month}-${day}`;
const parsedDate = parseCalendarDate(stringDate); const parsedDate = parseCalendarDate(stringDate);
expectDateToBeEqual(parsedDate, year, month, day); expectDateToBeEqual(parsedDate, year, month, day);
} },
); );
it.each([ it.each([
@@ -68,7 +68,7 @@ describe("parseCalendarDate", () => {
"2022-04-01 T00:00:00-00:00", "2022-04-01 T00:00:00-00:00",
])("parse a wrong date", (wrongFormattedDate) => { ])("parse a wrong date", (wrongFormattedDate) => {
expect(() => parseCalendarDate(wrongFormattedDate)).toThrow( expect(() => parseCalendarDate(wrongFormattedDate)).toThrow(
"Invalid date format when initializing props on DatePicker component" "Invalid date format when initializing props on DatePicker component",
); );
}); });
@@ -96,7 +96,7 @@ describe("parseCalendarDate", () => {
// Make sure the ISO string have been converted to the local timezone // Make sure the ISO string have been converted to the local timezone
const nextDay = parseDate(dateString).add({ days: 1 }); const nextDay = parseDate(dateString).add({ days: 1 });
expect(parsedDate?.compare(nextDay)).eq(0); expect(parsedDate?.compare(nextDay)).eq(0);
} },
); );
it.each([ it.each([
@@ -123,7 +123,7 @@ describe("parseCalendarDate", () => {
// Make sure the ISO string have been converted to the local timezone // Make sure the ISO string have been converted to the local timezone
expect(parsedDate?.compare(sameDay)).eq(0); expect(parsedDate?.compare(sameDay)).eq(0);
} },
); );
}); });
@@ -146,7 +146,7 @@ describe("parseRangeCalendarDate", () => {
"parse a partially null or empty date range", "parse a partially null or empty date range",
(start: StringOrDate, end: StringOrDate) => { (start: StringOrDate, end: StringOrDate) => {
expect(parseRangeCalendarDate([start, end])).eq(undefined); expect(parseRangeCalendarDate([start, end])).eq(undefined);
} },
); );
it("parse an undefined date range", () => { it("parse an undefined date range", () => {

View File

@@ -11,7 +11,7 @@ import {
import { DatePickerAuxSubProps } from ":/components/Forms/DatePicker/DatePickerAux"; import { DatePickerAuxSubProps } from ":/components/Forms/DatePicker/DatePickerAux";
export const parseCalendarDate = ( export const parseCalendarDate = (
rawDate: StringOrDate | undefined rawDate: StringOrDate | undefined,
): undefined | CalendarDate => { ): undefined | CalendarDate => {
if (!rawDate) { if (!rawDate) {
return undefined; return undefined;
@@ -21,13 +21,13 @@ export const parseCalendarDate = (
return toCalendarDate(parseAbsoluteToLocal(ISODateString)); return toCalendarDate(parseAbsoluteToLocal(ISODateString));
} catch (e) { } catch (e) {
throw new Error( throw new Error(
"Invalid date format when initializing props on DatePicker component" "Invalid date format when initializing props on DatePicker component",
); );
} }
}; };
export const parseRangeCalendarDate = ( export const parseRangeCalendarDate = (
rawRange: StringsOrDateRange | undefined rawRange: StringsOrDateRange | undefined,
): DateRange | undefined => { ): DateRange | undefined => {
if (!rawRange || !rawRange[0] || !rawRange[1]) { if (!rawRange || !rawRange[0] || !rawRange[1]) {
return undefined; return undefined;

View File

@@ -36,7 +36,7 @@ export const DropZone = forwardRef<FileUploaderRefType, DropZoneProps>(
children, children,
...props ...props
}: DropZoneProps, }: DropZoneProps,
ref ref,
) => { ) => {
const [dragActive, setDragActive] = useState(false); const [dragActive, setDragActive] = useState(false);
const container = useRef<HTMLLabelElement>(null); const container = useRef<HTMLLabelElement>(null);
@@ -98,7 +98,7 @@ export const DropZone = forwardRef<FileUploaderRefType, DropZoneProps>(
{ {
"c__file-uploader--active": dragActive, "c__file-uploader--active": dragActive,
"c__file-uploader--animate-icon": animateIcon, "c__file-uploader--animate-icon": animateIcon,
} },
)} )}
onDragEnter={() => { onDragEnter={() => {
setDragActive(true); setDragActive(true);
@@ -157,5 +157,5 @@ export const DropZone = forwardRef<FileUploaderRefType, DropZoneProps>(
</div> </div>
</label> </label>
); );
} },
); );

View File

@@ -15,7 +15,7 @@ export const FileUploaderMono = forwardRef<
const [file, setFile] = useState<File | undefined>( const [file, setFile] = useState<File | undefined>(
fakeDefaultFiles && fakeDefaultFiles.length > 0 fakeDefaultFiles && fakeDefaultFiles.length > 0
? fakeDefaultFiles[0] ? fakeDefaultFiles[0]
: undefined : undefined,
); );
// This is made to prevent useEffects inside DropZone that depends on `files` to trigger on each render, // This is made to prevent useEffects inside DropZone that depends on `files` to trigger on each render,
// doing this preserves the reference of the array. // doing this preserves the reference of the array.

View File

@@ -45,7 +45,7 @@ export const FileUploaderMulti = forwardRef<
"components.forms.file_uploader.delete_file_name", "components.forms.file_uploader.delete_file_name",
{ {
name: file.name, name: file.name,
} },
)} )}
onClick={() => { onClick={() => {
setFiles(files.filter((f) => f !== file)); setFiles(files.filter((f) => f !== file));

View File

@@ -26,7 +26,7 @@ describe("<FileUploader />", () => {
render( render(
<CunninghamProvider> <CunninghamProvider>
<FileUploader /> <FileUploader />
</CunninghamProvider> </CunninghamProvider>,
); );
const user = userEvent.setup(); const user = userEvent.setup();
const input: HTMLInputElement = const input: HTMLInputElement =
@@ -39,7 +39,7 @@ describe("<FileUploader />", () => {
await screen.findByText("hello.png"); await screen.findByText("hello.png");
expect( expect(
screen.queryByLabelText(/Drag and drop or /) screen.queryByLabelText(/Drag and drop or /),
).not.toBeInTheDocument(); ).not.toBeInTheDocument();
}); });
@@ -47,7 +47,7 @@ describe("<FileUploader />", () => {
render( render(
<CunninghamProvider> <CunninghamProvider>
<FileUploader /> <FileUploader />
</CunninghamProvider> </CunninghamProvider>,
); );
const user = userEvent.setup(); const user = userEvent.setup();
const input: HTMLInputElement = const input: HTMLInputElement =
@@ -60,7 +60,7 @@ describe("<FileUploader />", () => {
await screen.findByText("hello.png"); await screen.findByText("hello.png");
expect( expect(
screen.queryByLabelText(/Drag and drop or /) screen.queryByLabelText(/Drag and drop or /),
).not.toBeInTheDocument(); ).not.toBeInTheDocument();
const deleteButton = screen.getByRole("button", { const deleteButton = screen.getByRole("button", {
@@ -84,7 +84,7 @@ describe("<FileUploader />", () => {
render( render(
<CunninghamProvider> <CunninghamProvider>
<FileUploader name="file" /> <FileUploader name="file" />
</CunninghamProvider> </CunninghamProvider>,
); );
const user = userEvent.setup(); const user = userEvent.setup();
@@ -106,10 +106,10 @@ describe("<FileUploader />", () => {
render( render(
<CunninghamProvider> <CunninghamProvider>
<FileUploader state="uploading" /> <FileUploader state="uploading" />
</CunninghamProvider> </CunninghamProvider>,
); );
expect( expect(
document.querySelector(".c__file-uploader--uploading") document.querySelector(".c__file-uploader--uploading"),
).toBeInTheDocument(); ).toBeInTheDocument();
screen.getByText("Uploading..."); screen.getByText("Uploading...");
screen.getByRole("status", { name: "Uploading..." }); screen.getByRole("status", { name: "Uploading..." });
@@ -119,13 +119,13 @@ describe("<FileUploader />", () => {
render( render(
<CunninghamProvider> <CunninghamProvider>
<FileUploader state="success" /> <FileUploader state="success" />
</CunninghamProvider> </CunninghamProvider>,
); );
expect( expect(
document.querySelector(".c__file-uploader--success") document.querySelector(".c__file-uploader--success"),
).toBeInTheDocument(); ).toBeInTheDocument();
expect(document.querySelector(".material-icons")?.textContent).toContain( expect(document.querySelector(".material-icons")?.textContent).toContain(
"done" "done",
); );
}); });
@@ -133,19 +133,19 @@ describe("<FileUploader />", () => {
render( render(
<CunninghamProvider> <CunninghamProvider>
<FileUploader state="error" bigText="Error file is too big" /> <FileUploader state="error" bigText="Error file is too big" />
</CunninghamProvider> </CunninghamProvider>,
); );
// Big text is shown is file is not selected. // Big text is shown is file is not selected.
expect( expect(
document.querySelector(".c__file-uploader--error") document.querySelector(".c__file-uploader--error"),
).toBeInTheDocument(); ).toBeInTheDocument();
screen.getByText("Error file is too big"); screen.getByText("Error file is too big");
// Upload a file. // Upload a file.
const user = userEvent.setup(); const user = userEvent.setup();
const input: HTMLInputElement = screen.getByLabelText( const input: HTMLInputElement = screen.getByLabelText(
/Error file is too big/ /Error file is too big/,
); );
const file = new File(["hello"], "hello.png", { type: "image/png" }); const file = new File(["hello"], "hello.png", { type: "image/png" });
await act(async () => { await act(async () => {
@@ -154,7 +154,7 @@ describe("<FileUploader />", () => {
// The filename is shown in place of the big text. // The filename is shown in place of the big text.
expect( expect(
screen.queryByText("Error file is too big") screen.queryByText("Error file is too big"),
).not.toBeInTheDocument(); ).not.toBeInTheDocument();
await screen.findByText("hello.png"); await screen.findByText("hello.png");
}); });
@@ -163,7 +163,7 @@ describe("<FileUploader />", () => {
render( render(
<CunninghamProvider> <CunninghamProvider>
<FileUploader text="JPG, PNG or GIF - Max file size 2MB" /> <FileUploader text="JPG, PNG or GIF - Max file size 2MB" />
</CunninghamProvider> </CunninghamProvider>,
); );
screen.getByText("JPG, PNG or GIF - Max file size 2MB"); screen.getByText("JPG, PNG or GIF - Max file size 2MB");
}); });
@@ -176,11 +176,11 @@ describe("<FileUploader />", () => {
fileSelectedIcon={<span>file_selected_custom_icon</span>} fileSelectedIcon={<span>file_selected_custom_icon</span>}
deleteIcon={<span>delete_custom_icon</span>} deleteIcon={<span>delete_custom_icon</span>}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
screen.getByText("custom_icon"); screen.getByText("custom_icon");
expect( expect(
screen.queryByText("file_selected_custom_icon") screen.queryByText("file_selected_custom_icon"),
).not.toBeInTheDocument(); ).not.toBeInTheDocument();
expect(screen.queryByText("delete_custom_icon")).not.toBeInTheDocument(); expect(screen.queryByText("delete_custom_icon")).not.toBeInTheDocument();
@@ -200,12 +200,12 @@ describe("<FileUploader />", () => {
// Hover delete file to show the custom delete icon. // Hover delete file to show the custom delete icon.
const spanDelete = document.querySelector( const spanDelete = document.querySelector(
".c__file-uploader__inner__actions" ".c__file-uploader__inner__actions",
)!; )!;
await act(async () => user.hover(spanDelete)); await act(async () => user.hover(spanDelete));
expect(screen.queryByText("custom_icon")).not.toBeInTheDocument(); expect(screen.queryByText("custom_icon")).not.toBeInTheDocument();
expect( expect(
screen.queryByText("file_selected_custom_icon") screen.queryByText("file_selected_custom_icon"),
).not.toBeInTheDocument(); ).not.toBeInTheDocument();
screen.getByText("delete_custom_icon"); screen.getByText("delete_custom_icon");
}); });
@@ -217,7 +217,7 @@ describe("<FileUploader />", () => {
successIcon={<span>custom_success_icon</span>} successIcon={<span>custom_success_icon</span>}
state="success" state="success"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
screen.getByText("custom_success_icon"); screen.getByText("custom_success_icon");
}); });
@@ -229,7 +229,7 @@ describe("<FileUploader />", () => {
uploadingIcon={<span>custom_uploading_icon</span>} uploadingIcon={<span>custom_uploading_icon</span>}
state="uploading" state="uploading"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
screen.getByText("custom_uploading_icon"); screen.getByText("custom_uploading_icon");
}); });
@@ -277,7 +277,7 @@ describe("<FileUploader />", () => {
describe("Multi", () => { describe("Multi", () => {
const expectFiles = (expectedFiles: { name: string; specs: string }[]) => { const expectFiles = (expectedFiles: { name: string; specs: string }[]) => {
const actualElements = document.querySelectorAll( const actualElements = document.querySelectorAll(
".c__file-uploader__file" ".c__file-uploader__file",
); );
const actual = Array.from(actualElements).map((element) => { const actual = Array.from(actualElements).map((element) => {
return { return {
@@ -294,7 +294,7 @@ describe("<FileUploader />", () => {
render( render(
<CunninghamProvider> <CunninghamProvider>
<FileUploader multiple={true} /> <FileUploader multiple={true} />
</CunninghamProvider> </CunninghamProvider>,
); );
const user = userEvent.setup(); const user = userEvent.setup();
const input: HTMLInputElement = const input: HTMLInputElement =
@@ -318,7 +318,7 @@ describe("<FileUploader />", () => {
render( render(
<CunninghamProvider> <CunninghamProvider>
<FileUploader multiple={true} /> <FileUploader multiple={true} />
</CunninghamProvider> </CunninghamProvider>,
); );
const user = userEvent.setup(); const user = userEvent.setup();
const input: HTMLInputElement = const input: HTMLInputElement =
@@ -341,7 +341,7 @@ describe("<FileUploader />", () => {
await user.click( await user.click(
screen.getByRole("button", { screen.getByRole("button", {
name: "Delete file hello.png", name: "Delete file hello.png",
}) }),
); );
}); });
@@ -351,7 +351,7 @@ describe("<FileUploader />", () => {
await user.click( await user.click(
screen.getByRole("button", { screen.getByRole("button", {
name: "Delete file foo.png", name: "Delete file foo.png",
}) }),
); );
}); });
@@ -368,7 +368,7 @@ describe("<FileUploader />", () => {
render( render(
<CunninghamProvider> <CunninghamProvider>
<FileUploader name="files" multiple={true} /> <FileUploader name="files" multiple={true} />
</CunninghamProvider> </CunninghamProvider>,
); );
const user = userEvent.setup(); const user = userEvent.setup();
@@ -400,7 +400,7 @@ describe("<FileUploader />", () => {
render( render(
<CunninghamProvider> <CunninghamProvider>
<FileUploader name="files" multiple={true} /> <FileUploader name="files" multiple={true} />
</CunninghamProvider> </CunninghamProvider>,
); );
const user = userEvent.setup(); const user = userEvent.setup();
@@ -440,7 +440,7 @@ describe("<FileUploader />", () => {
render( render(
<CunninghamProvider> <CunninghamProvider>
<FileUploader state="uploading" multiple={true} /> <FileUploader state="uploading" multiple={true} />
</CunninghamProvider> </CunninghamProvider>,
); );
const user = userEvent.setup(); const user = userEvent.setup();
@@ -460,7 +460,7 @@ describe("<FileUploader />", () => {
]); ]);
expect( expect(
document.querySelector(".c__file-uploader--uploading") document.querySelector(".c__file-uploader--uploading"),
).toBeInTheDocument(); ).toBeInTheDocument();
screen.getByText("Uploading..."); screen.getByText("Uploading...");
screen.getByRole("status", { name: "Uploading..." }); screen.getByRole("status", { name: "Uploading..." });
@@ -470,13 +470,13 @@ describe("<FileUploader />", () => {
render( render(
<CunninghamProvider> <CunninghamProvider>
<FileUploader state="success" multiple={true} /> <FileUploader state="success" multiple={true} />
</CunninghamProvider> </CunninghamProvider>,
); );
expect( expect(
document.querySelector(".c__file-uploader--success") document.querySelector(".c__file-uploader--success"),
).toBeInTheDocument(); ).toBeInTheDocument();
expect(document.querySelector(".material-icons")?.textContent).toContain( expect(document.querySelector(".material-icons")?.textContent).toContain(
"done" "done",
); );
}); });
@@ -488,12 +488,12 @@ describe("<FileUploader />", () => {
bigText="Error file is too big" bigText="Error file is too big"
multiple={true} multiple={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
// Big text is shown is file is not selected. // Big text is shown is file is not selected.
expect( expect(
document.querySelector(".c__file-uploader--error") document.querySelector(".c__file-uploader--error"),
).toBeInTheDocument(); ).toBeInTheDocument();
screen.getByText("Error file is too big"); screen.getByText("Error file is too big");
@@ -515,7 +515,7 @@ describe("<FileUploader />", () => {
// The error is still displayed if files are selected. // The error is still displayed if files are selected.
expect( expect(
document.querySelector(".c__file-uploader--error") document.querySelector(".c__file-uploader--error"),
).toBeInTheDocument(); ).toBeInTheDocument();
screen.getByText("Error file is too big"); screen.getByText("Error file is too big");
}); });
@@ -527,7 +527,7 @@ describe("<FileUploader />", () => {
text="JPG, PNG or GIF - Max file size 2MB" text="JPG, PNG or GIF - Max file size 2MB"
multiple={true} multiple={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
screen.getByText("JPG, PNG or GIF - Max file size 2MB"); screen.getByText("JPG, PNG or GIF - Max file size 2MB");
}); });

View File

@@ -37,5 +37,5 @@ export const FileUploader = forwardRef<FileUploaderRefType, FileUploaderProps>(
)} )}
</Field> </Field>
); );
} },
); );

View File

@@ -35,7 +35,7 @@ describe("<Input/>", () => {
<div> <div>
<Input label="First name" /> <Input label="First name" />
<Input label="Second name" /> <Input label="Second name" />
</div> </div>,
); );
const input: HTMLInputElement = screen.getByRole("textbox", { const input: HTMLInputElement = screen.getByRole("textbox", {
@@ -67,14 +67,14 @@ describe("<Input/>", () => {
render(<Input label="First name" state="success" />); render(<Input label="First name" state="success" />);
expect(document.querySelector(".c__field--success")).toBeInTheDocument(); expect(document.querySelector(".c__field--success")).toBeInTheDocument();
expect( expect(
document.querySelector(".c__input__wrapper--success") document.querySelector(".c__input__wrapper--success"),
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
it("renders with state=error", async () => { it("renders with state=error", async () => {
render(<Input label="First name" state="error" />); render(<Input label="First name" state="error" />);
expect(document.querySelector(".c__field--error")).toBeInTheDocument(); expect(document.querySelector(".c__field--error")).toBeInTheDocument();
expect( expect(
document.querySelector(".c__input__wrapper--error") document.querySelector(".c__input__wrapper--error"),
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
it("renders disabled", async () => { it("renders disabled", async () => {
@@ -84,7 +84,7 @@ describe("<Input/>", () => {
name: "First name", name: "First name",
}); });
expect( expect(
document.querySelector(".c__input__wrapper--disabled") document.querySelector(".c__input__wrapper--disabled"),
).toBeInTheDocument(); ).toBeInTheDocument();
expect(input.value).toEqual(""); expect(input.value).toEqual("");
// Disabled inputs should not be able to type. // Disabled inputs should not be able to type.
@@ -96,7 +96,7 @@ describe("<Input/>", () => {
<Input <Input
label="First name" label="First name"
icon={<span className="material-icons">apartment</span>} icon={<span className="material-icons">apartment</span>}
/> />,
); );
expect(document.querySelector(".material-icons")).toBeInTheDocument(); expect(document.querySelector(".material-icons")).toBeInTheDocument();
}); });
@@ -105,7 +105,7 @@ describe("<Input/>", () => {
<Input <Input
label="First name" label="First name"
rightIcon={<span className="material-icons">apartment</span>} rightIcon={<span className="material-icons">apartment</span>}
/> />,
); );
expect(document.querySelector(".material-icons")).toBeInTheDocument(); expect(document.querySelector(".material-icons")).toBeInTheDocument();
}); });
@@ -115,7 +115,7 @@ describe("<Input/>", () => {
label="First name" label="First name"
rightIcon={<span className="material-icons">apartment</span>} rightIcon={<span className="material-icons">apartment</span>}
text="Some text" text="Some text"
/> />,
); );
screen.getByText("Some text"); screen.getByText("Some text");
}); });
@@ -125,7 +125,7 @@ describe("<Input/>", () => {
label="First name" label="First name"
rightIcon={<span className="material-icons">apartment</span>} rightIcon={<span className="material-icons">apartment</span>}
rightText="Some text right" rightText="Some text right"
/> />,
); );
screen.getByText("Some text right"); screen.getByText("Some text right");
}); });

View File

@@ -42,7 +42,7 @@ export const Input = forwardRef<InputRefType, Props>(
charCounterMax, charCounterMax,
...props ...props
}: Props, }: Props,
ref ref,
) => { ) => {
const classes = ["c__input"]; const classes = ["c__input"];
if (className) { if (className) {
@@ -100,7 +100,7 @@ export const Input = forwardRef<InputRefType, Props>(
"c__input__wrapper--" + state, "c__input__wrapper--" + state,
{ {
"c__input__wrapper--disabled": props.disabled, "c__input__wrapper--disabled": props.disabled,
} },
)} )}
onClick={() => { onClick={() => {
inputRef.current?.focus(); inputRef.current?.focus();
@@ -139,5 +139,5 @@ export const Input = forwardRef<InputRefType, Props>(
</div> </div>
</Field> </Field>
); );
} },
); );

View File

@@ -35,14 +35,14 @@ describe("<Radio/>", () => {
render(<Radio label="Yes" state="success" text="Success text" />); render(<Radio label="Yes" state="success" text="Success text" />);
expect(screen.getByText("Success text")).toBeInTheDocument(); expect(screen.getByText("Success text")).toBeInTheDocument();
expect( expect(
document.querySelector(".c__field.c__field--success") document.querySelector(".c__field.c__field--success"),
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
it("should render with state=error", async () => { it("should render with state=error", async () => {
render(<Radio label="Yes" state="error" text="Error text" />); render(<Radio label="Yes" state="error" text="Error text" />);
expect(screen.getByText("Error text")).toBeInTheDocument(); expect(screen.getByText("Error text")).toBeInTheDocument();
expect( expect(
document.querySelector(".c__field.c__field--error") document.querySelector(".c__field.c__field--error"),
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
it("should render with group", async () => { it("should render with group", async () => {
@@ -50,7 +50,7 @@ describe("<Radio/>", () => {
<RadioGroup> <RadioGroup>
<Radio label="Yes" /> <Radio label="Yes" />
<Radio label="No" /> <Radio label="No" />
</RadioGroup> </RadioGroup>,
); );
screen.getByRole("radio", { screen.getByRole("radio", {
name: "Yes", name: "Yes",
@@ -64,7 +64,7 @@ describe("<Radio/>", () => {
<RadioGroup> <RadioGroup>
<Radio name="agree" label="Yes" /> <Radio name="agree" label="Yes" />
<Radio name="agree" label="No" /> <Radio name="agree" label="No" />
</RadioGroup> </RadioGroup>,
); );
const user = userEvent.setup(); const user = userEvent.setup();
const yesInput: HTMLInputElement = screen.getByLabelText("Yes"); const yesInput: HTMLInputElement = screen.getByLabelText("Yes");
@@ -83,7 +83,7 @@ describe("<Radio/>", () => {
<RadioGroup text="Text"> <RadioGroup text="Text">
<Radio label="Yes" /> <Radio label="Yes" />
<Radio label="No" /> <Radio label="No" />
</RadioGroup> </RadioGroup>,
); );
expect(screen.getByText("Text")).toBeInTheDocument(); expect(screen.getByText("Text")).toBeInTheDocument();
}); });
@@ -92,11 +92,11 @@ describe("<Radio/>", () => {
<RadioGroup state="success" text="Success text"> <RadioGroup state="success" text="Success text">
<Radio label="Yes" /> <Radio label="Yes" />
<Radio label="No" /> <Radio label="No" />
</RadioGroup> </RadioGroup>,
); );
expect(screen.getByText("Success text")).toBeInTheDocument(); expect(screen.getByText("Success text")).toBeInTheDocument();
expect( expect(
document.querySelector(".c__radio__group.c__field.c__field--success") document.querySelector(".c__radio__group.c__field.c__field--success"),
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
it("should render with group state=error", async () => { it("should render with group state=error", async () => {
@@ -104,11 +104,11 @@ describe("<Radio/>", () => {
<RadioGroup state="error" text="Error text"> <RadioGroup state="error" text="Error text">
<Radio label="Yes" /> <Radio label="Yes" />
<Radio label="No" /> <Radio label="No" />
</RadioGroup> </RadioGroup>,
); );
expect(screen.getByText("Error text")).toBeInTheDocument(); expect(screen.getByText("Error text")).toBeInTheDocument();
expect( expect(
document.querySelector(".c__radio__group.c__field.c__field--error") document.querySelector(".c__radio__group.c__field.c__field--error"),
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
}); });

View File

@@ -5,7 +5,7 @@ import { SelectMono, SelectProps } from ":/components/Forms/Select/mono";
export const Select = (props: SelectProps) => { export const Select = (props: SelectProps) => {
if (props.defaultValue && props.value) { if (props.defaultValue && props.value) {
throw new Error( throw new Error(
"You cannot use both defaultValue and value props on Select component" "You cannot use both defaultValue and value props on Select component",
); );
} }

View File

@@ -79,7 +79,7 @@ export const SelectMonoAux = ({
return; return;
} }
const optionToSelect = options.find( const optionToSelect = options.find(
(option) => optionToValue(option) === value (option) => optionToValue(option) === value,
); );
downshiftReturn.selectItem(optionToSelect ?? null); downshiftReturn.selectItem(optionToSelect ?? null);
}, [value]); }, [value]);
@@ -98,7 +98,7 @@ export const SelectMonoAux = ({
"c__select--" + state, "c__select--" + state,
{ {
"c__select--disabled": disabled, "c__select--disabled": disabled,
} },
)} )}
> >
{/* We disabled linting for this specific line because we consider that the onClick props is only used for */} {/* We disabled linting for this specific line because we consider that the onClick props is only used for */}
@@ -134,7 +134,7 @@ export const SelectMonoAux = ({
color="tertiary" color="tertiary"
size="small" size="small"
aria-label={t( aria-label={t(
"components.forms.select.clear_button_aria_label" "components.forms.select.clear_button_aria_label",
)} )}
className="c__select__inner__actions__clear" className="c__select__inner__actions__clear"
onClick={(e) => { onClick={(e) => {

View File

@@ -26,7 +26,7 @@ export const SelectMonoSearchable = (props: SubProps) => {
}); });
const [labelAsPlaceholder, setLabelAsPlaceholder] = useState( const [labelAsPlaceholder, setLabelAsPlaceholder] = useState(
!downshiftReturn.selectedItem !downshiftReturn.selectedItem,
); );
useEffect(() => { useEffect(() => {
if (hasInputFocused || downshiftReturn.inputValue) { if (hasInputFocused || downshiftReturn.inputValue) {

View File

@@ -41,7 +41,7 @@ describe("<Select/>", () => {
]} ]}
searchable={true} searchable={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = screen.getByRole("combobox", { const input = screen.getByRole("combobox", {
@@ -103,7 +103,7 @@ describe("<Select/>", () => {
]} ]}
searchable={true} searchable={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = screen.getByRole("combobox", { const input = screen.getByRole("combobox", {
@@ -166,7 +166,7 @@ describe("<Select/>", () => {
searchable={true} searchable={true}
defaultValue="new_york" defaultValue="new_york"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const user = userEvent.setup(); const user = userEvent.setup();
@@ -207,7 +207,7 @@ describe("<Select/>", () => {
searchable={true} searchable={true}
defaultValue="New York" defaultValue="New York"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = screen.getByRole("combobox", { const input = screen.getByRole("combobox", {
@@ -242,7 +242,7 @@ describe("<Select/>", () => {
searchable={true} searchable={true}
defaultValue="new_york" defaultValue="new_york"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = screen.getByRole("combobox", { const input = screen.getByRole("combobox", {
@@ -277,7 +277,7 @@ describe("<Select/>", () => {
searchable={true} searchable={true}
defaultValue="not_found" defaultValue="not_found"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = screen.getByRole("combobox", { const input = screen.getByRole("combobox", {
@@ -288,7 +288,7 @@ describe("<Select/>", () => {
it("works controlled", async () => { it("works controlled", async () => {
const Wrapper = () => { const Wrapper = () => {
const [value, setValue] = useState<string | number | undefined>( const [value, setValue] = useState<string | number | undefined>(
"london" "london",
); );
return ( return (
<CunninghamProvider> <CunninghamProvider>
@@ -356,7 +356,7 @@ describe("<Select/>", () => {
await user.click( await user.click(
screen.getByRole("option", { screen.getByRole("option", {
name: "New York", name: "New York",
}) }),
); );
// Make sure value is selected. // Make sure value is selected.
@@ -394,7 +394,7 @@ describe("<Select/>", () => {
disabled={true} disabled={true}
searchable={true} searchable={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = screen.getByRole("combobox", { const input = screen.getByRole("combobox", {
name: "City", name: "City",
@@ -402,7 +402,7 @@ describe("<Select/>", () => {
expect(input).toHaveAttribute("disabled"); expect(input).toHaveAttribute("disabled");
const button: HTMLButtonElement = document.querySelector( const button: HTMLButtonElement = document.querySelector(
".c__select__inner__actions__open" ".c__select__inner__actions__open",
)!; )!;
expect(button).toBeDisabled(); expect(button).toBeDisabled();
@@ -505,7 +505,7 @@ describe("<Select/>", () => {
await user.click( await user.click(
screen.getByRole("option", { screen.getByRole("option", {
name: "New York", name: "New York",
}) }),
); );
// Submit the form being fulfilled. // Submit the form being fulfilled.
@@ -550,7 +550,7 @@ describe("<Select/>", () => {
}, },
]} ]}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = screen.getByRole("combobox", { const input = screen.getByRole("combobox", {
name: "City", name: "City",
@@ -565,7 +565,7 @@ describe("<Select/>", () => {
expect(valueRendered).toHaveTextContent(""); expect(valueRendered).toHaveTextContent("");
expectMenuToBeClosed(menu); expectMenuToBeClosed(menu);
expect( expect(
screen.queryByRole("option", { name: "Paris" }) screen.queryByRole("option", { name: "Paris" }),
).not.toBeInTheDocument(); ).not.toBeInTheDocument();
// Make sure the label is set as placeholder. // Make sure the label is set as placeholder.
@@ -576,7 +576,7 @@ describe("<Select/>", () => {
// Make sure the menu is opened and options are rendered. // Make sure the menu is opened and options are rendered.
expectMenuToBeOpen(menu); expectMenuToBeOpen(menu);
expect( expect(
screen.queryByRole("option", { name: "Paris" }) screen.queryByRole("option", { name: "Paris" }),
).toBeInTheDocument(); ).toBeInTheDocument();
// Make sure the option is not selected. // Make sure the option is not selected.
@@ -639,7 +639,7 @@ describe("<Select/>", () => {
]} ]}
defaultValue="Tokyo" defaultValue="Tokyo"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const menu: HTMLDivElement = screen.getByRole("listbox", { const menu: HTMLDivElement = screen.getByRole("listbox", {
name: "City", name: "City",
@@ -679,7 +679,7 @@ describe("<Select/>", () => {
]} ]}
defaultValue="new_york" defaultValue="new_york"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const menu: HTMLDivElement = screen.getByRole("listbox", { const menu: HTMLDivElement = screen.getByRole("listbox", {
name: "City", name: "City",
@@ -697,7 +697,7 @@ describe("<Select/>", () => {
it("works controlled", async () => { it("works controlled", async () => {
const Wrapper = () => { const Wrapper = () => {
const [value, setValue] = useState<string | number | undefined>( const [value, setValue] = useState<string | number | undefined>(
"london" "london",
); );
return ( return (
<CunninghamProvider> <CunninghamProvider>
@@ -754,7 +754,7 @@ describe("<Select/>", () => {
await user.click( await user.click(
screen.getByRole("option", { screen.getByRole("option", {
name: "New York", name: "New York",
}) }),
); );
// Make sure value is selected. // Make sure value is selected.
@@ -795,7 +795,7 @@ describe("<Select/>", () => {
]} ]}
disabled={true} disabled={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = screen.getByRole("combobox", { const input = screen.getByRole("combobox", {
name: "City", name: "City",
@@ -803,7 +803,7 @@ describe("<Select/>", () => {
expect(input).toHaveAttribute("disabled"); expect(input).toHaveAttribute("disabled");
const button: HTMLButtonElement = document.querySelector( const button: HTMLButtonElement = document.querySelector(
".c__select__inner__actions__open" ".c__select__inner__actions__open",
)!; )!;
expect(button).toBeDisabled(); expect(button).toBeDisabled();
@@ -849,7 +849,7 @@ describe("<Select/>", () => {
]} ]}
text="This is a text" text="This is a text"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
screen.getByText("This is a text"); screen.getByText("This is a text");
}); });
@@ -879,10 +879,10 @@ describe("<Select/>", () => {
text="This is a text" text="This is a text"
state="error" state="error"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
expect( expect(
document.querySelector(".c__select.c__select--error") document.querySelector(".c__select.c__select--error"),
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
it("renders with state=success", async () => { it("renders with state=success", async () => {
@@ -911,10 +911,10 @@ describe("<Select/>", () => {
text="This is a text" text="This is a text"
state="success" state="success"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
expect( expect(
document.querySelector(".c__select.c__select--success") document.querySelector(".c__select.c__select--success"),
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
it("submits form data", async () => { it("submits form data", async () => {
@@ -986,7 +986,7 @@ describe("<Select/>", () => {
await user.click( await user.click(
screen.getByRole("option", { screen.getByRole("option", {
name: "New York", name: "New York",
}) }),
); );
// Submit the form being fulfilled. // Submit the form being fulfilled.
@@ -1030,7 +1030,7 @@ describe("<Select/>", () => {
clearable={false} clearable={false}
defaultValue="Paris" defaultValue="Paris"
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
screen.getByRole("combobox", { screen.getByRole("combobox", {
name: "City", name: "City",
@@ -1043,7 +1043,7 @@ describe("<Select/>", () => {
expect( expect(
screen.queryByRole("button", { screen.queryByRole("button", {
name: "Clear selection", name: "Clear selection",
}) }),
).not.toBeInTheDocument(); ).not.toBeInTheDocument();
}); });
it("is not possible to select disabled options", async () => { it("is not possible to select disabled options", async () => {
@@ -1067,7 +1067,7 @@ describe("<Select/>", () => {
}, },
]} ]}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = screen.getByRole("combobox", { const input = screen.getByRole("combobox", {
name: "City", name: "City",
@@ -1129,7 +1129,7 @@ describe("<Select/>", () => {
]} ]}
hideLabel={true} hideLabel={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
// Make sure the input is accessible. // Make sure the input is accessible.
screen.getByRole("combobox", { screen.getByRole("combobox", {

View File

@@ -31,7 +31,7 @@ export type SelectProps = PropsWithChildren &
export const SelectMono = (props: SelectProps) => { export const SelectMono = (props: SelectProps) => {
const defaultSelectedItem = props.defaultValue const defaultSelectedItem = props.defaultValue
? props.options.find( ? props.options.find(
(option) => optionToValue(option) === props.defaultValue (option) => optionToValue(option) === props.defaultValue,
) )
: undefined; : undefined;

View File

@@ -23,14 +23,14 @@ import {
*/ */
export function getMultiOptionsFilter( export function getMultiOptionsFilter(
selectedOptions: Option[], selectedOptions: Option[],
inputValue?: string inputValue?: string,
) { ) {
const optionsFilter = getOptionsFilter(inputValue); const optionsFilter = getOptionsFilter(inputValue);
return (option: Option) => { return (option: Option) => {
return ( return (
!selectedOptions.find( !selectedOptions.find(
(selectedOption) => (selectedOption) =>
optionToValue(selectedOption) === optionToValue(option) optionToValue(selectedOption) === optionToValue(option),
) && optionsFilter(option) ) && optionsFilter(option)
); );
}; };
@@ -85,7 +85,7 @@ export const SelectMultiAux = ({
{ {
"c__select--disabled": disabled, "c__select--disabled": disabled,
"c__select--populated": selectedItems.length > 0, "c__select--populated": selectedItems.length > 0,
} },
)} )}
> >
<div <div
@@ -117,7 +117,7 @@ export const SelectMultiAux = ({
color="tertiary" color="tertiary"
size="small" size="small"
aria-label={t( aria-label={t(
"components.forms.select.clear_all_button_aria_label" "components.forms.select.clear_all_button_aria_label",
)} )}
className="c__select__inner__actions__clear" className="c__select__inner__actions__clear"
onClick={(e) => { onClick={(e) => {
@@ -164,13 +164,13 @@ export const SelectMultiAux = ({
disabled={disabled} disabled={disabled}
size="small" size="small"
aria-label={t( aria-label={t(
"components.forms.select.clear_button_aria_label" "components.forms.select.clear_button_aria_label",
)} )}
className="c__select__inner__value__pill__clear" className="c__select__inner__value__pill__clear"
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
useMultipleSelectionReturn.removeSelectedItem( useMultipleSelectionReturn.removeSelectedItem(
selectedItemForRender selectedItemForRender,
); );
}} }}
icon={<span className="material-icons">close</span>} icon={<span className="material-icons">close</span>}

View File

@@ -13,9 +13,9 @@ export const SelectMultiSearchable = (props: SubProps) => {
const options = React.useMemo( const options = React.useMemo(
() => () =>
props.options.filter( props.options.filter(
getMultiOptionsFilter(props.selectedItems, inputValue) getMultiOptionsFilter(props.selectedItems, inputValue),
), ),
[props.selectedItems, inputValue] [props.selectedItems, inputValue],
); );
const [hasInputFocused, setHasInputFocused] = useState(false); const [hasInputFocused, setHasInputFocused] = useState(false);
const useMultipleSelectionReturn = useMultipleSelection({ const useMultipleSelectionReturn = useMultipleSelection({

View File

@@ -10,7 +10,7 @@ import { optionToString } from ":/components/Forms/Select/mono-common";
export const SelectMultiSimple = (props: SubProps) => { export const SelectMultiSimple = (props: SubProps) => {
const options = React.useMemo( const options = React.useMemo(
() => props.options.filter(getMultiOptionsFilter(props.selectedItems, "")), () => props.options.filter(getMultiOptionsFilter(props.selectedItems, "")),
[props.selectedItems] [props.selectedItems],
); );
const useMultipleSelectionReturn = useMultipleSelection({ const useMultipleSelectionReturn = useMultipleSelection({

View File

@@ -42,7 +42,7 @@ describe("<Select multi={true} />", () => {
]} ]}
multi={true} multi={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = screen.getByRole("combobox", { const input = screen.getByRole("combobox", {
name: "Cities", name: "Cities",
@@ -63,7 +63,7 @@ describe("<Select multi={true} />", () => {
// Make sure the menu is opened and options are rendered. // Make sure the menu is opened and options are rendered.
expectMenuToBeOpen(menu); expectMenuToBeOpen(menu);
expect( expect(
screen.queryByRole("option", { name: "Paris" }) screen.queryByRole("option", { name: "Paris" }),
).toBeInTheDocument(); ).toBeInTheDocument();
// Make sure the option is not selected. // Make sure the option is not selected.
@@ -83,19 +83,19 @@ describe("<Select multi={true} />", () => {
// Make sure the option is removed from the menu. // Make sure the option is removed from the menu.
expect( expect(
screen.queryByRole("option", { name: "London" }) screen.queryByRole("option", { name: "London" }),
).not.toBeInTheDocument(); ).not.toBeInTheDocument();
// Select other options. // Select other options.
await user.click( await user.click(
screen.getByRole("option", { screen.getByRole("option", {
name: "Tokyo", name: "Tokyo",
}) }),
); );
await user.click( await user.click(
screen.getByRole("option", { screen.getByRole("option", {
name: "Panama", name: "Panama",
}) }),
); );
await waitFor(() => expectSelectedOptions(["London", "Tokyo", "Panama"])); await waitFor(() => expectSelectedOptions(["London", "Tokyo", "Panama"]));
@@ -103,30 +103,30 @@ describe("<Select multi={true} />", () => {
// Clear one option. // Clear one option.
await user.click( await user.click(
within( within(
screen.getByText("Panama").parentNode as HTMLDivElement screen.getByText("Panama").parentNode as HTMLDivElement,
).getByRole("button", { ).getByRole("button", {
name: "Clear selection", name: "Clear selection",
}) }),
); );
await waitFor(() => expectSelectedOptions(["London", "Tokyo"])); await waitFor(() => expectSelectedOptions(["London", "Tokyo"]));
// Clear one option. // Clear one option.
await user.click( await user.click(
within( within(
screen.getByText("London").parentNode as HTMLDivElement screen.getByText("London").parentNode as HTMLDivElement,
).getByRole("button", { ).getByRole("button", {
name: "Clear selection", name: "Clear selection",
}) }),
); );
await waitFor(() => expectSelectedOptions(["Tokyo"])); await waitFor(() => expectSelectedOptions(["Tokyo"]));
// Clear one option. // Clear one option.
await user.click( await user.click(
within( within(
screen.getByText("Tokyo").parentNode as HTMLDivElement screen.getByText("Tokyo").parentNode as HTMLDivElement,
).getByRole("button", { ).getByRole("button", {
name: "Clear selection", name: "Clear selection",
}) }),
); );
expectSelectedOptions([]); expectSelectedOptions([]);
}); });
@@ -156,7 +156,7 @@ describe("<Select multi={true} />", () => {
]} ]}
multi={true} multi={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = screen.getByRole("combobox", { const input = screen.getByRole("combobox", {
name: "Cities", name: "Cities",
@@ -167,17 +167,17 @@ describe("<Select multi={true} />", () => {
await user.click( await user.click(
screen.getByRole("option", { screen.getByRole("option", {
name: "London", name: "London",
}) }),
); );
await user.click( await user.click(
screen.getByRole("option", { screen.getByRole("option", {
name: "Tokyo", name: "Tokyo",
}) }),
); );
await user.click( await user.click(
screen.getByRole("option", { screen.getByRole("option", {
name: "Panama", name: "Panama",
}) }),
); );
expectSelectedOptions(["London", "Tokyo", "Panama"]); expectSelectedOptions(["London", "Tokyo", "Panama"]);
@@ -211,7 +211,7 @@ describe("<Select multi={true} />", () => {
defaultValue={["Tokyo", "New York"]} defaultValue={["Tokyo", "New York"]}
multi={true} multi={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
expectSelectedOptions(["New York", "Tokyo"]); expectSelectedOptions(["New York", "Tokyo"]);
}); });
@@ -242,7 +242,7 @@ describe("<Select multi={true} />", () => {
defaultValue={["tokyo", "new_york"]} defaultValue={["tokyo", "new_york"]}
multi={true} multi={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
expectSelectedOptions(["New York", "Tokyo"]); expectSelectedOptions(["New York", "Tokyo"]);
}); });
@@ -298,14 +298,14 @@ describe("<Select multi={true} />", () => {
// Make sure the option is removed from the menu. // Make sure the option is removed from the menu.
expect( expect(
screen.queryByRole("option", { name: "London" }) screen.queryByRole("option", { name: "London" }),
).not.toBeInTheDocument(); ).not.toBeInTheDocument();
// Select an option. // Select an option.
await user.click( await user.click(
screen.getByRole("option", { screen.getByRole("option", {
name: "New York", name: "New York",
}) }),
); );
// Make sure value is selected. // Make sure value is selected.
@@ -347,7 +347,7 @@ describe("<Select multi={true} />", () => {
disabled={true} disabled={true}
multi={true} multi={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = screen.getByRole("combobox", { const input = screen.getByRole("combobox", {
name: "Cities", name: "Cities",
@@ -355,7 +355,7 @@ describe("<Select multi={true} />", () => {
expect(input).toHaveAttribute("disabled"); expect(input).toHaveAttribute("disabled");
const button: HTMLButtonElement = document.querySelector( const button: HTMLButtonElement = document.querySelector(
".c__select__inner__actions__open" ".c__select__inner__actions__open",
)!; )!;
expect(button).toBeDisabled(); expect(button).toBeDisabled();
@@ -402,7 +402,7 @@ describe("<Select multi={true} />", () => {
text="This is a text" text="This is a text"
multi={true} multi={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
screen.getByText("This is a text"); screen.getByText("This is a text");
}); });
@@ -434,10 +434,10 @@ describe("<Select multi={true} />", () => {
state="error" state="error"
multi={true} multi={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
expect( expect(
document.querySelector(".c__select.c__select--error") document.querySelector(".c__select.c__select--error"),
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
@@ -468,10 +468,10 @@ describe("<Select multi={true} />", () => {
state="success" state="success"
multi={true} multi={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
expect( expect(
document.querySelector(".c__select.c__select--success") document.querySelector(".c__select.c__select--success"),
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
@@ -546,7 +546,7 @@ describe("<Select multi={true} />", () => {
await user.click( await user.click(
screen.getByRole("option", { screen.getByRole("option", {
name: "New York", name: "New York",
}) }),
); );
expectSelectedOptions(["New York"]); expectSelectedOptions(["New York"]);
@@ -566,7 +566,7 @@ describe("<Select multi={true} />", () => {
await user.click( await user.click(
await screen.findByRole("option", { await screen.findByRole("option", {
name: "Paris", name: "Paris",
}) }),
); );
expectSelectedOptions(["New York", "Paris"]); expectSelectedOptions(["New York", "Paris"]);
@@ -616,7 +616,7 @@ describe("<Select multi={true} />", () => {
defaultValue={["Paris"]} defaultValue={["Paris"]}
multi={true} multi={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
screen.getByRole("combobox", { screen.getByRole("combobox", {
name: "Cities", name: "Cities",
@@ -628,7 +628,7 @@ describe("<Select multi={true} />", () => {
expect( expect(
screen.queryByRole("button", { screen.queryByRole("button", {
name: "Clear all selections", name: "Clear all selections",
}) }),
).not.toBeInTheDocument(); ).not.toBeInTheDocument();
}); });
@@ -654,7 +654,7 @@ describe("<Select multi={true} />", () => {
}, },
]} ]}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = screen.getByRole("combobox", { const input = screen.getByRole("combobox", {
name: "Cities", name: "Cities",
@@ -715,7 +715,7 @@ describe("<Select multi={true} />", () => {
hideLabel={true} hideLabel={true}
multi={true} multi={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
// Make sure the input is accessible. // Make sure the input is accessible.
screen.getByRole("combobox", { screen.getByRole("combobox", {
@@ -753,7 +753,7 @@ describe("<Select multi={true} />", () => {
searchable={true} searchable={true}
multi={true} multi={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = screen.getByRole("combobox", { const input = screen.getByRole("combobox", {
@@ -815,7 +815,7 @@ describe("<Select multi={true} />", () => {
searchable={true} searchable={true}
multi={true} multi={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = screen.getByRole("combobox", { const input = screen.getByRole("combobox", {
@@ -875,7 +875,7 @@ describe("<Select multi={true} />", () => {
searchable={true} searchable={true}
multi={true} multi={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = screen.getByRole("combobox", { const input = screen.getByRole("combobox", {
@@ -936,7 +936,7 @@ describe("<Select multi={true} />", () => {
multi={true} multi={true}
defaultValue={["panama", "tokyo", "new_york"]} defaultValue={["panama", "tokyo", "new_york"]}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
expectSelectedOptions(["Panama", "New York", "Tokyo"]); expectSelectedOptions(["Panama", "New York", "Tokyo"]);
@@ -996,7 +996,7 @@ describe("<Select multi={true} />", () => {
searchable={true} searchable={true}
defaultValue={["London", "Tokyo", "Panama"]} defaultValue={["London", "Tokyo", "Panama"]}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
expectSelectedOptions(["Panama", "London", "Tokyo"]); expectSelectedOptions(["Panama", "London", "Tokyo"]);
@@ -1035,7 +1035,7 @@ describe("<Select multi={true} />", () => {
searchable={true} searchable={true}
defaultValue={["London", "Tokyo", "Panama"]} defaultValue={["London", "Tokyo", "Panama"]}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
expectSelectedOptions(["Panama", "London", "Tokyo"]); expectSelectedOptions(["Panama", "London", "Tokyo"]);
@@ -1068,7 +1068,7 @@ describe("<Select multi={true} />", () => {
searchable={true} searchable={true}
multi={true} multi={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
expectSelectedOptions(["New York", "Tokyo"]); expectSelectedOptions(["New York", "Tokyo"]);
}); });
@@ -1100,7 +1100,7 @@ describe("<Select multi={true} />", () => {
searchable={true} searchable={true}
multi={true} multi={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
expectSelectedOptions(["New York"]); expectSelectedOptions(["New York"]);
}); });
@@ -1199,7 +1199,7 @@ describe("<Select multi={true} />", () => {
searchable={true} searchable={true}
multi={true} multi={true}
/> />
</CunninghamProvider> </CunninghamProvider>,
); );
const input = screen.getByRole("combobox", { const input = screen.getByRole("combobox", {
name: "Cities", name: "Cities",
@@ -1207,7 +1207,7 @@ describe("<Select multi={true} />", () => {
expect(input).toHaveAttribute("disabled"); expect(input).toHaveAttribute("disabled");
const button: HTMLButtonElement = document.querySelector( const button: HTMLButtonElement = document.querySelector(
".c__select__inner__actions__open" ".c__select__inner__actions__open",
)!; )!;
expect(button).toBeDisabled(); expect(button).toBeDisabled();

View File

@@ -13,12 +13,12 @@ export const SelectMulti = (props: SelectMultiProps) => {
const getSelectedItemsFromProps = () => { const getSelectedItemsFromProps = () => {
const valueToUse = props.defaultValue ?? props.value ?? []; const valueToUse = props.defaultValue ?? props.value ?? [];
return props.options.filter((option) => return props.options.filter((option) =>
(valueToUse as string[]).includes(optionToValue(option)) (valueToUse as string[]).includes(optionToValue(option)),
); );
}; };
const [selectedItems, setSelectedItems] = React.useState<Option[]>( const [selectedItems, setSelectedItems] = React.useState<Option[]>(
getSelectedItemsFromProps() getSelectedItemsFromProps(),
); );
// If the component is used as a controlled component, we need to update the local value when the value prop changes. // If the component is used as a controlled component, we need to update the local value when the value prop changes.
@@ -36,7 +36,7 @@ export const SelectMulti = (props: SelectMultiProps) => {
}, [JSON.stringify(selectedItems)]); }, [JSON.stringify(selectedItems)]);
const onSelectedItemsChange: SubProps["onSelectedItemsChange"] = ( const onSelectedItemsChange: SubProps["onSelectedItemsChange"] = (
newSelectedItems newSelectedItems,
) => { ) => {
setSelectedItems(newSelectedItems); setSelectedItems(newSelectedItems);
// props.onSelectedItemsChange?.(newSelectedItems); // props.onSelectedItemsChange?.(newSelectedItems);

View File

@@ -17,22 +17,22 @@ export const expectMenuToBeClosed = (menu: HTMLDivElement) => {
export const expectOptionToBeSelected = (option: HTMLLIElement) => { export const expectOptionToBeSelected = (option: HTMLLIElement) => {
expect(option).toHaveAttribute("aria-selected", "true"); expect(option).toHaveAttribute("aria-selected", "true");
expect(Array.from(option.classList)).contains( expect(Array.from(option.classList)).contains(
"c__select__menu__item--selected" "c__select__menu__item--selected",
); );
expect(Array.from(option.classList)).contains( expect(Array.from(option.classList)).contains(
"c__select__menu__item--highlight" "c__select__menu__item--highlight",
); );
}; };
export const expectOptionToBeUnselected = (option: HTMLLIElement) => { export const expectOptionToBeUnselected = (option: HTMLLIElement) => {
expect(option).toHaveAttribute("aria-selected", "false"); expect(option).toHaveAttribute("aria-selected", "false");
expect(Array.from(option.classList)).not.contains( expect(Array.from(option.classList)).not.contains(
"c__select__menu__item--selected" "c__select__menu__item--selected",
); );
}; };
export const expectOptionToBeDisabled = (option: HTMLLIElement) => { export const expectOptionToBeDisabled = (option: HTMLLIElement) => {
expect(option).toHaveAttribute("disabled"); expect(option).toHaveAttribute("disabled");
expect(Array.from(option.classList)).contains( expect(Array.from(option.classList)).contains(
"c__select__menu__item--disabled" "c__select__menu__item--disabled",
); );
}; };

View File

@@ -48,7 +48,7 @@ describe("<Switch/>", () => {
render(<Switch label="Newsletter" state="success" text="Success text" />); render(<Switch label="Newsletter" state="success" text="Success text" />);
screen.getByText("Success text"); screen.getByText("Success text");
expect( expect(
document.querySelector(".c__field.c__field--success") document.querySelector(".c__field.c__field--success"),
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
@@ -56,7 +56,7 @@ describe("<Switch/>", () => {
render(<Switch label="Newsletter" state="error" text="Error text" />); render(<Switch label="Newsletter" state="error" text="Error text" />);
screen.getByText("Error text"); screen.getByText("Error text");
expect( expect(
document.querySelector(".c__field.c__field--error") document.querySelector(".c__field.c__field--error"),
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
@@ -68,7 +68,7 @@ describe("<Switch/>", () => {
<Switch label="Newsletter" /> <Switch label="Newsletter" />
<Switch label="Notifications" /> <Switch label="Notifications" />
<Switch label="Phone" /> <Switch label="Phone" />
</div> </div>,
); );
// expect all checkboxes to be unchecked // expect all checkboxes to be unchecked
const newsletter: HTMLInputElement = screen.getByRole("checkbox", { const newsletter: HTMLInputElement = screen.getByRole("checkbox", {

View File

@@ -26,7 +26,7 @@ export const Switch = ({
{ {
"c__checkbox--disabled": props.disabled, "c__checkbox--disabled": props.disabled,
"c__switch--full-width": fullWidth, "c__switch--full-width": fullWidth,
} },
)} )}
> >
<Field text={text} compact={true} state={state} fullWidth={fullWidth}> <Field text={text} compact={true} state={state} fullWidth={fullWidth}>

View File

@@ -103,7 +103,7 @@ describe("<Pagination/>", () => {
{ text: "2", name: "You are currently on page 2" }, { text: "2", name: "You are currently on page 2" },
{ text: "3", name: "Go to page 3" }, { text: "3", name: "Go to page 3" },
{ text: "navigate_next", name: "Go to next page", disabled: false }, { text: "navigate_next", name: "Go to next page", disabled: false },
]) ]),
); );
// Go to page 3. // Go to page 3.
@@ -120,7 +120,7 @@ describe("<Pagination/>", () => {
{ text: "2", name: "Go to page 2" }, { text: "2", name: "Go to page 2" },
{ text: "3", name: "You are currently on page 3" }, { text: "3", name: "You are currently on page 3" },
{ text: "navigate_next", name: "Go to next page", disabled: true }, { text: "navigate_next", name: "Go to next page", disabled: true },
]) ]),
); );
const previousButton = screen.getByRole("button", { const previousButton = screen.getByRole("button", {
@@ -141,7 +141,7 @@ describe("<Pagination/>", () => {
{ text: "2", name: "You are currently on page 2" }, { text: "2", name: "You are currently on page 2" },
{ text: "3", name: "Go to page 3" }, { text: "3", name: "Go to page 3" },
{ text: "navigate_next", name: "Go to next page", disabled: false }, { text: "navigate_next", name: "Go to next page", disabled: false },
]) ]),
); );
// Go to page 1. // Go to page 1.
@@ -158,7 +158,7 @@ describe("<Pagination/>", () => {
{ text: "2", name: "Go to page 2" }, { text: "2", name: "Go to page 2" },
{ text: "3", name: "Go to page 3" }, { text: "3", name: "Go to page 3" },
{ text: "navigate_next", name: "Go to next page", disabled: false }, { text: "navigate_next", name: "Go to next page", disabled: false },
]) ]),
); );
}); });
it("can goto page", async () => { it("can goto page", async () => {
@@ -176,7 +176,7 @@ describe("<Pagination/>", () => {
}); });
await waitFor(() => await waitFor(() =>
screen.getByRole("button", { name: "You are currently on page 60" }) screen.getByRole("button", { name: "You are currently on page 60" }),
); );
// Try to go to page > 100 and verify that it goes to 100. // Try to go to page > 100 and verify that it goes to 100.
@@ -187,7 +187,7 @@ describe("<Pagination/>", () => {
}); });
await waitFor(() => await waitFor(() =>
screen.getByRole("button", { name: "You are currently on page 100" }) screen.getByRole("button", { name: "You are currently on page 100" }),
); );
// Try to go to page < 1 and verify that it goes to 1. // Try to go to page < 1 and verify that it goes to 1.
@@ -198,7 +198,7 @@ describe("<Pagination/>", () => {
}); });
await waitFor(() => await waitFor(() =>
screen.getByRole("button", { name: "You are currently on page 1" }) screen.getByRole("button", { name: "You are currently on page 1" }),
); );
}); });
}); });

View File

@@ -33,14 +33,14 @@ export const List = () => {
const timeout = setTimeout(() => { const timeout = setTimeout(() => {
// Sets the number of pages based on the number of items in the database. // Sets the number of pages based on the number of items in the database.
pagination.setPagesCount( pagination.setPagesCount(
Math.ceil(database.length / pagination.pageSize) Math.ceil(database.length / pagination.pageSize),
); );
// Sets the items to display on the current page. // Sets the items to display on the current page.
setItems( setItems(
database.slice( database.slice(
(pagination.page - 1) * pagination.pageSize, (pagination.page - 1) * pagination.pageSize,
pagination.page * pagination.pageSize pagination.page * pagination.pageSize,
) ),
); );
}, 500); }, 500);
return () => { return () => {

View File

@@ -1,5 +1,5 @@
export const expectPaginationList = ( export const expectPaginationList = (
expectations: { text: string; name?: string; disabled?: boolean }[] expectations: { text: string; name?: string; disabled?: boolean }[],
) => { ) => {
const buttons = document.querySelectorAll(".c__pagination__list > *"); const buttons = document.querySelectorAll(".c__pagination__list > *");
expect(buttons.length).toEqual(expectations.length); expect(buttons.length).toEqual(expectations.length);

View File

@@ -15,7 +15,7 @@ describe("<CunninghamProvider />", () => {
render( render(
<CunninghamProvider> <CunninghamProvider>
<h1>Hi</h1> <h1>Hi</h1>
</CunninghamProvider> </CunninghamProvider>,
); );
screen.getByRole("heading", { level: 1, name: "Hi" }); screen.getByRole("heading", { level: 1, name: "Hi" });
}); });

View File

@@ -37,7 +37,7 @@ export const SUPPORTED_LOCALES = Object.values(Locales);
const findTranslation = ( const findTranslation = (
key: string, key: string,
locale: TranslationSet locale: TranslationSet,
): string | undefined => { ): string | undefined => {
const [namespace, ...keys] = key.split("."); const [namespace, ...keys] = key.split(".");
return keys.reduce((acc, subKey) => acc[subKey], (locale as any)[namespace]); return keys.reduce((acc, subKey) => acc[subKey], (locale as any)[namespace]);
@@ -54,7 +54,7 @@ export const CunninghamProvider = ({
"fr-FR": frFR, "fr-FR": frFR,
...customLocales, ...customLocales,
}), }),
[customLocales] [customLocales],
); );
const locale = useMemo(() => { const locale = useMemo(() => {
@@ -80,7 +80,7 @@ export const CunninghamProvider = ({
}, },
currentLocale: locale, currentLocale: locale,
}), }),
[currentLocale, locales] [currentLocale, locales],
); );
return ( return (

View File

@@ -2,7 +2,7 @@ import { RefObject, useEffect } from "react";
export const useHandleClickOutside = ( export const useHandleClickOutside = (
ref: RefObject<HTMLDivElement>, ref: RefObject<HTMLDivElement>,
onClickOutside: any onClickOutside: any,
) => { ) => {
useEffect(() => { useEffect(() => {
const outsideListenerEvent = (event: MouseEvent) => { const outsideListenerEvent = (event: MouseEvent) => {

View File

@@ -8,7 +8,7 @@ import path from "path";
*/ */
export const buildTheme = (debug?: boolean) => { export const buildTheme = (debug?: boolean) => {
const child = child_process.exec( const child = child_process.exec(
"cd " + path.join(__dirname, "..", "..") + " && yarn build-theme" "cd " + path.join(__dirname, "..", "..") + " && yarn build-theme",
); );
return new Promise<void>((resolve) => { return new Promise<void>((resolve) => {
child.stdout?.on("data", (data) => { child.stdout?.on("data", (data) => {

View File

@@ -21,7 +21,7 @@ describe("range", () => {
// Check step between values. // Check step between values.
output.forEach( output.forEach(
(item, index) => (item, index) =>
index < output.length - 1 && expect(output[index + 1] - item).eq(1) index < output.length - 1 && expect(output[index + 1] - item).eq(1),
); );
}); });
@@ -31,7 +31,7 @@ describe("range", () => {
[10, 0], [10, 0],
])("raises error if max is inferior to min", async (min, max) => { ])("raises error if max is inferior to min", async (min, max) => {
expect(() => range(min, max)).toThrow( expect(() => range(min, max)).toThrow(
"`min` arg must be inferior to `max` arg." "`min` arg must be inferior to `max` arg.",
); );
}); });
}); });

View File

@@ -31,11 +31,11 @@ describe("CssGenerator", () => {
"..", "..",
"tests", "tests",
"assets", "assets",
"expected-default-" + Config.tokenFilename + ".css" "expected-default-" + Config.tokenFilename + ".css",
) ),
) )
.toString() .toString()
.replace(":root", "html") .replace(":root", "html"),
); );
}; };
@@ -58,11 +58,11 @@ describe("CssGenerator", () => {
"..", "..",
"tests", "tests",
"assets", "assets",
"expected-with-utility-classes-" + Config.tokenFilename + ".css" "expected-with-utility-classes-" + Config.tokenFilename + ".css",
) ),
) )
.toString() .toString()
.replace(":root", "html") .replace(":root", "html"),
); );
}); });
}); });

View File

@@ -52,7 +52,7 @@ function generateColorClasses(tokens: Tokens) {
function generateBgClasses(tokens: Tokens) { function generateBgClasses(tokens: Tokens) {
return Object.keys(tokens.theme.colors).map( return Object.keys(tokens.theme.colors).map(
(key) => (key) =>
`.bg-${key} { background-color: var(--${Config.sass.varPrefix}theme--colors--${key}); }` `.bg-${key} { background-color: var(--${Config.sass.varPrefix}theme--colors--${key}); }`,
); );
} }
@@ -65,7 +65,7 @@ function generateBgClasses(tokens: Tokens) {
function generateClrClasses(tokens: Tokens) { function generateClrClasses(tokens: Tokens) {
return Object.keys(tokens.theme.colors).map( return Object.keys(tokens.theme.colors).map(
(key) => (key) =>
`.clr-${key} { color: var(--${Config.sass.varPrefix}theme--colors--${key}); }` `.clr-${key} { color: var(--${Config.sass.varPrefix}theme--colors--${key}); }`,
); );
} }
@@ -86,7 +86,7 @@ function generateFontClasses(tokens: Tokens) {
function generateFwClasses(tokens: Tokens) { function generateFwClasses(tokens: Tokens) {
return Object.keys(tokens.theme.font.weights).map( return Object.keys(tokens.theme.font.weights).map(
(key) => (key) =>
`.fw-${key} { font-weight: var(--${Config.sass.varPrefix}theme--font--weights--${key}); }` `.fw-${key} { font-weight: var(--${Config.sass.varPrefix}theme--font--weights--${key}); }`,
); );
} }
@@ -99,7 +99,7 @@ function generateFwClasses(tokens: Tokens) {
function generateFsClasses(tokens: Tokens) { function generateFsClasses(tokens: Tokens) {
return Object.keys(tokens.theme.font.sizes).map( return Object.keys(tokens.theme.font.sizes).map(
(key) => (key) =>
`.fs-${key} { font-size: var(--${Config.sass.varPrefix}theme--font--sizes--${key}); }` `.fs-${key} { font-size: var(--${Config.sass.varPrefix}theme--font--sizes--${key}); }`,
); );
} }
@@ -112,7 +112,7 @@ function generateFsClasses(tokens: Tokens) {
function generateFClasses(tokens: Tokens) { function generateFClasses(tokens: Tokens) {
return Object.keys(tokens.theme.font.families).map( return Object.keys(tokens.theme.font.families).map(
(key) => (key) =>
`.f-${key} { font-family: var(--${Config.sass.varPrefix}theme--font--families--${key}); }` `.f-${key} { font-family: var(--${Config.sass.varPrefix}theme--font--families--${key}); }`,
); );
} }
@@ -133,7 +133,7 @@ function generateMarginClasses(tokens: Tokens) {
`.mb-${key} { margin-bottom: var(--${Config.sass.varPrefix}theme--spacings--${key}); }` + `.mb-${key} { margin-bottom: var(--${Config.sass.varPrefix}theme--spacings--${key}); }` +
`.mt-${key} { margin-top: var(--${Config.sass.varPrefix}theme--spacings--${key}); }` + `.mt-${key} { margin-top: var(--${Config.sass.varPrefix}theme--spacings--${key}); }` +
`.ml-${key} { margin-left: var(--${Config.sass.varPrefix}theme--spacings--${key}); }` + `.ml-${key} { margin-left: var(--${Config.sass.varPrefix}theme--spacings--${key}); }` +
`.mr-${key} { margin-right: var(--${Config.sass.varPrefix}theme--spacings--${key}); }` `.mr-${key} { margin-right: var(--${Config.sass.varPrefix}theme--spacings--${key}); }`,
); );
} }
@@ -150,6 +150,6 @@ function generatePaddingClasses(tokens: Tokens) {
`.pb-${key} { padding-bottom: var(--${Config.sass.varPrefix}theme--spacings--${key}); }` + `.pb-${key} { padding-bottom: var(--${Config.sass.varPrefix}theme--spacings--${key}); }` +
`.pt-${key} { padding-top: var(--${Config.sass.varPrefix}theme--spacings--${key}); }` + `.pt-${key} { padding-top: var(--${Config.sass.varPrefix}theme--spacings--${key}); }` +
`.pl-${key} { padding-left: var(--${Config.sass.varPrefix}theme--spacings--${key}); }` + `.pl-${key} { padding-left: var(--${Config.sass.varPrefix}theme--spacings--${key}); }` +
`.pr-${key} { padding-right: var(--${Config.sass.varPrefix}theme--spacings--${key}); }` `.pr-${key} { padding-right: var(--${Config.sass.varPrefix}theme--spacings--${key}); }`,
); );
} }

View File

@@ -35,7 +35,7 @@ function JSONToSassMap(json: Object, isDefault = true) {
[`'${key}'`]: [`'${key}'`]:
typeof value === "object" ? deepQuoteObjectKeys(value) : value, typeof value === "object" ? deepQuoteObjectKeys(value) : value,
}), }),
{} {},
); );
} }
const jsonWithQuotedKeys = deepQuoteObjectKeys(json); const jsonWithQuotedKeys = deepQuoteObjectKeys(json);

View File

@@ -12,7 +12,7 @@ describe("resolveRefs", () => {
tokens as unknown as Tokens, tokens as unknown as Tokens,
(ref, resolvingTokens) => { (ref, resolvingTokens) => {
return resolve(resolvingTokens, ref); return resolve(resolvingTokens, ref);
} },
); );
expect(res).toEqual({ expect(res).toEqual({
a: "b", a: "b",
@@ -51,7 +51,7 @@ describe("resolveRefs", () => {
tokens as unknown as Tokens, tokens as unknown as Tokens,
(ref, resolvingTokens) => { (ref, resolvingTokens) => {
return resolve(resolvingTokens, ref); return resolve(resolvingTokens, ref);
} },
); );
expect(res).toEqual({ expect(res).toEqual({
a: "b", a: "b",
@@ -77,7 +77,7 @@ describe("resolveRefs", () => {
tokens as unknown as Tokens, tokens as unknown as Tokens,
(ref, resolvingTokens) => { (ref, resolvingTokens) => {
return resolve(resolvingTokens, ref); return resolve(resolvingTokens, ref);
} },
); );
expect(res).toEqual({ expect(res).toEqual({
a: "value", a: "value",
@@ -97,7 +97,7 @@ describe("resolveRefs", () => {
return `ref(${ref})`; return `ref(${ref})`;
}); });
}).toThrow( }).toThrow(
"Maximum resolveRefs iterations: please reduce usage of chained references." "Maximum resolveRefs iterations: please reduce usage of chained references.",
); );
}); });
}); });

View File

@@ -7,7 +7,7 @@ import { resolve } from "Utils/resolve";
export type Generator = ( export type Generator = (
tokens: Tokens, tokens: Tokens,
opts: { path: string; selector: string; utilityClasses?: boolean } opts: { path: string; selector: string; utilityClasses?: boolean },
) => Promise<void>; ) => Promise<void>;
export const Generators: Record<string, Generator> = { export const Generators: Record<string, Generator> = {
@@ -19,7 +19,7 @@ export const Generators: Record<string, Generator> = {
export const resolveRefs = ( export const resolveRefs = (
tokens: Tokens, tokens: Tokens,
callback: (ref: string, tokens: Tokens) => string callback: (ref: string, tokens: Tokens) => string,
): Tokens => { ): Tokens => {
let refsCount = 0; let refsCount = 0;
let resolved = tokens; let resolved = tokens;
@@ -72,7 +72,7 @@ export const resolveRefs = (
// Prevent infinite loops. // Prevent infinite loops.
if (iterations >= maxIterations) { if (iterations >= maxIterations) {
throw new Error( throw new Error(
"Maximum resolveRefs iterations: please reduce usage of chained references." "Maximum resolveRefs iterations: please reduce usage of chained references.",
); );
} }
refsCount = 0; refsCount = 0;

View File

@@ -22,13 +22,13 @@ export const buildTheme = async () => {
selector: options.selector, selector: options.selector,
utilityClasses: options.utilityClasses, utilityClasses: options.utilityClasses,
}); });
}) }),
); );
}; };
export const run = async (args: string[]) => { export const run = async (args: string[]) => {
console.log( console.log(
chalk.red(figlet.textSync("Cunningham", { horizontalLayout: "full" })) chalk.red(figlet.textSync("Cunningham", { horizontalLayout: "full" })),
); );
const commaSeparatedList = (value: string) => { const commaSeparatedList = (value: string) => {
@@ -40,21 +40,21 @@ export const run = async (args: string[]) => {
.option( .option(
"-s, --selector <selector>", "-s, --selector <selector>",
"Specify the css root selector element.", "Specify the css root selector element.",
":root" ":root",
) )
.option( .option(
"-cwd, --working-dir <directory>", "-cwd, --working-dir <directory>",
"Specify the working dir ( you might not need this )." "Specify the working dir ( you might not need this ).",
) )
.option( .option(
"-o, --output <directory>", "-o, --output <directory>",
"Specify the output dir of generated files." "Specify the output dir of generated files.",
) )
.option("--utility-classes", "Generate CSS utility classes.") .option("--utility-classes", "Generate CSS utility classes.")
.requiredOption( .requiredOption(
"-g, --generators <generators>", "-g, --generators <generators>",
"Specify the generators to use.", "Specify the generators to use.",
commaSeparatedList commaSeparatedList,
) )
.parse(args); .parse(args);

View File

@@ -14,6 +14,6 @@ export const put = (path: string, content: string) => {
fs.writeFileSync(path, content); fs.writeFileSync(path, content);
console.log( console.log(
chalk.bgGreen(chalk.white("File " + path + " generated successfully.")) chalk.bgGreen(chalk.white("File " + path + " generated successfully.")),
); );
}; };

View File

@@ -1,7 +1,7 @@
export const resolve = ( export const resolve = (
object: Record<string, any>, object: Record<string, any>,
path: string, path: string,
separator: string = "." separator: string = ".",
): any => { ): any => {
return path.split(separator).reduce((acc, cur) => { return path.split(separator).reduce((acc, cur) => {
return acc[cur]; return acc[cur];

View File

@@ -16,7 +16,7 @@ const runBin = async (args: string) => {
const promise = exec( const promise = exec(
path.join(__dirname, "..", "..", "..", "dist", "bin", "Main.js") + path.join(__dirname, "..", "..", "..", "dist", "bin", "Main.js") +
" " + " " +
args args,
); );
promise.child.stdout?.on("data", (data) => { promise.child.stdout?.on("data", (data) => {
@@ -61,10 +61,10 @@ describe("Cunningham Bin", () => {
path.join( path.join(
__dirname, __dirname,
"assets", "assets",
"expected-default-" + Config.tokenFilename + ".css" "expected-default-" + Config.tokenFilename + ".css",
) ),
) )
.toString() .toString(),
); );
}); });
@@ -77,7 +77,7 @@ describe("Cunningham Bin", () => {
fs.copyFileSync( fs.copyFileSync(
path.join(__dirname, "assets", "cunningham.js"), path.join(__dirname, "assets", "cunningham.js"),
localConfigurationFile localConfigurationFile,
); );
expect(fs.existsSync(localConfigurationFile)).toEqual(true); expect(fs.existsSync(localConfigurationFile)).toEqual(true);
@@ -89,10 +89,10 @@ describe("Cunningham Bin", () => {
path.join( path.join(
__dirname, __dirname,
"assets", "assets",
"expected-js-" + Config.tokenFilename + ".css" "expected-js-" + Config.tokenFilename + ".css",
) ),
) )
.toString() .toString(),
); );
}); });
@@ -105,7 +105,7 @@ describe("Cunningham Bin", () => {
fs.copyFileSync( fs.copyFileSync(
path.join(__dirname, "assets", "cunningham.ts"), path.join(__dirname, "assets", "cunningham.ts"),
localConfigurationFile localConfigurationFile,
); );
expect(fs.existsSync(localConfigurationFile)).toEqual(true); expect(fs.existsSync(localConfigurationFile)).toEqual(true);
@@ -131,10 +131,10 @@ describe("Cunningham Bin", () => {
path.join( path.join(
__dirname, __dirname,
"assets", "assets",
"expected-default-" + Config.tokenFilename + ".css" "expected-default-" + Config.tokenFilename + ".css",
) ),
) )
.toString() .toString(),
); );
}; };

View File

@@ -9,7 +9,7 @@ import { Generators } from "Generators";
*/ */
export const cleanup = (dir: string) => { export const cleanup = (dir: string) => {
const tokenFilenames = Object.keys(Generators).map( const tokenFilenames = Object.keys(Generators).map(
(extension) => Config.tokenFilename + "." + extension (extension) => Config.tokenFilename + "." + extension,
); );
tokenFilenames.forEach((filename) => { tokenFilenames.forEach((filename) => {

View File

@@ -9,7 +9,7 @@ describe("buildRefs", () => {
"primary-500": "blue", "primary-500": "blue",
}, },
}, },
}) }),
).toEqual({ ).toEqual({
theme: { theme: {
colors: { colors: {