Skip to content
Closed
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
27 changes: 27 additions & 0 deletions packages/core-fields/src/post_type_supports/date/field.tsx
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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 ) } ) );
},
},
};
2 changes: 2 additions & 0 deletions packages/core-fields/src/post_type_supports/date/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
46 changes: 45 additions & 1 deletion packages/core-fields/src/test/post-type-supports.jsdom.test.ts
Original file line number Diff line number Diff line change
@@ -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( [
Expand Down Expand Up @@ -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(
Expand Down
1 change: 1 addition & 0 deletions packages/dataviews/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)).
Expand Down
18 changes: 18 additions & 0 deletions packages/dataviews/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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 } );
Expand Down Expand Up @@ -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 );
Expand Down Expand Up @@ -210,6 +217,7 @@ function CalendarDateTimeControl< Item >( {
dir={ isRTL() ? 'rtl' : 'ltr' }
weekStartsOn={ weekStartsOn }
disabled={ disabled || disabledMatchers }
events={ events }
/>
) }
</Stack>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
<DateTime
data={ item }
field={ field }
onChange={ noop }
config={ { getEvents } }
/>
);

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(
<DateTime
data={ { published: '2024-03-15T10:30:00.000Z' } }
field={ field }
onChange={ noop }
config={ { compact: true, getEvents } }
/>
);

expect( getEvents ).not.toHaveBeenCalled();
} );
} );
} );
Original file line number Diff line number Diff line change
@@ -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;
}
49 changes: 45 additions & 4 deletions packages/dataviews/src/types/field-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ export type EditConfigText = {
/**
* Edit configuration for datetime controls.
*/
export type EditConfigDatetime = {
export type EditConfigDatetime< Item = any > = {
/**
* The control to render.
*/
Expand All @@ -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').
*/
Expand All @@ -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;

/**
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 >;
};
};

Expand Down
Loading
Loading