import type { CSSProperties } from 'react'; import { __, sprintf } from '@wordpress/i18n'; import { InspectorControls, useBlockProps } from '@wordpress/block-editor'; import { ToggleControl, TextControl, CheckboxControl as WCCheckboxControl, __experimentalToolsPanel as ToolsPanel, __experimentalToolsPanelItem as ToolsPanelItem, Spinner as WCSpinner, } from '@wordpress/components'; import { useSelect } from '@wordpress/data'; import { store as coreStore } from '@wordpress/core-data'; import type { Post } from '@wordpress/core-data'; import { useEffect, useRef, useState } from '@wordpress/element'; import { useServerSideRender } from '@wordpress/server-side-render'; import { useDisabled } from '@wordpress/compose'; import { canUserEditPostContext, useToolsPanelDropdownMenuProps, } from '../utils/hooks'; import HtmlRenderer from '../utils/html-renderer'; import type { BreadcrumbsEditProps } from './types'; const separatorDefaultValue = '/'; export default function BreadcrumbEdit( { attributes, setAttributes, name, context: { postId, postType, templateSlug }, }: BreadcrumbsEditProps ) { const { separator, showHomeItem, showCurrentItem, prefersTaxonomy, showOnHomePage, } = attributes; const { post, canEditPost, isPostTypeHierarchical, postTypeHasTaxonomies, hasTermsAssigned, isLoading, } = useSelect( ( select ) => { if ( ! postType ) { return {}; } const _post = select( coreStore ).getEntityRecord< Post & Record< string, unknown > >( 'postType', postType, postId ); const _canReadPost = postId ? select( coreStore ).canUser( 'read', { kind: 'postType', name: postType, id: postId, } ) : undefined; const _canEditPost = canUserEditPostContext( select, postType, postId ); const postTypeObject = select( coreStore ).getPostType( postType ); const _postTypeHasTaxonomies = postTypeObject && postTypeObject.taxonomies.length; let taxonomies; if ( _postTypeHasTaxonomies ) { taxonomies = select( coreStore ).getTaxonomies( { type: postType, per_page: -1, } ); } return { post: _post, canEditPost: _canEditPost, isPostTypeHierarchical: postTypeObject?.hierarchical, postTypeHasTaxonomies: _postTypeHasTaxonomies, hasTermsAssigned: _post && ( taxonomies || [] ) .filter( ( { visibility } ) => visibility?.publicly_queryable ) .some( ( taxonomy ) => { return !! ( _post[ taxonomy.rest_base ] as unknown[] | undefined )?.length; } ), isLoading: // Wait for the post record only while it can still be // expected. The record is requested with `context=edit`, // so it never arrives when the user can't edit the post // (`_canEditPost === false`), nor when the post isn't // readable under `postType` at all // (`_canReadPost === false`) — the placeholder or the // server-side render is shown instead. ( postId && _canEditPost !== false && _canReadPost !== false && ! _post ) || ! postTypeObject || ( _postTypeHasTaxonomies && ! taxonomies ), }; }, [ postType, postId ] ); /** * Counter used to cache-bust `useServerSideRender`. * * This is a catch-all signal to re-render the block when a post's title, * parent ID, or terms change. * * This is fundamentally imperfect, because there are other entities which * could change in the meantime (the titles of ancestor posts, or the * labels of taxonomy terms), hence the choice to re-render systematically * upon saving. */ const [ invalidationKey, setInvalidationKey ] = useState( 0 ); useEffect( () => { setInvalidationKey( ( c ) => c + 1 ); }, [ post ] ); const dropdownMenuProps = useToolsPanelDropdownMenuProps(); const { content, status, error } = useServerSideRender( { attributes, skipBlockSupportAttributes: true, block: name, urlQueryArgs: { // The block-renderer endpoint requires `edit_post` permissions // for the post referenced by `post_id`, and the `postId` block // context can reference a post the current user can't edit (e.g. // another author's post in a query-like block), which failed with // a 403 error. Withhold `post_id` only when the post is confirmed // non-editable; when that can't be determined (e.g. `postId` and // `postType` coming from different providers don't designate a // readable post), forward it and let the server decide, as before. post_id: canEditPost === false ? undefined : postId, invalidationKey, }, } ); const prevContentRef = useRef( '' ); useEffect( () => { if ( status === 'success' ) { prevContentRef.current = content!; } }, [ content, status ] ); const [ showLoader, setShowLoader ] = useState( false ); useEffect( () => { if ( status !== 'loading' ) { return; } const timeout = setTimeout( () => { setShowLoader( true ); }, 400 ); return () => { clearTimeout( timeout ); setShowLoader( false ); }; }, [ status ] ); const disabledRef = useDisabled(); const blockProps = useBlockProps( { ref: disabledRef } ); if ( isLoading ) { return (
); } // Try to determine breadcrumb type for more accurate previews. let _showTerms; // Some non-hierarchical post types (e.g., attachments) can have parents. // Use hierarchical breadcrumbs if a parent exists, otherwise use taxonomy breadcrumbs. if ( ! isPostTypeHierarchical && ! post?.parent ) { _showTerms = true; } else if ( ! postTypeHasTaxonomies ) { // Hierarchical post type without taxonomies can only use ancestors. _showTerms = false; } else { // For hierarchical post types with taxonomies, use the attribute. _showTerms = prefersTaxonomy; } let placeholder = null; // This is fragile because this block is server side rendered and we'll have to // update the placeholder html if the server side rendering output changes. const showPlaceholder = ! postId || ! postType || // Without `post_id`, the server can't render the real breadcrumbs, // so show the placeholder for posts the user can't edit. canEditPost === false || // When `templateSlug` is set only show placeholder if the post type is not. // This is needed because when we are showing the template in post editor we // want to show the real breadcrumbs if we have the post type. ( templateSlug && ! postType ) || ( ! _showTerms && ! isPostTypeHierarchical ) || ( _showTerms && ! hasTermsAssigned ); if ( showPlaceholder ) { const placeholderItems = []; if ( showHomeItem ) { placeholderItems.push( __( 'Home' ) ); } if ( templateSlug && ! postId ) { placeholderItems.push( __( 'Page' ) ); } else if ( _showTerms ) { placeholderItems.push( __( 'Category' ) ); } else { placeholderItems.push( __( 'Ancestor' ), __( 'Parent' ) ); } placeholder = ( ); } return ( <> { setAttributes( { separator: separatorDefaultValue, showHomeItem: true, showCurrentItem: true, } ); } } dropdownMenuProps={ dropdownMenuProps } > ! showHomeItem } onDeselect={ () => setAttributes( { showHomeItem: true, } ) } > setAttributes( { showHomeItem: value } ) } checked={ showHomeItem } /> ! showCurrentItem } onDeselect={ () => setAttributes( { showCurrentItem: true, } ) } > setAttributes( { showCurrentItem: value } ) } checked={ showCurrentItem } /> separator !== separatorDefaultValue } onDeselect={ () => setAttributes( { separator: separatorDefaultValue, } ) } > setAttributes( { separator: value } ) } onBlur={ () => { if ( ! separator ) { setAttributes( { separator: separatorDefaultValue, } ); } } } /> setAttributes( { showOnHomePage: value } ) } help={ __( 'If this Breadcrumbs block appears in a template or template part that’s shown on the homepage, enable this option to display the breadcrumb trail. Otherwise, this setting has no effect.' ) } /> setAttributes( { prefersTaxonomy: value } ) } help={ __( 'The exact type of breadcrumbs shown will vary automatically depending on the page in which this block is displayed. In the specific case of a hierarchical post type with taxonomies, the breadcrumbs can either reflect its post hierarchy (default) or the hierarchy of its assigned taxonomy terms.' ) } /> { status === 'loading' && ! showPlaceholder && ( prevContentRef.current ? ( ) : (
) ) } { status === 'error' && (

{ sprintf( /* translators: %s: error message returned when rendering the block. */ __( 'Error: %s' ), error! ) }

) } { showPlaceholder && placeholder } { ! showPlaceholder && status === 'success' && ( ) } ); }