Skip to content
3 changes: 1 addition & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

47 changes: 47 additions & 0 deletions packages/e2e-tests/plugins/server-side-rendered-block.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php
/**
* Plugin Name: Gutenberg Test Server-Side Rendered Block
* Plugin URI: https://github.com/WordPress/gutenberg
* Author: Gutenberg Team
*
* @package gutenberg-test-server-side-rendered-block
*/

add_action(
'init',
static function () {
wp_register_script(
'server-side-rendered-block',
plugins_url( 'server-side-rendered-block/editor.js', __FILE__ ),
array( 'wp-blocks', 'wp-element', 'wp-editor', 'wp-components', 'wp-server-side-render' ),
filemtime( plugin_dir_path( __FILE__ ) . 'server-side-rendered-block/editor.js' ),
true
);

register_block_type(
'test/server-side-rendered-block',
array(
'attributes' => array(
'count' => array(
'type' => 'number',
'default' => 0,
),
),
'render_callback' => static function ( $attributes ) {
$count = isset( $attributes['count'] ) ? absint( $attributes['count'] ) : 0;

// Simulate an empty response when count is over maximum value = 10.
if ( $count > 10 ) {
return '';
}

return sprintf(
'<p>Coffee count: %d</p>',
$count
);
},
'editor_script_handles' => array( 'server-side-rendered-block' ),
)
);
}
);
49 changes: 49 additions & 0 deletions packages/e2e-tests/plugins/server-side-rendered-block/editor.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
( function () {
const { createElement: el, Fragment } = wp.element;
const { registerBlockType } = wp.blocks;
const { InspectorControls, useBlockProps } = wp.blockEditor;
const ServerSideRender = wp.serverSideRender;
const { PanelBody, __experimentalNumberControl: NumberControl } =
wp.components;

registerBlockType( 'test/server-side-rendered-block', {
apiVersion: 3,
title: 'Test Server-Side Render',
icon: 'coffee',
category: 'text',

edit: function Edit( { attributes, setAttributes } ) {
const blockProps = useBlockProps();
return el(
Fragment,
null,
el(
InspectorControls,
{},
el(
PanelBody,
null,
el( NumberControl, {
label: 'Count',
value: attributes.count || 0,
min: 0,
max: 10,
__next40pxDefaultSize: true,
onChange: ( value ) => {
setAttributes( { count: value } );
},
} )
)
),
el(
'div',
blockProps,
el( ServerSideRender, {
block: 'test/server-side-rendered-block',
attributes,
} )
)
);
},
} );
} )();
158 changes: 73 additions & 85 deletions packages/server-side-render/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,122 +20,110 @@ npm install @wordpress/server-side-render --save

_This package assumes that your code will run in an **ES2015+** environment. If you're using an environment that has limited or no support for such language features and APIs, you should include [the polyfill shipped in `@wordpress/babel-preset-default`](https://github.com/WordPress/gutenberg/tree/HEAD/packages/babel-preset-default#polyfill) in your code._

## Usage
## API

The props accepted by the component are described below.
<!-- START TOKEN(Autogenerated API docs) -->

## Props
### default

### attributes
> **Deprecated** Use `ServerSideRender` non-default export instead.

An object containing the attributes of the block to be server-side rendered.
E.g: `{ displayAsDropdown: true }`, `{ showHierarchy: true }`, etc...
A compatibility layer for the `ServerSideRender` component when used with `wp` global namespace.

- Type: `Object`
- Required: No
_Usage_

### block

The identifier of the block to be server-side rendered.
Examples: "core/archives", "core/latest-comments", "core/rss", etc...

- Type: `String`
- Required: Yes

### className

A class added to the DOM element that wraps the server side rendered block.
Examples: "my-custom-server-side-rendered".

- Type: `String`
- Required: No

### httpMethod
```js
import ServerSideRender from '@wordpress/server-side-render';
```

The HTTP request method to use is either `GET` or `POST`, with `GET` as the default. When using `POST`, attributes are sent in the request body rather than the URL, allowing for a larger attributes object.
### ServerSideRender

- Type: `String`
- Required: No
- Default: 'GET'
A component that renders server-side content for blocks.

### skipBlockSupportAttributes
Note: URL query will include the current post ID when applicable. This is useful for blocks that depend on the context of the current post for rendering.

Remove attributes and style properties applied by the block supports. This prevents duplication of styles in the block wrapper and the `ServerSideRender` components. Even if certain features skip serialization to HTML markup by `__experimentalSkipSerialization`, all attributes and style properties are removed.
_Usage_

- Type: `Boolean`
- Required: No
- Default: false
```jsx
import { ServerSideRender } from '@wordpress/server-side-render';
// Legacy import for WordPress 6.8 and earlier
// import { default as ServerSideRender } from '@wordpress/server-side-render';

function Example() {
return (
<ServerSideRender
block="core/archives"
attributes={ { showPostCounts: true } }
urlQueryArgs={ { customArg: 'value' } }
className="custom-class"
/>
);
}
```

### urlQueryArgs
_Parameters_

Query arguments to apply to the request URL.
E.g: `{ post_id: 12 }`.
- _props_ `Object`: Component props.
- _props.block_ `string`: The identifier of the block to be serverside rendered.
- _props.attributes_ `Object`: The block attributes to be sent to the server for rendering.
- _props.className_ `[string]`: Additional classes to apply to the wrapper element.
- _props.httpMethod_ `[string]`: The HTTP method to use ('GET' or 'POST'). Default is 'GET'
- _props.urlQueryArgs_ `[Object]`: Additional query arguments to append to the request URL.
- _props.skipBlockSupportAttributes_ `[boolean]`: Whether to remove block support attributes before sending.
- _props.EmptyResponsePlaceholder_ `[Function]`: Component rendered when the API response is empty.
- _props.ErrorResponsePlaceholder_ `[Function]`: Component rendered when the API response is an error.
- _props.LoadingResponsePlaceholder_ `[Function]`: Component rendered while the API request is loading.

- Type: `Object`
- Required: No
_Returns_

### EmptyResponsePlaceholder
- `JSX.Element`: The rendered server-side content.

The component is rendered when the API response is empty. The component will receive the value of the API response, and all props passed into `ServerSideRenderer`.
### useServerSideRender

- Type: `Component`
- Required: No
A hook for server-side rendering a preview of dynamic blocks to display in the editor.

### ErrorResponsePlaceholder
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.

The component is rendered when the API response is an error. The component will receive the value of the API response, and all props passed into `ServerSideRenderer`.
_Usage_

- Type: `Component`
- Required: No
Basic usage:

### LoadingResponsePlaceholder
```jsx
import { RawHTML } from '@wordpress/element';
import { useServerSideRender } from '@wordpress/server-side-render';

The component is rendered while the API request is being processed (loading state). The component will receive the value of the API response, and all props passed into `ServerSideRenderer`.
function MyServerSideRender( { attributes, block } ) {
const { content, status, error } = useServerSideRender( {
attributes,
block,
} );

- Type: `Component`
- Required: No
if ( status === 'loading' ) {
return <div>Loading...</div>;
}

#### Example usage
if ( status === 'error' ) {
return <div>Error: { error }</div>;
}

```jsx
const MyServerSideRender = () => (
<ServerSideRender LoadingResponsePlaceholder={ MyAmazingPlaceholder } />
);
return <RawHTML>{ content }</RawHTML>;
}
```

## Usage

Render core/archives preview.
_Parameters_

```jsx
import ServerSideRender from '@wordpress/server-side-render';
- _args_ `Object`: The hook configuration object.
- _args.attributes_ `Object`: The block attributes to be sent to the server for rendering.
- _args.block_ `string`: The identifier of the block to be serverside rendered. Example: 'core/archives'.
- _args.skipBlockSupportAttributes_ `[boolean]`: Whether to remove block support attributes before sending.
- _args.httpMethod_ `[string]`: The HTTP method to use ('GET' or 'POST'). Default is 'GET'.
- _args.urlQueryArgs_ `[Object]`: Additional query arguments to append to the request URL.

const MyServerSideRender = () => (
<ServerSideRender
block="core/archives"
attributes={ {
showPostCounts: true,
displayAsDropdown: false,
} }
/>
);
```
_Returns_

If imported from the `wp` global, an alias is required to work in JSX.
- `ServerSideRenderResponse`: The server-side render response object.

```jsx
const { serverSideRender: ServerSideRender } = wp;

const MyServerSideRender = () => (
<ServerSideRender
block="core/archives"
attributes={ {
showPostCounts: true,
displayAsDropdown: false,
} }
/>
);
```
<!-- END TOKEN(Autogenerated API docs) -->

## Output

Expand Down
3 changes: 1 addition & 2 deletions packages/server-side-render/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@
"@wordpress/deprecated": "file:../deprecated",
"@wordpress/element": "file:../element",
"@wordpress/i18n": "file:../i18n",
"@wordpress/url": "file:../url",
"fast-deep-equal": "^3.1.3"
"@wordpress/url": "file:../url"
},
"peerDependencies": {
"react": "^18.0.0",
Expand Down
Loading