-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
swap-template-button.js
80 lines (77 loc) · 2.22 KB
/
swap-template-button.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
/**
* WordPress dependencies
*/
import { useMemo, useState } from '@wordpress/element';
import { decodeEntities } from '@wordpress/html-entities';
import { __experimentalBlockPatternsList as BlockPatternsList } from '@wordpress/block-editor';
import { MenuItem, Modal } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { useDispatch } from '@wordpress/data';
import { store as coreStore } from '@wordpress/core-data';
import { parse } from '@wordpress/blocks';
/**
* Internal dependencies
*/
import { useAvailableTemplates, useEditedPostContext } from './hooks';
export default function SwapTemplateButton( { onClick } ) {
const [ showModal, setShowModal ] = useState( false );
const { postType, postId } = useEditedPostContext();
const availableTemplates = useAvailableTemplates( postType );
const { editEntityRecord } = useDispatch( coreStore );
if ( ! availableTemplates?.length ) {
return null;
}
const onTemplateSelect = async ( template ) => {
editEntityRecord(
'postType',
postType,
postId,
{ template: template.name },
{ undoIgnore: true }
);
setShowModal( false ); // Close the template suggestions modal first.
onClick();
};
return (
<>
<MenuItem onClick={ () => setShowModal( true ) }>
{ __( 'Swap template' ) }
</MenuItem>
{ showModal && (
<Modal
title={ __( 'Choose a template' ) }
onRequestClose={ () => setShowModal( false ) }
overlayClassName="editor-post-template__swap-template-modal"
isFullScreen
>
<div className="editor-post-template__swap-template-modal-content">
<TemplatesList
postType={ postType }
onSelect={ onTemplateSelect }
/>
</div>
</Modal>
) }
</>
);
}
function TemplatesList( { postType, onSelect } ) {
const availableTemplates = useAvailableTemplates( postType );
const templatesAsPatterns = useMemo(
() =>
availableTemplates.map( ( template ) => ( {
name: template.slug,
blocks: parse( template.content.raw ),
title: decodeEntities( template.title.rendered ),
id: template.id,
} ) ),
[ availableTemplates ]
);
return (
<BlockPatternsList
label={ __( 'Templates' ) }
blockPatterns={ templatesAsPatterns }
onClickPattern={ onSelect }
/>
);
}