From bf754e79eae4c9eeef69675ad77fe471430394e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fabian=20Ka=CC=88gy?= Date: Fri, 26 Jan 2024 13:24:23 +0100 Subject: [PATCH] add a method to only preview a template part for users that can only view but not edit them --- .../src/template-part/edit/index.js | 62 ++++++++++++++++++- 1 file changed, 61 insertions(+), 1 deletion(-) diff --git a/packages/block-library/src/template-part/edit/index.js b/packages/block-library/src/template-part/edit/index.js index 72fc06338e7807..1f64067313281d 100644 --- a/packages/block-library/src/template-part/edit/index.js +++ b/packages/block-library/src/template-part/edit/index.js @@ -7,13 +7,15 @@ import { useBlockProps, Warning, store as blockEditorStore, + useInnerBlocksProps, + useSettings, RecursionProvider, useHasRecursion, InspectorControls, } from '@wordpress/block-editor'; import { Spinner, Modal, MenuItem } from '@wordpress/components'; import { __, sprintf } from '@wordpress/i18n'; -import { store as coreStore } from '@wordpress/core-data'; +import { store as coreStore, useEntityBlockEditor } from '@wordpress/core-data'; import { useState } from '@wordpress/element'; /** @@ -67,11 +69,52 @@ function ReplaceButton( { ); } +function NonEditableTemplatePartPreview( { + postId: id, + layout, + tagName: TagName, + blockProps, +} ) { + const themeSupportsLayout = useSelect( ( select ) => { + const { getSettings } = select( blockEditorStore ); + return getSettings()?.supportsLayout; + }, [] ); + const [ defaultLayout ] = useSettings( 'layout' ); + const usedLayout = layout?.inherit ? defaultLayout || {} : layout; + + const [ blocks ] = useEntityBlockEditor( 'postType', 'wp_template_part', { + id, + context: 'view', + } ); + + const innerBlocksProps = useInnerBlocksProps( blockProps, { + value: blocks, + onChange: () => {}, + onInput: () => {}, + renderAppender: undefined, + layout: themeSupportsLayout ? usedLayout : undefined, + } ); + + return ; +} + export default function TemplatePartEdit( { attributes, setAttributes, clientId, } ) { + const { canEditTemplatePart, canViewTemplatePart } = useSelect( + ( select ) => ( { + canEditTemplatePart: + select( coreStore ).canUser( 'create', 'template-parts' ) ?? + false, + canViewTemplatePart: + select( coreStore ).canUser( 'read', 'template-parts' ) ?? + false, + } ), + [] + ); + const currentTheme = useSelect( ( select ) => select( coreStore ).getCurrentTheme()?.stylesheet, [] @@ -126,6 +169,23 @@ export default function TemplatePartEdit( { const isEntityAvailable = ! isPlaceholder && ! isMissing && isResolved; const TagName = tagName || areaObject.tagName; + if ( ! canEditTemplatePart && canViewTemplatePart ) { + return ( + + 0 } + layout={ layout } + /> + + ); + } + // We don't want to render a missing state if we have any inner blocks. // A new template part is automatically created if we have any inner blocks but no entity. if (