diff --git a/packages/core-fields/src/post_type_supports/date/field.tsx b/packages/core-fields/src/post_type_supports/date/field.tsx index 031ab3596bccce..5f3b5c8052a03c 100644 --- a/packages/core-fields/src/post_type_supports/date/field.tsx +++ b/packages/core-fields/src/post_type_supports/date/field.tsx @@ -1,3 +1,6 @@ +import { resolveSelect } from '@wordpress/data'; +import { store as coreDataStore } from '@wordpress/core-data'; +import { getDate } from '@wordpress/date'; import type { FieldsScriptParts } from '../../types'; import { hasActionLink } from '../../shared/has-action-link'; import type { PostWithDate } from './types'; @@ -10,4 +13,28 @@ export const fieldExtensions: FieldsScriptParts< PostWithDate >[ string ] = { // Only the users who can publish the post see the control. isVisible: ( item ) => hasActionLink( item, 'wp:action-publish' ), render: DateView, + Edit: { + control: 'datetime', + // Mark the days that already have published or scheduled posts of + // the same type, to help pick a free day. + getEvents: async ( { item, from, to } ) => { + // A filter or a bulk edit form has no post type. + if ( ! item?.type ) { + return []; + } + const posts = + ( await resolveSelect( coreDataStore ).getEntityRecords< + Required< Pick< PostWithDate, 'id' | 'date' > > + >( 'postType', item.type, { + status: 'publish,future', + after: from.toISOString(), + before: to.toISOString(), + exclude: item.id ? [ item.id ] : undefined, + per_page: 100, + _fields: 'id,date', + } ) ) ?? []; + // `date` is in the site time zone. + return posts.map( ( { date } ) => ( { date: getDate( date ) } ) ); + }, + }, }; diff --git a/packages/core-fields/src/post_type_supports/date/types.ts b/packages/core-fields/src/post_type_supports/date/types.ts index ac59740a952ba1..40da1f9f09e823 100644 --- a/packages/core-fields/src/post_type_supports/date/types.ts +++ b/packages/core-fields/src/post_type_supports/date/types.ts @@ -2,6 +2,8 @@ * The properties of a post the date field reads. */ export interface PostWithDate { + id?: number; + type?: string; date?: string; modified?: string; status?: string; diff --git a/packages/core-fields/src/test/post-type-supports.jsdom.test.ts b/packages/core-fields/src/test/post-type-supports.jsdom.test.ts index fe8c6cb1bee92e..b70af2abeb64b5 100644 --- a/packages/core-fields/src/test/post-type-supports.jsdom.test.ts +++ b/packages/core-fields/src/test/post-type-supports.jsdom.test.ts @@ -1,6 +1,20 @@ -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; +import type { EditConfigDatetime } from '@wordpress/dataviews'; import postTypeSupports from '../post_type_supports'; +const { getEntityRecords } = vi.hoisted( () => ( { + getEntityRecords: vi.fn(), +} ) ); +vi.mock( import( '@wordpress/data' ), async ( importOriginal ) => { + const actual = await importOriginal(); + return { + ...actual, + resolveSelect: ( () => ( { + getEntityRecords, + } ) ) as unknown as typeof actual.resolveSelect, + }; +} ); + describe( 'post_type_supports', () => { it( 'provides the JavaScript parts of the fields that have some', () => { expect( Object.keys( postTypeSupports ) ).toEqual( [ @@ -118,6 +132,36 @@ describe( 'post_type_supports', () => { expect( isVisible?.( { _links: {} } ) ).toBe( false ); } ); + it( 'marks the days with published or scheduled posts of the same type in the date calendar', async () => { + const { getEvents } = postTypeSupports.date.Edit as EditConfigDatetime; + const from = new Date( '2026-11-01T00:00:00.000Z' ); + const to = new Date( '2026-11-30T23:59:59.999Z' ); + getEntityRecords.mockResolvedValue( [ + { id: 2, date: '2026-11-05T10:00:00' }, + ] ); + + await expect( + getEvents?.( { item: { id: 1, type: 'post' }, from, to } ) + ).resolves.toEqual( [ + { date: new Date( '2026-11-05T10:00:00.000Z' ) }, + ] ); + expect( getEntityRecords ).toHaveBeenCalledWith( 'postType', 'post', { + status: 'publish,future', + after: '2026-11-01T00:00:00.000Z', + before: '2026-11-30T23:59:59.999Z', + exclude: [ 1 ], + per_page: 100, + _fields: 'id,date', + } ); + + // A filter or a bulk edit form has no post type to look up. + getEntityRecords.mockClear(); + await expect( getEvents?.( { item: {}, from, to } ) ).resolves.toEqual( + [] + ); + expect( getEntityRecords ).not.toHaveBeenCalled(); + } ); + it( 'treats an auto-draft as a draft', () => { const { getValue } = postTypeSupports.status; expect( getValue?.( { item: { status: 'auto-draft' } } ) ).toBe( diff --git a/packages/dataviews/CHANGELOG.md b/packages/dataviews/CHANGELOG.md index 0d002b3456df70..9947472687b492 100644 --- a/packages/dataviews/CHANGELOG.md +++ b/packages/dataviews/CHANGELOG.md @@ -9,6 +9,7 @@ ### Enhancements +- DataForm: Add a `getEvents` option to the `datetime` control config, which marks days on the calendar, such as days that already have posts ([#86249](https://github.com/WordPress/gutenberg/pull/86249)). - Use `Button` and `IconButton` from `@wordpress/ui` in the bulk actions bar. Hovered actions now get a background fill, a running action shows a spinner in place of its label and is announced to screen readers, and the `dataviews-bulk-actions__action` class is removed ([#85939](https://github.com/WordPress/gutenberg/pull/85939)). - DataForm: Tighten the line height of field values in the panel layout, so values that wrap onto several lines take less room ([#85828](https://github.com/WordPress/gutenberg/pull/85828)). - Omit trailing ellipses from action button labels ([#85396](https://github.com/WordPress/gutenberg/pull/85396)). diff --git a/packages/dataviews/README.md b/packages/dataviews/README.md index 053d458657b15a..32fbfda3da39e2 100644 --- a/packages/dataviews/README.md +++ b/packages/dataviews/README.md @@ -1630,6 +1630,23 @@ Additionally, some of the bundled Edit controls are configurable via a config ob } ``` +`compact` renders the control without the calendar widget. `getEvents` loads the events to mark on the calendar, such as the posts already published or scheduled on a day. It receives the item and the start and end of the month the calendar displays (`{ item, from, to }`), runs again each time the user navigates to another month, and returns a promise of `{ date }` objects: + +```js +{ + id: 'date', + type: 'datetime', + label: 'Date', + Edit: { + control: 'datetime', + getEvents: async ( { item, from, to } ) => { + const posts = await fetchPosts( { after: from, before: to } ); + return posts.map( ( post ) => ( { date: new Date( post.date ) } ) ); + }, + } +} +``` + Finally, the field author can always provide its own custom `Edit` control. It receives the following props: - `data`: the item to be processed @@ -1646,6 +1663,7 @@ Finally, the field author can always provide its own custom `Edit` control. It r - `suffixPadding`: the padding of the suffix slot, `default` (the default) or `minimal` (text control) - `rows`: the number of rows to display (e.g., in the text area component) - `compact`: whether to render a compact version without the calendar widget (datetime control) + - `getEvents`: a function that loads the events to mark on the calendar widget (datetime control) ```js { diff --git a/packages/dataviews/src/components/dataform-controls/datetime.tsx b/packages/dataviews/src/components/dataform-controls/datetime.tsx index c9e75023d5ea6d..2a6a227e9178ad 100644 --- a/packages/dataviews/src/components/dataform-controls/datetime.tsx +++ b/packages/dataviews/src/components/dataform-controls/datetime.tsx @@ -15,6 +15,7 @@ import { OPERATOR_IN_THE_PAST, OPERATOR_OVER } from '../../constants'; import RelativeDateControl from './utils/relative-date-control'; import toCalendarDate from './utils/to-calendar-date'; import useDisabledDateMatchers from './utils/use-disabled-date-matchers'; +import useCalendarEvents from './utils/use-calendar-events'; import getCustomValidity from './utils/get-custom-validity'; import getCalendarLocale from './utils/get-calendar-locale'; import getTimezoneDescription from './utils/get-timezone-description'; @@ -37,7 +38,7 @@ function CalendarDateTimeControl< Item >( { validity, config, }: DataFormControlProps< Item > ) { - const { compact } = config || {}; + const { compact, getEvents } = config || {}; const { id, label, description, setValue, getValue, isValid } = field; const disabled = field.isDisabled( { item: data, field } ); const fieldValue = getValue( { item: data } ); @@ -65,6 +66,12 @@ function CalendarDateTimeControl< Item >( { } }, [ timeZone, value ] ); + const events = useCalendarEvents( + compact ? undefined : getEvents, + data, + calendarMonth + ); + const inputControlRef = useRef< HTMLInputElement >( null ); const validationTimeoutRef = useRef< ReturnType< typeof setTimeout > >( undefined ); @@ -210,6 +217,7 @@ function CalendarDateTimeControl< Item >( { dir={ isRTL() ? 'rtl' : 'ltr' } weekStartsOn={ weekStartsOn } disabled={ disabled || disabledMatchers } + events={ events } /> ) } diff --git a/packages/dataviews/src/components/dataform-controls/test/datetime.jsdom.test.tsx b/packages/dataviews/src/components/dataform-controls/test/datetime.jsdom.test.tsx index 0e4b8e7c356e50..56b57f2038c930 100644 --- a/packages/dataviews/src/components/dataform-controls/test/datetime.jsdom.test.tsx +++ b/packages/dataviews/src/components/dataform-controls/test/datetime.jsdom.test.tsx @@ -364,4 +364,63 @@ describe( 'DateTime control', () => { } } ); } ); + + describe( 'calendar events', () => { + it( 'marks the events of the displayed month and loads them again on navigation', async () => { + const user = userEvent.setup(); + const getEvents = vi.fn( async ( { from }: { from: Date } ) => + from.getUTCMonth() === 2 + ? [ { date: new Date( '2024-03-20T08:00:00.000Z' ) } ] + : [] + ); + const item = { published: '2024-03-15T10:30:00.000Z' }; + + render( + + ); + + expect( + await screen.findByRole( 'button', { + name: 'Wednesday, March 20, 2024, 1 event', + } ) + ).toBeVisible(); + expect( getEvents ).toHaveBeenCalledTimes( 1 ); + expect( getEvents ).toHaveBeenLastCalledWith( { + item, + from: new Date( '2024-03-01T00:00:00.000Z' ), + to: new Date( '2024-03-31T23:59:59.999Z' ), + } ); + + await user.click( + screen.getByRole( 'button', { name: 'Next month' } ) + ); + + expect( getEvents ).toHaveBeenCalledTimes( 2 ); + expect( getEvents ).toHaveBeenLastCalledWith( + expect.objectContaining( { + from: new Date( '2024-04-01T00:00:00.000Z' ), + } ) + ); + } ); + + it( 'does not load events without the calendar', () => { + const getEvents = vi.fn( async () => [] ); + + render( + + ); + + expect( getEvents ).not.toHaveBeenCalled(); + } ); + } ); } ); diff --git a/packages/dataviews/src/components/dataform-controls/utils/use-calendar-events.ts b/packages/dataviews/src/components/dataform-controls/utils/use-calendar-events.ts new file mode 100644 index 00000000000000..65a7c4c5de3047 --- /dev/null +++ b/packages/dataviews/src/components/dataform-controls/utils/use-calendar-events.ts @@ -0,0 +1,59 @@ +import { endOfMonth, startOfMonth } from 'date-fns'; +import { useEffect, useRef, useState } from '@wordpress/element'; +import type { CalendarEvent, GetCalendarEvents } from '../../../types'; + +/** + * Loads the events to mark on the calendar for the month it displays. + * + * Events load again when the displayed month changes, not when the item does: + * an edit to the item (e.g. typing a new date) shouldn't refetch them. + * + * @param getEvents The loader from the control config, if any. + * @param item The item being edited. + * @param month A date in the displayed month, in the calendar's time zone. + * @return The events of the displayed month, once loaded. + */ +export default function useCalendarEvents< Item >( + getEvents: GetCalendarEvents< Item > | undefined, + item: Item, + month: Date +): CalendarEvent[] | undefined { + const [ events, setEvents ] = useState< CalendarEvent[] >(); + // Read by the loading effect, which only reruns when the month changes. + const latestRef = useRef( { item, month } ); + useEffect( () => { + latestRef.current = { item, month }; + }, [ item, month ] ); + + // `month` can change identity within the same month; its start doesn't. + const monthStart = startOfMonth( month ).getTime(); + + useEffect( () => { + setEvents( undefined ); + if ( ! getEvents ) { + return; + } + let isCurrent = true; + // Computed on the calendar's date, so the bounds follow its time zone. + const from = startOfMonth( latestRef.current.month ); + getEvents( { + item: latestRef.current.item, + from, + to: endOfMonth( from ), + } ).then( + ( result ) => { + if ( isCurrent ) { + setEvents( result ); + } + }, + () => { + // The markers are a hint: leave them out if they fail to load. + } + ); + return () => { + isCurrent = false; + }; + }, [ getEvents, monthStart ] ); + + return events; +} diff --git a/packages/dataviews/src/types/field-api.ts b/packages/dataviews/src/types/field-api.ts index 4f901599371c05..4143c1d038e431 100644 --- a/packages/dataviews/src/types/field-api.ts +++ b/packages/dataviews/src/types/field-api.ts @@ -282,7 +282,7 @@ export type EditConfigText = { /** * Edit configuration for datetime controls. */ -export type EditConfigDatetime = { +export type EditConfigDatetime< Item = any > = { /** * The control to render. */ @@ -291,8 +291,42 @@ export type EditConfigDatetime = { * Whether to render a compact version without the calendar widget. */ compact?: boolean; + /** + * Loads the events to mark on the calendar widget. + */ + getEvents?: GetCalendarEvents< Item >; }; +/** + * An event to mark on a calendar day, such as content already scheduled. + */ +export type CalendarEvent = { + /** + * When the event happens. + */ + date: Date; +}; + +/** + * Loads the events to mark on the calendar widget of a datetime control. It is + * called with the item being edited and the bounds of the month the calendar + * displays, and again each time the user navigates to another month. + */ +export type GetCalendarEvents< Item = any > = ( args: { + /** + * The item being edited. + */ + item: Item; + /** + * The start of the displayed month, in the calendar's time zone. + */ + from: Date; + /** + * The end of the displayed month, in the calendar's time zone. + */ + to: Date; +} ) => Promise< CalendarEvent[] >; + /** * Edit configuration for other control types (excluding 'text', 'textarea', and 'datetime'). */ @@ -307,10 +341,10 @@ export type EditConfigGeneric = { * Edit configuration object with type-safe control options. * Each control type has its own specific configuration properties. */ -export type EditConfig = +export type EditConfig< Item = any > = | EditConfigTextarea | EditConfigText - | EditConfigDatetime + | EditConfigDatetime< Item > | EditConfigGeneric; /** @@ -358,7 +392,10 @@ export type Field< Item > = { /** * Callback used to render an edit control for the field. */ - Edit?: ComponentType< DataFormControlProps< Item > > | string | EditConfig; + Edit?: + | ComponentType< DataFormControlProps< Item > > + | string + | EditConfig< Item >; /** * Callback used to sort the field. @@ -803,6 +840,10 @@ export type DataFormControlProps< Item > = { * (datetime control). */ compact?: boolean; + /** + * Loads the events to mark on the calendar widget (datetime control). + */ + getEvents?: GetCalendarEvents< Item >; }; }; diff --git a/packages/ui/CHANGELOG.md b/packages/ui/CHANGELOG.md index 030b153f25c0b5..19690b33384bd6 100644 --- a/packages/ui/CHANGELOG.md +++ b/packages/ui/CHANGELOG.md @@ -8,6 +8,7 @@ ### New Features +- `Calendar`, `RangeCalendar`: Add an `events` prop that marks days with a dot and adds the number of events to their accessible label ([#86249](https://github.com/WordPress/gutenberg/pull/86249)). - `Badge`: Add an optional `infotip` popup with a trailing help icon ([#85309](https://github.com/WordPress/gutenberg/pull/85309)). - `Menu.Popup`: Add width presets, with `sm` as the default to preserve the 320px maximum width ([#84086](https://github.com/WordPress/gutenberg/pull/84086)). - `Notice.List`: Add announcements for added and changed notices, excluding hidden content, with per-notice message and urgency overrides ([#85209](https://github.com/WordPress/gutenberg/pull/85209)). diff --git a/packages/ui/src/calendar/calendar.tsx b/packages/ui/src/calendar/calendar.tsx index 5d5480cb094e7a..621a190251a2a9 100644 --- a/packages/ui/src/calendar/calendar.tsx +++ b/packages/ui/src/calendar/calendar.tsx @@ -1,8 +1,9 @@ import { DayPicker } from '@daypicker/react'; import { forwardRef, useCallback, useMemo } from '@wordpress/element'; -import { COMMON_PROPS } from './utils/constants'; +import { COMMON_PROPS, MODIFIER_CLASSNAMES } from './utils/constants'; import { clampNumberOfMonths } from './utils/misc'; import { useControlledValue } from './utils/use-controlled-value'; +import { useEvents } from './utils/use-events'; import { useLocalizationProps } from './utils/use-localization-props'; import { usePreserveDayFocus } from './utils/use-preserve-day-focus'; import { RootContext } from './utils/root-context'; @@ -30,6 +31,7 @@ export const Calendar = forwardRef< HTMLDivElement, CalendarProps >( role = 'application', 'aria-label': ariaLabel, labels: customLabels, + events, ...props }, ref @@ -41,13 +43,18 @@ export const Calendar = forwardRef< HTMLDivElement, CalendarProps >( mode: 'single', } ); - const labels = useMemo( + const mergedLabels = useMemo( () => customLabels ? { ...localizationProps.labels, ...customLabels } : localizationProps.labels, [ localizationProps.labels, customLabels ] ); + const { eventsMatcher, labels } = useEvents( events, mergedLabels ); + const eventsModifiers = useMemo( + () => ( eventsMatcher ? { events: eventsMatcher } : undefined ), + [ eventsMatcher ] + ); const onChange: OnValueChangeHandler< Date | null | undefined > = useCallback( ( selected, triggerDate, modifiers, e ) => { @@ -95,6 +102,8 @@ export const Calendar = forwardRef< HTMLDivElement, CalendarProps >( onSelect={ setSelected } onDayFocus={ dayFocusProps.onDayFocus } onDayBlur={ dayFocusProps.onDayBlur } + modifiers={ eventsModifiers } + modifiersClassNames={ MODIFIER_CLASSNAMES } /> ); diff --git a/packages/ui/src/calendar/range-calendar.tsx b/packages/ui/src/calendar/range-calendar.tsx index 81754b174f85ec..50a070aaf2f69a 100644 --- a/packages/ui/src/calendar/range-calendar.tsx +++ b/packages/ui/src/calendar/range-calendar.tsx @@ -4,6 +4,7 @@ import { forwardRef, useMemo, useState, useCallback } from '@wordpress/element'; import { COMMON_PROPS, MODIFIER_CLASSNAMES } from './utils/constants'; import { clampNumberOfMonths } from './utils/misc'; import { useControlledValue } from './utils/use-controlled-value'; +import { useEvents } from './utils/use-events'; import { useLocalizationProps } from './utils/use-localization-props'; import { usePreserveDayFocus } from './utils/use-preserve-day-focus'; import { RootContext } from './utils/root-context'; @@ -162,6 +163,7 @@ export const RangeCalendar = forwardRef< HTMLDivElement, RangeCalendarProps >( role = 'application', 'aria-label': ariaLabel, labels: customLabels, + events, ...props }, ref @@ -173,13 +175,14 @@ export const RangeCalendar = forwardRef< HTMLDivElement, RangeCalendarProps >( mode: 'range', } ); - const labels = useMemo( + const mergedLabels = useMemo( () => customLabels ? { ...localizationProps.labels, ...customLabels } : localizationProps.labels, [ localizationProps.labels, customLabels ] ); + const { eventsMatcher, labels } = useEvents( events, mergedLabels ); const onChange: OnValueChangeHandler< DateRange | null | undefined > = useCallback( ( selected, triggerDate, modifiers, e ) => { @@ -222,8 +225,9 @@ export const RangeCalendar = forwardRef< HTMLDivElement, RangeCalendarProps >( preview: previewRange, preview_start: previewRange?.from, preview_end: previewRange?.to, + ...( eventsMatcher ? { events: eventsMatcher } : {} ), }; - }, [ previewRange ] ); + }, [ previewRange, eventsMatcher ] ); const rootContextValue = useMemo( () => ( { diff --git a/packages/ui/src/calendar/stories/index.story.tsx b/packages/ui/src/calendar/stories/index.story.tsx index 23140088ea0f76..944320b50121b2 100644 --- a/packages/ui/src/calendar/stories/index.story.tsx +++ b/packages/ui/src/calendar/stories/index.story.tsx @@ -42,6 +42,21 @@ export const DisabledDates: Story = { }, }; +/** + * Use `events` to mark days that already have something on them, such as + * scheduled posts. Each marked day shows a dot, and its accessible label + * includes the number of events. + */ +export const WithEvents: Story = { + args: { + events: [ 3, 10, 10, 18, 24 ].map( ( day ) => { + const date = new Date(); + date.setDate( day ); + return { date }; + } ), + }, +}; + export const WithSelectedDateAndMonth: Story = { args: { defaultValue: firstDayOfNextMonth, diff --git a/packages/ui/src/calendar/style.module.css b/packages/ui/src/calendar/style.module.css index e3c3bb7a062817..6e134570576475 100644 --- a/packages/ui/src/calendar/style.module.css +++ b/packages/ui/src/calendar/style.module.css @@ -184,6 +184,29 @@ border: 2px solid currentColor; } + /* + * Days with events: show a dot below the day number. Like the today dot, it + * follows the text color, so it stays visible on selected days and in + * forced-colors (high-contrast) mode. + */ + .events::before { + content: ""; + position: absolute; + z-index: 1; + inset-block-end: 3px; + inset-inline-start: 50%; + translate: -50% 0; + width: 0; + height: 0; + border-radius: 50%; + border: 2px solid currentColor; + pointer-events: none; + } + + .root[dir="rtl"] .events::before { + translate: 50% 0; + } + /* Selected date button (individual date, range start, and range end) */ .selected:not(.range-middle) { &:has(.day-button, .day-button:hover:not(:disabled)) { diff --git a/packages/ui/src/calendar/test/calendar.jsdom.test.tsx b/packages/ui/src/calendar/test/calendar.jsdom.test.tsx index eef964b5eff2cf..665a7193be9c72 100644 --- a/packages/ui/src/calendar/test/calendar.jsdom.test.tsx +++ b/packages/ui/src/calendar/test/calendar.jsdom.test.tsx @@ -853,6 +853,54 @@ describe( 'Calendar', () => { } ); } ); + describe( 'Events', () => { + it( 'should mark the days that have events and announce how many', () => { + render( + + ); + + expect( getDateButton( tomorrow ) ).toHaveAccessibleName( + /, 2 events$/ + ); + expect( getDateButton( yesterday ) ).toHaveAccessibleName( + /, 1 event$/ + ); + expect( getDateButton( today ) ).not.toHaveAccessibleName( + /event/ + ); + } ); + + it( 'should match events to days in the calendar time zone', () => { + // 20:00 UTC on May 15 is already May 16 (today) in Tokyo. + const timeZone = 'Asia/Tokyo'; + render( + + ); + + expect( + screen.getByRole( 'button', { + name: new RegExp( + `^Today, ${ new Intl.DateTimeFormat( 'en-US', { + weekday: 'long', + year: 'numeric', + month: 'long', + day: 'numeric', + } ).format( new Date( 2025, 4, 16 ) ) }, 1 event$` + ), + } ) + ).toBeVisible(); + } ); + } ); + describe( 'Disabled states', () => { it( 'should support disabling all dates via the `disabled` prop', async () => { const user = setupUserEvent(); diff --git a/packages/ui/src/calendar/test/range-calendar.jsdom.test.tsx b/packages/ui/src/calendar/test/range-calendar.jsdom.test.tsx index 069b5dd017bd2f..2f4f8c10341d73 100644 --- a/packages/ui/src/calendar/test/range-calendar.jsdom.test.tsx +++ b/packages/ui/src/calendar/test/range-calendar.jsdom.test.tsx @@ -1326,6 +1326,24 @@ describe( 'RangeCalendar', () => { } ); } ); + describe( 'Events', () => { + it( 'should mark the days that have events and announce how many', () => { + render( + + ); + + expect( getDateButton( tomorrow ) ).toHaveAccessibleName( + /, 1 event$/ + ); + expect( getDateButton( today ) ).not.toHaveAccessibleName( + /event/ + ); + } ); + } ); + describe( 'Disabled states', () => { it( 'should support disabling all dates via the `disabled` prop', async () => { const user = setupUserEvent(); diff --git a/packages/ui/src/calendar/types.ts b/packages/ui/src/calendar/types.ts index a694ccf664839b..429a946ad0d50c 100644 --- a/packages/ui/src/calendar/types.ts +++ b/packages/ui/src/calendar/types.ts @@ -231,6 +231,14 @@ export interface BaseProps extends Omit< * Specify which days are disabled. Using `true` will disable all dates. */ disabled?: Matcher | Matcher[] | undefined; + /** + * Events to mark on the calendar, such as content already scheduled on a + * day. Each day with at least one event shows a marker, and its accessible + * label includes the number of events. + * + * Days are matched in the calendar's `timeZone`. + */ + events?: { date: Date }[]; /** * Disable the navigation buttons. */ diff --git a/packages/ui/src/calendar/utils/constants.ts b/packages/ui/src/calendar/utils/constants.ts index 1dd439ad649484..31786898a5b132 100644 --- a/packages/ui/src/calendar/utils/constants.ts +++ b/packages/ui/src/calendar/utils/constants.ts @@ -47,12 +47,13 @@ const CLASSNAMES = { }; /* - * Only `preview` carries styles — the shape of the dashed preview border is + * Classes for the custom modifiers. The shape of the dashed preview border is * picked by the `Day` component from the `preview_start` / `preview_end` * modifiers themselves, not from a class. */ export const MODIFIER_CLASSNAMES = { preview: styles.preview, + events: styles.events, }; export const COMMON_PROPS = { diff --git a/packages/ui/src/calendar/utils/use-events.ts b/packages/ui/src/calendar/utils/use-events.ts new file mode 100644 index 00000000000000..67c384403a8904 --- /dev/null +++ b/packages/ui/src/calendar/utils/use-events.ts @@ -0,0 +1,56 @@ +import { isSameDay } from 'date-fns'; +import { useMemo } from '@wordpress/element'; +import { _n, sprintf } from '@wordpress/i18n'; +import type { BaseProps, Modifiers } from '../types'; + +type Labels = NonNullable< BaseProps[ 'labels' ] >; + +/** + * Marks the days that have events and announces how many each one has. + * + * Days are compared with the day as the first argument, so `date-fns` reads + * the event date in the calendar's time zone when the day is a `TZDate`. + * + * @param events The events to mark. + * @param labels The calendar labels to extend. + * @return The `events` matcher, if any, and the extended labels. + */ +export function useEvents( + events: BaseProps[ 'events' ], + labels: Labels +): { eventsMatcher?: ( day: Date ) => boolean; labels: Labels } { + return useMemo( () => { + if ( ! events?.length ) { + return { labels }; + } + + const countEvents = ( day: Date ) => + events.filter( ( event ) => isSameDay( day, event.date ) ).length; + + const withEvents = + ( label?: ( date: Date, modifiers?: Modifiers ) => string ) => + ( date: Date, modifiers?: Modifiers ) => { + const baseLabel = label?.( date, modifiers ) ?? ''; + const count = modifiers?.events ? countEvents( date ) : 0; + if ( ! count ) { + return baseLabel; + } + return sprintf( + // translators: 1: The label of the day (e.g. "Monday, April 29, 2025"). 2: Number of events on that day. + _n( '%1$s, %2$d event', '%1$s, %2$d events', count ), + baseLabel, + count + ); + }; + + return { + eventsMatcher: ( day: Date ) => + events.some( ( event ) => isSameDay( day, event.date ) ), + labels: { + ...labels, + labelDayButton: withEvents( labels.labelDayButton ), + labelGridcell: withEvents( labels.labelGridcell ), + }, + }; + }, [ events, labels ] ); +} diff --git a/test/e2e/specs/editor/various/datepicker.spec.js b/test/e2e/specs/editor/various/datepicker.spec.js index fccf496b115dec..52f487e0ef8b70 100644 --- a/test/e2e/specs/editor/various/datepicker.spec.js +++ b/test/e2e/specs/editor/various/datepicker.spec.js @@ -70,3 +70,66 @@ TIMEZONES.forEach( ( timezone ) => { } ); } ); } ); + +test.describe( 'Datepicker: events', () => { + test.beforeAll( async ( { requestUtils } ) => { + await requestUtils.deleteAllPosts(); + } ); + + test.afterAll( async ( { requestUtils } ) => { + await requestUtils.deleteAllPosts(); + } ); + + test( 'should mark the days that have published or scheduled posts', async ( { + admin, + editor, + page, + requestUtils, + } ) => { + // Dates in the site time zone, which the calendar displays. + const now = new Date(); + const thisMonth = new Date( now.getFullYear(), now.getMonth(), 1 ); + const nextMonth = new Date( now.getFullYear(), now.getMonth() + 1, 1 ); + const toPostDate = ( date ) => + `${ date.getFullYear() }-${ String( date.getMonth() + 1 ).padStart( + 2, + '0' + ) }-01T10:00:00`; + const toDayLabel = ( date ) => + date.toLocaleDateString( 'en-US', { + weekday: 'long', + year: 'numeric', + month: 'long', + day: 'numeric', + } ); + + await requestUtils.createPost( { + title: 'Published', + status: 'publish', + date: toPostDate( thisMonth ), + } ); + await requestUtils.createPost( { + title: 'Scheduled', + status: 'future', + date: toPostDate( nextMonth ), + } ); + + await admin.createNewPost(); + const summary = await openPostSummary( { editor, page } ); + await summary.getByRole( 'button', { name: 'Edit Date' } ).click(); + + await expect( + page.getByRole( 'button', { + // The first day of the month can be today. + name: new RegExp( `${ toDayLabel( thisMonth ) }, 1 event$` ), + } ) + ).toBeVisible(); + + await page.getByRole( 'button', { name: 'Next month' } ).click(); + await expect( + page.getByRole( 'button', { + name: new RegExp( `${ toDayLabel( nextMonth ) }, 1 event$` ), + } ) + ).toBeVisible(); + } ); +} );