/** * Fork of hook from `@wordpress/server-side-render`. * * Additional features: * - `placeholder` and `enabled` props * - includes post ID * - returns string */ import * as React from 'react' import {__, _x, sprintf} from '@wordpress/i18n' import { useEffect, useRef, useState, useMemo, } from '@wordpress/element' import { debounce, } from '@wordpress/compose' import { useSelect, } from '@wordpress/data' import { store as editorStore, } from '@wordpress/editor' import apiFetch from '@wordpress/api-fetch' import { addQueryArgs, } from '@wordpress/url' import { sanitizeBlockAttributes, // @ts-expect-error } from '@wordpress/blocks' import {debugError} from '@ska/utils' const EMPTY_OBJECT: Record = {} export function rendererPath(block: string, attributes: Record | null = null, urlQueryArgs: Record = EMPTY_OBJECT): string { return addQueryArgs(`/wp/v2/block-renderer/${block}`, { context: 'edit', ...(attributes !== null ? {attributes} : EMPTY_OBJECT), ...urlQueryArgs, }) } export function removeBlockSupportAttributes(attributes: Record & {style?: Record}): Record { const { backgroundColor, borderColor, fontFamily, fontSize, gradient, textColor, className, ...restAttributes } = attributes const { border, color, elements, shadow, spacing, typography, ...restStyles } = attributes?.style || EMPTY_OBJECT return { ...restAttributes, style: restStyles, } } /** * Server-side render response object. */ export interface ServerSideRenderResponse { /** The current request status: 'idle', 'loading', 'success', or 'error'. */ status: 'idle' | 'loading' | 'success' | 'error' /** The rendered block content (available when status is 'success'). */ content?: string /** The error message (available when status is 'error'). */ error?: string } /** * Configuration object for the useServerSideRender hook. */ export interface UseServerSideRenderArgs { /** The block attributes to be sent to the server for rendering. */ attributes: Record /** The identifier of the block to be server-side rendered. Example: 'core/archives'. */ block: string /** Whether to remove block support attributes before sending. */ skipBlockSupportAttributes?: boolean /** The HTTP method to use ('GET' or 'POST'). Default is 'GET'. */ httpMethod?: 'GET' | 'POST' /** Additional query arguments to append to the request URL. */ urlQueryArgs?: Record /** Placeholder content. */ placeholder?: string /** Whether to fetch data. */ enabled?: boolean } const POST_REQUEST_HEADERS = {'Content-Type': 'application/json'} const GET_REQUEST_HEADERS = {} /** * A hook for server-side rendering a preview of dynamic blocks to display in the editor. * * Handles fetching server-rendered previews for blocks, managing loading states, * and automatically debouncing requests to prevent excessive API calls. It supports both * GET and POST requests, with POST requests used for larger attribute payloads. * * @param args The hook configuration object. * @return Rendered string or placeholder string. */ export function useServerSideRender(args: UseServerSideRenderArgs): string { const { attributes, block, skipBlockSupportAttributes = false, httpMethod = 'GET', urlQueryArgs: originalUrlQueryArgs, placeholder = '', enabled = true, } = args const [response, setResponse] = useState(null) const shouldDebounceRef = useRef(false) const { currentPostId, } = useSelect((select) => { const { getCurrentPostId, } = select(editorStore) return { currentPostId: getCurrentPostId(), } }, []) const urlQueryArgs = useMemo(() => { if(!currentPostId || typeof currentPostId !== 'number') { return originalUrlQueryArgs } return { post_id: currentPostId, ...originalUrlQueryArgs, } }, [currentPostId, originalUrlQueryArgs]) let sanitizedAttributes: Record | null = attributes && sanitizeBlockAttributes(block, attributes) if(skipBlockSupportAttributes && sanitizedAttributes) { sanitizedAttributes = removeBlockSupportAttributes(sanitizedAttributes) } // If httpMethod is 'POST', send the attributes in the request body instead of the URL. // This allows sending a larger attributes object than in a GET request, where the attributes are in the URL. const isPostRequest = httpMethod === 'POST' const urlAttributes = isPostRequest ? null : sanitizedAttributes const path = rendererPath(block, urlAttributes, urlQueryArgs) const body = isPostRequest ? JSON.stringify({attributes: sanitizedAttributes ?? null}) : undefined useEffect(() => { if(!enabled) { return } const controller = new AbortController() const debouncedFetch = debounce(function() { apiFetch<{rendered: string}>({ path, method: isPostRequest ? 'POST' : 'GET', body, headers: isPostRequest ? POST_REQUEST_HEADERS : GET_REQUEST_HEADERS, signal: controller.signal, }) .then(response => { setResponse(response ? response.rendered : placeholder) }) .catch((error: unknown) => { debugError(error) // // The request was aborted, do not update the response. // if(error instanceof Error && error.name === 'AbortError') { // return // } // setResponse({ // status: 'error', // error: error instanceof Error ? error.message : String(error), // }) }) .finally(() => { // Debounce requests after first fetch. shouldDebounceRef.current = true }) }, shouldDebounceRef.current ? 500 : 0) debouncedFetch() return () => { controller.abort() debouncedFetch.cancel() } }, [path, isPostRequest, body, placeholder, enabled]) if(!enabled) { return placeholder } // if(isLoading) { // if(placeholder) { // return placeholder // } // return showLoader ? 'Loading...' : '' // } // if(typeof response === 'string' && !response) { // return __('Block rendered as empty.') // } if(response) { return response } if(typeof response === 'string') { return __('Block rendered as empty.') } return placeholder }