-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
edit.js
103 lines (94 loc) · 2.68 KB
/
edit.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
* External dependencies
*/
import memoize from 'memize';
/**
* WordPress dependencies
*/
import { calendar as icon } from '@wordpress/icons';
import { Disabled, Placeholder, Spinner } from '@wordpress/components';
import { useSelect } from '@wordpress/data';
import ServerSideRender from '@wordpress/server-side-render';
import { useBlockProps } from '@wordpress/block-editor';
import { store as coreStore } from '@wordpress/core-data';
import { __ } from '@wordpress/i18n';
/**
* Returns the year and month of a specified date.
*
* @see `WP_REST_Posts_Controller::prepare_date_response()`.
*
* @param {string} date Date in `ISO8601/RFC3339` format.
* @return {Object} Year and date of the specified date.
*/
const getYearMonth = memoize( ( date ) => {
if ( ! date ) {
return {};
}
const dateObj = new Date( date );
return {
year: dateObj.getFullYear(),
month: dateObj.getMonth() + 1,
};
} );
export default function CalendarEdit( { attributes } ) {
const blockProps = useBlockProps();
const { date, hasPosts, hasPostsResolved } = useSelect( ( select ) => {
const { getEntityRecords, hasFinishedResolution } = select( coreStore );
const singlePublishedPostQuery = {
status: 'publish',
per_page: 1,
};
const posts = getEntityRecords(
'postType',
'post',
singlePublishedPostQuery
);
const postsResolved = hasFinishedResolution( 'getEntityRecords', [
'postType',
'post',
singlePublishedPostQuery,
] );
let _date;
// FIXME: @wordpress/block-library should not depend on @wordpress/editor.
// Blocks can be loaded into a *non-post* block editor.
// eslint-disable-next-line @wordpress/data-no-store-string-literals
const editorSelectors = select( 'core/editor' );
if ( editorSelectors ) {
const postType = editorSelectors.getEditedPostAttribute( 'type' );
// Dates are used to overwrite year and month used on the calendar.
// This overwrite should only happen for 'post' post types.
// For other post types the calendar always displays the current month.
if ( postType === 'post' ) {
_date = editorSelectors.getEditedPostAttribute( 'date' );
}
}
return {
date: _date,
hasPostsResolved: postsResolved,
hasPosts: postsResolved && posts?.length === 1,
};
}, [] );
if ( ! hasPosts ) {
return (
<div { ...blockProps }>
<Placeholder icon={ icon } label={ __( 'Calendar' ) }>
{ ! hasPostsResolved ? (
<Spinner />
) : (
__( 'No published posts found.' )
) }
</Placeholder>
</div>
);
}
return (
<div { ...blockProps }>
<Disabled>
<ServerSideRender
block="core/calendar"
attributes={ { ...attributes, ...getYearMonth( date ) } }
/>
</Disabled>
</div>
);
}