Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions packages/gamut/__tests__/__snapshots__/gamut.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,13 @@ exports[`Gamut Exported Keys 1`] = `
"BodyPortal",
"Box",
"Breadcrumbs",
"Calendar",
"CalendarBody",
"CalendarFooter",
"CalendarHeader",
"Card",
"Checkbox",
"clampToMonth",
"Coachmark",
"Column",
"ConnectedCheckbox",
Expand All @@ -32,6 +37,11 @@ exports[`Gamut Exported Keys 1`] = `
"CTAButton",
"DataList",
"DataTable",
"DatePicker",
"DatePickerCalendar",
"DatePickerContext",
"DatePickerInput",
"DatePickerProvider",
"DelayedRenderWrapper",
"Dialog",
"Disclosure",
Expand All @@ -46,14 +56,21 @@ exports[`Gamut Exported Keys 1`] = `
"FocusTrap",
"focusVisibleStyle",
"Form",
"formatDateForInput",
"formatDateRangeForInput",
"formatMonthYear",
"FormError",
"FormGroup",
"FormGroupDescription",
"FormGroupLabel",
"FormPropsContext",
"FormRequiredText",
"generateResponsiveClassnames",
"getDayOfWeek",
"getFocusableElements",
"getMonthGrid",
"getWeekdayFullNames",
"getWeekdayLabels",
"GridBox",
"GridForm",
"GridFormContent",
Expand All @@ -63,6 +80,11 @@ exports[`Gamut Exported Keys 1`] = `
"InfoTip",
"Input",
"isClickableCrumb",
"isDateDisabled",
"isDateInRange",
"isPastDate",
"isSameDay",
"isValidDate",
"LayoutGrid",
"List",
"ListCol",
Expand All @@ -75,6 +97,8 @@ exports[`Gamut Exported Keys 1`] = `
"omitProps",
"Overlay",
"Pagination",
"parseDateFromInput",
"parseDateRangeFromInput",
"Popover",
"PopoverContainer",
"PreviewTip",
Expand Down Expand Up @@ -112,6 +136,7 @@ exports[`Gamut Exported Keys 1`] = `
"ToolTip",
"USE_DEBOUNCED_FIELD_DIRTY_KEY",
"useConnectedForm",
"useDatePicker",
"useDebouncedField",
"useField",
"useFormState",
Expand Down
15 changes: 15 additions & 0 deletions packages/gamut/src/DatePicker/Calendar/Calendar.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { css } from '@codecademy/gamut-styles';
import styled from '@emotion/styled';

/**
* Outer wrapper for the calendar (header + body + footer).
* Used by DatePickerCalendar to group the calendar content.
*/
export const Calendar = styled.div(
css({
backgroundColor: 'background',
borderRadius: 'lg',
boxShadow: '0 4px 16px rgba(0, 0, 0, 0.12)',
width: 'max-content',
})
);
Copy link
Contributor

Choose a reason for hiding this comment

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

i found this confusing since this just a wrapper and DatePickerCalendar is the actual calendar

Copy link
Contributor Author

Choose a reason for hiding this comment

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

yeah this can be prettier. DatePickerCalendar is for DatePicker, but in theory the inside calendar parts could be used on their own

218 changes: 218 additions & 0 deletions packages/gamut/src/DatePicker/Calendar/CalendarBody.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
import { css, states } from '@codecademy/gamut-styles';
import styled from '@emotion/styled';
import { useCallback, useEffect, useMemo, useRef } from 'react';
import * as React from 'react';

import { TextButton } from '../../Button';
import { CalendarBodyProps } from './types';
import {
getMonthGrid,
isDateDisabled,
isDateInRange,
isSameDay,
} from './utils/dateGrid';
import { getWeekdayFullNames, getWeekdayLabels } from './utils/format';
import { getDatesWithRow, keyHandler } from './utils/keyHandler';

const TableHeader = styled.th(
css({
fontSize: 14,
fontWeight: 'base',
color: 'text-disabled',
textAlign: 'center',
})
);

const DateButton = styled(TextButton)(
states({
isToday: {
position: 'relative',
'&::after': {
content: '""',
position: 'absolute',
bottom: 4,
left: '50%',
width: 4,
height: 4,
borderRadius: 'full',
bg: 'hyper',
},
},
isSelected: {
bg: 'text',
color: 'background',
'&:hover, &:focus': {
bg: 'secondary-hover',
color: 'background',
},
'&::after': {
bg: 'background',
},
},
isInRange: {
bg: 'text-disabled',
color: 'background',
borderRadius: 'none',
'&:hover, &:focus': {
bg: 'secondary-hover',
color: 'background',
},
'&::after': {
bg: 'background',
},
},
disabled: {
color: 'text-disabled',
textDecoration: 'line-through',
},
}),
css({
fontWeight: 'base',
width: '32px',
})
);

export const CalendarBody: React.FC<CalendarBodyProps> = ({
visibleDate,
selectedDate,
endDate = null,
disabledDates = [],
onDateSelect,
locale,
weekStartsOn = 0,
labelledById,
focusedDate,
onFocusedDateChange,
onVisibleDateChange,
onEscapeKeyPress,
}) => {
const year = visibleDate.getFullYear();
const month = visibleDate.getMonth();
const weeks = getMonthGrid(year, month, weekStartsOn);
const weekdayLabels = getWeekdayLabels(locale, weekStartsOn);
const weekdayFullNames = getWeekdayFullNames(locale, weekStartsOn);
const buttonRefs = useRef<Map<number, HTMLElement>>(new Map());

const datesWithRow = useMemo(() => getDatesWithRow(weeks), [weeks]);
const focusTarget = focusedDate ?? selectedDate;

const isToday = useCallback(
(d: Date | null) => d !== null && isSameDay(d, new Date()),
[]
);

const focusButton = useCallback((date: Date | null) => {
if (date === null) return;
const key = new Date(
date.getFullYear(),
date.getMonth(),
date.getDate()
).getTime();
buttonRefs.current.get(key)?.focus();
}, []);

useEffect(() => {
if (focusTarget !== null) focusButton(focusTarget);
}, [focusTarget, focusButton]);

const handleKeyDown = useCallback(
(e: React.KeyboardEvent, date: Date) =>
keyHandler(
e,
date,
onFocusedDateChange,
datesWithRow,
month,
year,
disabledDates,
onDateSelect,
onEscapeKeyPress,
onVisibleDateChange
),
[
onFocusedDateChange,
datesWithRow,
month,
year,
disabledDates,
onDateSelect,
onEscapeKeyPress,
onVisibleDateChange,
]
);

const setButtonRef = useCallback((date: Date, el: HTMLElement | null) => {
const k = new Date(
date.getFullYear(),
date.getMonth(),
date.getDate()
).getTime();
if (el) buttonRefs.current.set(k, el);
else buttonRefs.current.delete(k);
}, []);

return (
<table aria-labelledby={labelledById} role="grid" width="100%">
<thead>
<tr>
{weekdayLabels.map((label, i) => (
<TableHeader abbr={weekdayFullNames[i]} key={label} scope="col">
{label}
</TableHeader>
))}
</tr>
</thead>
<tbody>
{weeks.map((week, rowIndex) => (
<tr key={week.join('-')}>
{week.map((date, colIndex) => {
if (date === null) {
return (
// fix this error
// eslint-disable-next-line react/no-array-index-key, jsx-a11y/control-has-associated-label
<td key={`empty-${rowIndex}-${colIndex}`} role="gridcell" />
);
}
const selected =
isSameDay(date, selectedDate) || isSameDay(date, endDate);
const inRange =
!!selectedDate &&
!!endDate &&
isDateInRange(date, selectedDate, endDate);
const disabled = isDateDisabled(date, disabledDates);
const today = isToday(date);
// this is making the selected date a differnet color bc it is focused, look into further
const isFocused =
focusTarget !== null && isSameDay(date, focusTarget);

return (
<td
aria-selected={selected}
key={date.getTime()}
role="gridcell"
>
<DateButton
disabled={disabled}
isInRange={inRange}
isSelected={selected}
isToday={today}
ref={(el) => setButtonRef(date, el as HTMLElement | null)}
tabIndex={isFocused ? 0 : -1}
variant="secondary"
onClick={() => onDateSelect(date)}
onFocus={() => onFocusedDateChange?.(date)}
onKeyDown={(e: React.KeyboardEvent) =>
handleKeyDown(e, date)
}
>
{date.getDate()}
</DateButton>
</td>
);
})}
</tr>
))}
</tbody>
</table>
);
};
62 changes: 62 additions & 0 deletions packages/gamut/src/DatePicker/Calendar/CalendarFooter.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import * as React from 'react';

import { FlexBox } from '../../Box';
import { TextButton } from '../../Button';
import { CalendarFooterProps } from './types';

// function formatQuickActionLabel(action: QuickAction): string {
// const { num, timePeriod } = action;
// const period =
// timePeriod === 'day'
// ? num === 1
// ? 'day'
// : 'days'
// : timePeriod === 'week'
// ? num === 1
// ? 'week'
// : 'weeks'
// : timePeriod === 'month'
// ? num === 1
// ? 'month'
// : 'months'
// : num === 1
// ? 'year'
// : 'years';
// return `${num} ${period}`;
// }

export const CalendarFooter: React.FC<CalendarFooterProps> = ({
onClearDate,
onTodayClick,
onSelectedDateChange,
onCurrentMonthYearChange,
}) => {
const handleClearDate = () => {
onSelectedDateChange(null);
onClearDate?.();
};

const handleTodayClick = () => {
const today = new Date();
onSelectedDateChange(today);
onCurrentMonthYearChange(
new Date(today.getFullYear(), today.getMonth(), 1)
);
onTodayClick?.();
};
// const actions = quickActions.slice(0, 3);

return (
<FlexBox
alignItems="center"
borderTop={1}
justifyContent="space-between"
p={12}
>
<TextButton onClick={handleClearDate}>Clear</TextButton>
<FlexBox gap={32}>
<TextButton onClick={handleTodayClick}>Today</TextButton>
</FlexBox>
</FlexBox>
);
};
Loading
Loading