Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,5 @@ All notable changes are listed here. The format follows [Keep a Changelog](https
- Site manifest: `GET /wp-json/headless/v1/site` (site, languages, menus as trees, locations, front page, content types and taxonomies).
- Redirects: rules managed with `wp headless redirect`, the old slugs of renamed posts, `GET /wp-json/headless/v1/redirects` and `/redirects/resolve`.
- Media: `GET /wp-json/headless/v1/media/{id}` (one shape for every kind, with the focal point of `pollora/media`), the `headless_featured_media` field, and `media.cdn_url` to serve the uploads from a CDN.
- Blocks as stable JSON: the field `headless_blocks` of a post, when `_fields` names it.
- mu-plugin loader (`stubs/pollora-headless.php`) and a Pollora service provider discovered by Composer.
16 changes: 14 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Prepare WordPress for headless mode: lock the public front, remove what a headless site does not use, and (in the releases to come) secure and speed up the API, preview drafts from a JS front end and tell it when content changes.

> **Status: `0.4`, not released.** The front gate and clean-up (0.1), CORS, REST security and speed, front-end links, multilingual sites and API tokens (0.2), the preview of drafts (0.3) and the notifications of changes (0.4) are in. The API may change until `1.0`. The roadmap below says what comes next; the API may change until `1.0`.
> **Status: `0.5`, not released.** The front gate and clean-up (0.1), CORS, REST security and speed, front-end links, multilingual sites and API tokens (0.2), the preview of drafts (0.3), the notifications of changes (0.4) and the normalised content (site manifest, redirects, media, blocks: 0.5) are in. The API may change until `1.0`. The roadmap below says what comes next; the API may change until `1.0`.

It works on a classic WordPress, on Bedrock and inside a [Pollora](https://pollora.dev) project, with the same core. Any Node application can use it: the contract is plain HTTP, no client library is needed.

Expand All @@ -26,6 +26,7 @@ It works on a classic WordPress, on Bedrock and inside a [Pollora](https://pollo
| Site manifest | `GET /wp-json/headless/v1/site`: the site and its languages, the menus as trees with front-end paths, the menu locations, the front page and the content types with their REST routes, in one public, cacheable answer. |
| Redirects | The redirects of the site for a front end: the ones you manage (`wp headless redirect add /old/ /new/`, patterns, 410 for a page that is gone) and the old addresses WordPress remembers for renamed posts, at `GET /wp-json/headless/v1/redirects` (every rule) and `/redirects/resolve?path=/old/` (one path). |
| Media | A file of the library in one shape whatever its kind (`GET /wp-json/headless/v1/media/{id}`: url, sizes, srcset, alt, caption, the focal point set with `pollora/media`), the featured image of a post in full without a second request, and the uploads served from a CDN. |
| Blocks | The blocks of a post as JSON that does not change shape: `?_fields=id,headless_blocks`. See [Blocks](#blocks-as-json). |
| URL mapper | `UrlMapper::toFront()` turns a URL of the WordPress site into the URL of the same page on the front end. It is the one place every URL the package hands out goes through. |

Nothing changes on the public site until you set the front-end URL: a site that is not told where its front end lives is never locked.
Expand Down Expand Up @@ -188,9 +189,20 @@ const post = await (await fetch('https://cms.example.com/wp-json/wp/v2/posts/12?

To serve the uploads from a CDN or an image proxy, set `media.cdn_url` (or `HEADLESS_MEDIA_CDN_URL` on Pollora): `https://cdn.example.com` replaces `https://cms.example.com/wp-content/uploads` in the address of every file, in `srcset` and in the HTML of the content. The administration keeps the WordPress addresses, so that an editor sees a file they have just uploaded.

## Blocks as JSON

```js
const post = await (await fetch('https://cms.example.com/wp-json/wp/v2/posts/12?_fields=id,headless_blocks')).json();
post.headless_blocks;
// [ { id: '0', name: 'core/heading', attributes: { level: 3 }, html: '<h3 …>Title</h3>', rendered: '<h3 …>Title</h3>', inner_blocks: [] },
// { id: '1', name: 'core/group', attributes: {}, html: '<div class="wp-block-group"></div>', rendered: '…', inner_blocks: [ { id: '1.0', name: 'core/paragraph', … } ] } ]
```

Every block has the same keys in the same order. `id` is its position (`1.0` is the first block inside the second): a key for a list. `attributes` are those of the block comment, completed with the defaults of the block type, `{}` when there are none; a value a block takes from its HTML (the text of a paragraph) is in `html`. `html` is the block's own HTML; `rendered` is what WordPress prints for it, inner blocks included, and is present on top-level blocks and on dynamic blocks (a list of posts has no HTML of its own). Text outside blocks (classic content) is one `core/freeform` block. A post with a password gives `null`. The field is computed only when `_fields` names it. It is not in the preview answer.

## Roadmap

`0.1` core · `0.2` CORS, REST security and speed, URL mapping, Polylang and WPML, API tokens · `0.3` content preview · `0.4` revalidation webhooks (this release) · `0.5` site manifest, media, blocks as JSON, redirects · `0.6` SEO (Yoast, Rank Math, AIOSEO, SEOPress, The SEO Framework) · `0.7` optional WPGraphQL, schema snapshots, forms and search · `0.8` doctor, end-to-end tests · `1.0` frozen contract.
`0.1` core · `0.2` CORS, REST security and speed, URL mapping, Polylang and WPML, API tokens · `0.3` content preview · `0.4` revalidation webhooks · `0.5` site manifest, redirects, media, blocks as JSON (this release) · `0.6` SEO (Yoast, Rank Math, AIOSEO, SEOPress, The SEO Framework) · `0.7` optional WPGraphQL, schema snapshots, forms and search · `0.8` doctor, end-to-end tests · `1.0` frozen contract.

## Quality

Expand Down
6 changes: 6 additions & 0 deletions config/headless.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,4 +138,10 @@
'enabled' => true,
'cdn_url' => env('HEADLESS_MEDIA_CDN_URL', ''),
],

// The blocks of a post as stable JSON, in the field `headless_blocks` of its REST answer when _fields names it:
// /wp-json/wp/v2/posts/12?_fields=id,headless_blocks. Only active once a front-end URL is set.
'blocks' => [
'enabled' => true,
],
];
69 changes: 69 additions & 0 deletions src/Domain/Block/BlockTree.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Domain\Block;

use Closure;
use stdClass;

/**
* The blocks of a post in a shape that does not change: the same keys on every block, in the same order, whatever
* the block, so that a front end can be typed against it.
*
* ```
* { id: "1.0", name: "core/paragraph", attributes: {…}, html: "<p>Hello</p>", rendered: "<p>Hello</p>", inner_blocks: [ … ] }
* ```
*
* - `id` is the position of the block in the content (`1.0` is the first block inside the second one): stable for one
* content, and a key a front end can use to render a list.
* - `attributes` are those of the block comment, completed with the defaults of the block type; `{}` when there are none.
* A value a block takes from its HTML (the text of a paragraph) is in `html`, as on the server it cannot be read otherwise.
* - `html` is the block's own HTML, without its inner blocks. `rendered` is what WordPress prints for it, inner blocks
* included: it is present on top-level blocks and on dynamic blocks (a list of posts has no HTML of its own), absent otherwise.
* - Text between blocks that is not whitespace is a `core/freeform` block.
*/
final class BlockTree
{
/**
* @param list<array<string, mixed>> $parsed what parse_blocks() returns
* @param Closure(string, array<string, mixed>): array<string, mixed> $withDefaults the attributes of a block, completed with its type's defaults
* @param Closure(array<string, mixed>): string $render the HTML WordPress prints for a parsed block
* @param Closure(string): bool $isDynamic whether a block type renders on the server
* @return list<array<string, mixed>>
*/
public static function from(array $parsed, Closure $withDefaults, Closure $render, Closure $isDynamic, string $prefix = ''): array
{
$blocks = [];

foreach ($parsed as $block) {
$name = is_string($block['blockName'] ?? null) ? $block['blockName'] : null;
$html = is_string($block['innerHTML'] ?? null) ? $block['innerHTML'] : '';

if ($name === null && trim($html) === '') {
continue;
}

$name ??= 'core/freeform';
$id = $prefix.count($blocks);
$attributes = $withDefaults($name, is_array($block['attrs'] ?? null) ? $block['attrs'] : []);

$normalised = [
'id' => $id,
'name' => $name,
'attributes' => $attributes === [] ? new stdClass : $attributes,
'html' => $html,
];

if ($prefix === '' || $isDynamic($name)) {
$normalised['rendered'] = $render($block);
}

$normalised['inner_blocks'] = self::from(is_array($block['innerBlocks'] ?? null) ? array_values($block['innerBlocks']) : [], $withDefaults, $render, $isDynamic, $id.'.');
$blocks[] = $normalised;

}

return $blocks;
}
}
2 changes: 2 additions & 0 deletions src/Infrastructure/Config/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ private function __construct(
public bool $oldSlugRedirects,
public bool $mediaRoutes,
public ?string $mediaCdn,
public bool $blocks,
) {}

/**
Expand Down Expand Up @@ -127,6 +128,7 @@ public static function fromArray(array $config, string $backendUrl): self
oldSlugRedirects: self::bool(is_array($config['redirects'] ?? null) ? $config['redirects'] : [], 'old_slugs', true),
mediaRoutes: $front instanceof Origin && self::bool($media, 'enabled', true),
mediaCdn: self::mediaCdn($media),
blocks: $front instanceof Origin && self::bool(is_array($config['blocks'] ?? null) ? $config['blocks'] : [], 'enabled', true),
);
}

Expand Down
90 changes: 90 additions & 0 deletions src/Infrastructure/WordPress/BlocksField.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Infrastructure\WordPress;

use Pollora\Headless\Domain\Block\BlockTree;

/**
* The blocks of a post as stable JSON (see BlockTree), in the field `headless_blocks` of its REST answer, when
* `_fields` names it: parsing and rendering every block is work a list of posts should not pay for by default.
*
* A post with a password gives no blocks (its content is not given either), and a block is rendered with the
* post as the current one, as on its own page.
*/
final readonly class BlocksField implements Module
{
public const string FIELD = 'headless_blocks';

public function register(HookRegistrar $hooks): void
{
$hooks->addAction('rest_api_init', [$this, 'fields']);
}

public function fields(): void
{
foreach (get_post_types(['show_in_rest' => true, 'public' => true]) as $type) {
if (post_type_supports($type, 'editor')) {
register_rest_field($type, self::FIELD, [
'get_callback' => [$this, 'blocks'],
'schema' => ['description' => 'The blocks of the content as stable JSON (ask for it in _fields).', 'type' => ['array', 'null'], 'context' => ['view', 'edit']],
]);
}
}
}

/**
* @param array<string, mixed> $post the post as the REST controller prepared it
* @param \WP_REST_Request<array<string, mixed>> $request
* @return list<array<string, mixed>>|null
*/
public function blocks(array $post, string $field, \WP_REST_Request $request): ?array
{
$wpPost = OptInField::requested($request, self::FIELD) ? get_post((int) ($post['id'] ?? 0)) : null;

if (! $wpPost instanceof \WP_Post || post_password_required($wpPost)) {
return null;
}

return self::forContent($wpPost->post_content, $wpPost);
}

/**
* @return list<array<string, mixed>>
*/
public static function forContent(string $content, \WP_Post $post): array
{
$registry = \WP_Block_Type_Registry::get_instance();

// Blocks read the current post (the title of a post, a list of its terms)
$original = $GLOBALS['post'] ?? null;
$GLOBALS['post'] = $post;
setup_postdata($post);

try {
return BlockTree::from(
parse_blocks($content),
static function (string $name, array $attributes) use ($registry): array {
$type = $registry->get_registered($name);

foreach ($type instanceof \WP_Block_Type ? $type->attributes ?? [] : [] as $key => $definition) {
if (is_array($definition) && array_key_exists('default', $definition) && ! array_key_exists($key, $attributes)) {
$attributes[$key] = $definition['default'];
}
}

return $attributes;
},
static fn (array $block): string => render_block($block),
static fn (string $name): bool => ($type = $registry->get_registered($name)) instanceof \WP_Block_Type && $type->is_dynamic(),
);
} finally {
$GLOBALS['post'] = $original;

if ($original instanceof \WP_Post) {
setup_postdata($original);
}
}
}
}
4 changes: 4 additions & 0 deletions src/Infrastructure/WordPress/Bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,10 @@ public static function modules(Settings $settings, ?Languages $languages = null)
$modules[] = new RedirectRoutes(new RedirectCatalog([new OptionRedirectStore, ...($settings->oldSlugRedirects ? [new OldSlugRedirects($urls)] : [])]));
}

if ($settings->blocks) {
$modules[] = new BlocksField;
}

if ($settings->mediaRoutes) {
$modules[] = new MediaRoutes(new NormalizedMedia);
}
Expand Down
101 changes: 101 additions & 0 deletions tests/Integration/BlocksTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
<?php

declare(strict_types=1);

use Pollora\Headless\Infrastructure\WordPress\BlocksField;
use Pollora\Headless\Infrastructure\WordPress\WordPressHooks;

/**
* Blocks as stable JSON against a real WordPress: the real block parser, the real block types, the real renderer.
*/
function blocksFor(string $content, string $status = 'publish', string $password = ''): array
{
(new BlocksField)->register(new WordPressHooks);
$GLOBALS['wp_rest_server'] = null;
rest_get_server();

$id = wp_insert_post(['post_title' => 'Blocks', 'post_content' => $content, 'post_status' => $status, 'post_password' => $password]);
$request = new WP_REST_Request('GET', "/wp/v2/posts/$id");
$request->set_param('_fields', 'id,headless_blocks');
$data = rest_do_request($request)->get_data();
wp_delete_post($id, true);

return $data;
}

afterEach(function (): void {
foreach (array_keys($GLOBALS['wp_filter']) as $hook) {
foreach ($GLOBALS['wp_filter'][$hook]->callbacks as $priority => $callbacks) {
foreach ($callbacks as $callback) {
$function = $callback['function'];

if (is_array($function) && is_object($function[0]) && str_starts_with($function[0]::class, 'Pollora\\Headless\\')) {
remove_filter($hook, $function, $priority);
}
}
}
}
});

it('gives the blocks of a post in a stable shape, nested', function (): void {
$data = blocksFor("<!-- wp:heading {\"level\":3} -->\n<h3 class=\"wp-block-heading\">Title</h3>\n<!-- /wp:heading -->\n\n<!-- wp:group -->\n<div class=\"wp-block-group\"><!-- wp:paragraph -->\n<p>Inside</p>\n<!-- /wp:paragraph --></div>\n<!-- /wp:group -->");
$blocks = $data['headless_blocks'];

expect($blocks)->toHaveCount(2)
->and(array_keys($blocks[0]))->toBe(['id', 'name', 'attributes', 'html', 'rendered', 'inner_blocks'])
->and($blocks[0])->toMatchArray(['id' => '0', 'name' => 'core/heading'])
->and($blocks[0]['attributes'])->toMatchArray(['level' => 3])
->and($blocks[0]['html'])->toContain('<h3 class="wp-block-heading">Title</h3>')
->and($blocks[0]['rendered'])->toContain('Title')
->and($blocks[1]['name'])->toBe('core/group')
->and($blocks[1]['rendered'])->toContain('Inside')
->and($blocks[1]['inner_blocks'])->toHaveCount(1)
->and($blocks[1]['inner_blocks'][0])->toMatchArray(['id' => '1.0', 'name' => 'core/paragraph'])
->and($blocks[1]['inner_blocks'][0])->not->toHaveKey('rendered');
});

it('renders a dynamic block that has no HTML of its own, even inside another block', function (): void {
$data = blocksFor("<!-- wp:group -->\n<div class=\"wp-block-group\"><!-- wp:latest-posts {\"postsToShow\":2} /--></div>\n<!-- /wp:group -->");
$inner = $data['headless_blocks'][0]['inner_blocks'][0];

expect($inner['name'])->toBe('core/latest-posts')
->and($inner['html'])->toBe('')
->and($inner['attributes'])->toMatchArray(['postsToShow' => 2])
->and($inner['rendered'])->toContain('wp-block-latest-posts');
});

it('completes the attributes with the defaults of the block type', function (): void {
$data = blocksFor('<!-- wp:latest-posts /-->');
$attributes = $data['headless_blocks'][0]['attributes'];

expect($attributes)->toHaveKey('postsToShow')->and($attributes['postsToShow'])->toBe(5);
});

it('turns classic content into one freeform block', function (): void {
$data = blocksFor('<p>Written in the classic editor.</p>');

expect($data['headless_blocks'])->toHaveCount(1)
->and($data['headless_blocks'][0]['name'])->toBe('core/freeform')
->and($data['headless_blocks'][0]['html'])->toContain('classic editor');
});

it('gives nothing for a post with a password, and no blocks for an empty post', function (): void {
$protected = blocksFor('<!-- wp:paragraph --><p>Secret</p><!-- /wp:paragraph -->', 'publish', 'hunter2');
$empty = blocksFor('');

expect($protected['headless_blocks'])->toBeNull()->and($empty['headless_blocks'])->toBe([]);
});

it('does not compute the blocks of a list of posts that did not ask for them', function (): void {
(new BlocksField)->register(new WordPressHooks);
$GLOBALS['wp_rest_server'] = null;
rest_get_server();
$id = wp_insert_post(['post_title' => 'Plain', 'post_content' => '<!-- wp:paragraph --><p>x</p><!-- /wp:paragraph -->', 'post_status' => 'publish']);

$request = new WP_REST_Request('GET', '/wp/v2/posts');
$request->set_param('_fields', 'id,title');
$data = rest_do_request($request)->get_data();
wp_delete_post($id, true);

expect($data[0])->not->toHaveKey('headless_blocks');
});
Loading
Loading