-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
Copy pathindex.tsx
273 lines (258 loc) · 7.69 KB
/
index.tsx
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/**
* WordPress dependencies
*/
import {
Icon,
BaseControl,
TextControl,
Flex,
FlexItem,
FlexBlock,
Button,
Modal,
__experimentalRadioGroup as RadioGroup,
__experimentalRadio as Radio,
__experimentalHStack as HStack,
__experimentalVStack as VStack,
} from '@wordpress/components';
import { useInstanceId } from '@wordpress/compose';
import { store as coreStore } from '@wordpress/core-data';
import { useDispatch, useSelect } from '@wordpress/data';
import { useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import {
check,
footer as footerIcon,
header as headerIcon,
sidebar as sidebarIcon,
symbolFilled as symbolFilledIcon,
} from '@wordpress/icons';
import { store as noticesStore } from '@wordpress/notices';
// @ts-expect-error serialize is not typed
import { serialize } from '@wordpress/blocks';
/**
* Internal dependencies
*/
import {
getCleanTemplatePartSlug,
getUniqueTemplatePartTitle,
useExistingTemplateParts,
} from './utils';
type CreateTemplatePartModalContentsProps = {
defaultArea?: string;
blocks: any[];
confirmLabel?: string;
closeModal: () => void;
onCreate: ( templatePart: any ) => void;
onError?: () => void;
defaultTitle?: string;
};
/**
* A React component that renders a modal for creating a template part. The modal displays a title and the contents for creating the template part.
* This component should not live in this package, it should be moved to a dedicated package responsible for managing template.
* @param {Object} props The component props.
* @param props.modalTitle
*/
export default function CreateTemplatePartModal( {
modalTitle,
...restProps
}: {
modalTitle: string;
} & CreateTemplatePartModalContentsProps ) {
const defaultModalTitle = useSelect(
( select ) =>
// @ts-expect-error getPostType is not typed with 'wp_template_part' as argument.
select( coreStore ).getPostType( 'wp_template_part' )?.labels
?.add_new_item,
[]
);
return (
<Modal
title={ modalTitle || defaultModalTitle }
onRequestClose={ restProps.closeModal }
overlayClassName="fields-create-template-part-modal"
focusOnMount="firstContentElement"
size="medium"
>
<CreateTemplatePartModalContents { ...restProps } />
</Modal>
);
}
const getTemplatePartIcon = ( iconName: string ) => {
if ( 'header' === iconName ) {
return headerIcon;
} else if ( 'footer' === iconName ) {
return footerIcon;
} else if ( 'sidebar' === iconName ) {
return sidebarIcon;
}
return symbolFilledIcon;
};
/**
* A React component that renders the content of a model for creating a template part.
* This component should not live in this package; it should be moved to a dedicated package responsible for managing template.
*
* @param {Object} props - The component props.
* @param {string} [props.defaultArea=uncategorized] - The default area for the template part.
* @param {Array} [props.blocks=[]] - The blocks to be included in the template part.
* @param {string} [props.confirmLabel='Add'] - The label for the confirm button.
* @param {Function} props.closeModal - Function to close the modal.
* @param {Function} props.onCreate - Function to call when the template part is successfully created.
* @param {Function} [props.onError] - Function to call when there is an error creating the template part.
* @param {string} [props.defaultTitle=''] - The default title for the template part.
*/
export function CreateTemplatePartModalContents( {
defaultArea = 'uncategorized',
blocks = [],
confirmLabel = __( 'Add' ),
closeModal,
onCreate,
onError,
defaultTitle = '',
}: CreateTemplatePartModalContentsProps ) {
const { createErrorNotice } = useDispatch( noticesStore );
const { saveEntityRecord } = useDispatch( coreStore );
const existingTemplateParts = useExistingTemplateParts();
const [ title, setTitle ] = useState( defaultTitle );
const [ area, setArea ] = useState( defaultArea );
const [ isSubmitting, setIsSubmitting ] = useState( false );
const instanceId = useInstanceId( CreateTemplatePartModal );
const defaultTemplatePartAreas = useSelect( ( select ) => {
const areas =
// @ts-expect-error getEntityRecord is not typed with unstableBase as argument.
select( coreStore ).getEntityRecord< {
default_template_part_areas: Array< {
area: string;
label: string;
icon: string;
description: string;
} >;
} >( 'root', '__unstableBase' )?.default_template_part_areas || [];
return areas.map( ( item ) => {
return { ...item, icon: getTemplatePartIcon( item.icon ) };
} );
}, [] );
async function createTemplatePart() {
if ( ! title || isSubmitting ) {
return;
}
try {
setIsSubmitting( true );
const uniqueTitle = getUniqueTemplatePartTitle(
title,
existingTemplateParts
);
const cleanSlug = getCleanTemplatePartSlug( uniqueTitle );
const templatePart = await saveEntityRecord(
'postType',
'wp_template_part',
{
slug: cleanSlug,
title: uniqueTitle,
content: serialize( blocks ),
area,
},
{ throwOnError: true }
);
await onCreate( templatePart );
// TODO: Add a success notice?
} catch ( error ) {
const errorMessage =
error instanceof Error &&
'code' in error &&
error.message &&
error.code !== 'unknown_error'
? error.message
: __(
'An error occurred while creating the template part.'
);
createErrorNotice( errorMessage, { type: 'snackbar' } );
onError?.();
} finally {
setIsSubmitting( false );
}
}
return (
<form
onSubmit={ async ( event ) => {
event.preventDefault();
await createTemplatePart();
} }
>
<VStack spacing="4">
<TextControl
__next40pxDefaultSize
__nextHasNoMarginBottom
label={ __( 'Name' ) }
value={ title }
onChange={ setTitle }
required
/>
<BaseControl
__nextHasNoMarginBottom
label={ __( 'Area' ) }
id={ `fields-create-template-part-modal__area-selection-${ instanceId }` }
className="fields-create-template-part-modal__area-base-control"
>
<RadioGroup
label={ __( 'Area' ) }
className="fields-create-template-part-modal__area-radio-group"
id={ `fields-create-template-part-modal__area-selection-${ instanceId }` }
onChange={ ( value ) =>
value && typeof value === 'string'
? setArea( value )
: () => void 0
}
checked={ area }
>
{ defaultTemplatePartAreas.map(
( { icon, label, area: value, description } ) => (
<Radio
__next40pxDefaultSize
key={ label }
value={ value }
className="fields-create-template-part-modal__area-radio"
>
<Flex align="start" justify="start">
<FlexItem>
<Icon icon={ icon } />
</FlexItem>
<FlexBlock className="fields-create-template-part-modal__option-label">
{ label }
<div>{ description }</div>
</FlexBlock>
<FlexItem className="fields-create-template-part-modal__checkbox">
{ area === value && (
<Icon icon={ check } />
) }
</FlexItem>
</Flex>
</Radio>
)
) }
</RadioGroup>
</BaseControl>
<HStack justify="right">
<Button
__next40pxDefaultSize
variant="tertiary"
onClick={ () => {
closeModal();
} }
>
{ __( 'Cancel' ) }
</Button>
<Button
__next40pxDefaultSize
variant="primary"
type="submit"
aria-disabled={ ! title || isSubmitting }
isBusy={ isSubmitting }
>
{ confirmLabel }
</Button>
</HStack>
</VStack>
</form>
);
}