diff --git a/CHANGELOG.md b/CHANGELOG.md index b773fdc..021f4be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/README.md b/README.md index 93f761d..d7f7870 100644 --- a/README.md +++ b/README.md @@ -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. @@ -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. @@ -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: '

Title

', rendered: '

Title

', inner_blocks: [] }, +// { id: '1', name: 'core/group', attributes: {}, html: '
', 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 diff --git a/config/headless.php b/config/headless.php index 45b5901..fb5799d 100644 --- a/config/headless.php +++ b/config/headless.php @@ -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, + ], ]; diff --git a/src/Domain/Block/BlockTree.php b/src/Domain/Block/BlockTree.php new file mode 100644 index 0000000..0008852 --- /dev/null +++ b/src/Domain/Block/BlockTree.php @@ -0,0 +1,69 @@ +Hello

", rendered: "

Hello

", 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> $parsed what parse_blocks() returns + * @param Closure(string, array): array $withDefaults the attributes of a block, completed with its type's defaults + * @param Closure(array): 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> + */ + 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; + } +} diff --git a/src/Infrastructure/Config/Settings.php b/src/Infrastructure/Config/Settings.php index ef6ebd9..231602b 100644 --- a/src/Infrastructure/Config/Settings.php +++ b/src/Infrastructure/Config/Settings.php @@ -64,6 +64,7 @@ private function __construct( public bool $oldSlugRedirects, public bool $mediaRoutes, public ?string $mediaCdn, + public bool $blocks, ) {} /** @@ -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), ); } diff --git a/src/Infrastructure/WordPress/BlocksField.php b/src/Infrastructure/WordPress/BlocksField.php new file mode 100644 index 0000000..800d8fd --- /dev/null +++ b/src/Infrastructure/WordPress/BlocksField.php @@ -0,0 +1,90 @@ +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 $post the post as the REST controller prepared it + * @param \WP_REST_Request> $request + * @return list>|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> + */ + 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); + } + } + } +} diff --git a/src/Infrastructure/WordPress/Bootstrap.php b/src/Infrastructure/WordPress/Bootstrap.php index bbe9167..b9c42e9 100644 --- a/src/Infrastructure/WordPress/Bootstrap.php +++ b/src/Infrastructure/WordPress/Bootstrap.php @@ -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); } diff --git a/tests/Integration/BlocksTest.php b/tests/Integration/BlocksTest.php new file mode 100644 index 0000000..cae3732 --- /dev/null +++ b/tests/Integration/BlocksTest.php @@ -0,0 +1,101 @@ +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("\n

Title

\n\n\n\n
\n

Inside

\n
\n"); + $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('

Title

') + ->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("\n
\n"); + $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(''); + $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('

Written in the classic editor.

'); + + 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('

Secret

', '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' => '

x

', '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'); +}); diff --git a/tests/Unit/Domain/BlockTreeTest.php b/tests/Unit/Domain/BlockTreeTest.php new file mode 100644 index 0000000..30fa641 --- /dev/null +++ b/tests/Unit/Domain/BlockTreeTest.php @@ -0,0 +1,84 @@ +> $parsed + * @return list> + */ +function blocksOf(array $parsed, array $defaults = [], array $dynamic = []): array +{ + return BlockTree::from( + $parsed, + static fn (string $name, array $attrs): array => [...$attrs, ...array_diff_key($defaults[$name] ?? [], $attrs)], + static fn (array $block): string => 'rendered:'.($block['blockName'] ?? 'freeform'), + static fn (string $name): bool => in_array($name, $dynamic, true), + ); +} + +function parsedBlock(?string $name, string $html = '', array $attrs = [], array $inner = []): array +{ + return ['blockName' => $name, 'attrs' => $attrs, 'innerBlocks' => $inner, 'innerHTML' => $html, 'innerContent' => [$html]]; +} + +it('gives every block the same keys in the same order', function (): void { + $blocks = blocksOf([parsedBlock('core/paragraph', '

Hello

', ['dropCap' => true])]); + + expect(array_keys($blocks[0]))->toBe(['id', 'name', 'attributes', 'html', 'rendered', 'inner_blocks']) + ->and($blocks[0])->toMatchArray(['id' => '0', 'name' => 'core/paragraph', 'attributes' => ['dropCap' => true], 'html' => '

Hello

', 'rendered' => 'rendered:core/paragraph', 'inner_blocks' => []]); +}); + +it('numbers the blocks by their position, through the nesting', function (): void { + $blocks = blocksOf([ + parsedBlock('core/heading', '

A

'), + parsedBlock('core/group', '
', [], [parsedBlock('core/paragraph', '

B

'), parsedBlock('core/columns', '', [], [parsedBlock('core/column', '', [], [parsedBlock('core/image', '')])])]), + ]); + + expect(array_column($blocks, 'id'))->toBe(['0', '1']) + ->and(array_column($blocks[1]['inner_blocks'], 'id'))->toBe(['1.0', '1.1']) + ->and($blocks[1]['inner_blocks'][1]['inner_blocks'][0]['inner_blocks'][0]['id'])->toBe('1.1.0.0'); +}); + +it('says what WordPress prints for the top-level blocks and for the dynamic ones only', function (): void { + $blocks = blocksOf([ + parsedBlock('core/group', '
', [], [parsedBlock('core/paragraph', '

Static

'), parsedBlock('core/latest-posts', '', [], [])]), + ], [], ['core/latest-posts']); + + expect($blocks[0])->toHaveKey('rendered') + ->and($blocks[0]['inner_blocks'][0])->not->toHaveKey('rendered') + ->and($blocks[0]['inner_blocks'][1]['rendered'])->toBe('rendered:core/latest-posts'); +}); + +it('completes the attributes with the defaults of the block type, and keeps what the comment says', function (): void { + $blocks = blocksOf([parsedBlock('core/image', '', ['id' => 5])], ['core/image' => ['id' => 0, 'sizeSlug' => 'large']]); + + expect($blocks[0]['attributes'])->toBe(['id' => 5, 'sizeSlug' => 'large']); +}); + +it('turns the text between blocks into a freeform block, and drops whitespace', function (): void { + $blocks = blocksOf([parsedBlock(null, "\n\n"), parsedBlock(null, '

Classic content

'), parsedBlock('core/paragraph', '

x

'), parsedBlock(null, ' ')]); + + expect(array_column($blocks, 'name'))->toBe(['core/freeform', 'core/paragraph']) + ->and(array_column($blocks, 'id'))->toBe(['0', '1']); +}); + +it('gives no attributes as an empty object, so that the JSON stays an object', function (): void { + $blocks = blocksOf([parsedBlock('core/separator', '
')]); + + expect($blocks[0]['attributes'])->toBeInstanceOf(stdClass::class) + ->and(json_encode($blocks[0]['attributes']))->toBe('{}'); +}); + +it('reads a parsed block that is incomplete', function (): void { + $blocks = blocksOf([['blockName' => 'core/quote'], ['blockName' => 'core/list', 'attrs' => 'broken', 'innerBlocks' => 'broken', 'innerHTML' => 5]]); + + expect(array_column($blocks, 'name'))->toBe(['core/quote', 'core/list']) + ->and($blocks[1]['inner_blocks'])->toBe([]) + ->and($blocks[1]['html'])->toBe(''); +}); + +it('gives nothing for a content without blocks', function (): void { + expect(blocksOf([]))->toBe([]); +}); diff --git a/tests/Unit/Infrastructure/BlocksFieldTest.php b/tests/Unit/Infrastructure/BlocksFieldTest.php new file mode 100644 index 0000000..0973e8b --- /dev/null +++ b/tests/Unit/Infrastructure/BlocksFieldTest.php @@ -0,0 +1,46 @@ +once(); + $module = new BlocksField; + $module->register(new WordPressHooks); + + Functions\when('get_post_types')->justReturn(['post', 'page', 'event']); + Functions\when('post_type_supports')->alias(static fn (string $type, string $feature): bool => $type !== 'event' && $feature === 'editor'); + Functions\expect('register_rest_field')->twice()->with(Mockery::anyOf('post', 'page'), 'headless_blocks', Mockery::type('array')); + + $module->fields(); +}); + +it('gives no blocks unless the request names the field', function (): void { + $request = Mockery::mock('WP_REST_Request'); + $request->shouldReceive('get_param')->with('_fields')->andReturn('id,title'); + Functions\expect('get_post')->never(); + + expect((new BlocksField)->blocks(['id' => 12], 'headless_blocks', $request))->toBeNull(); +}); + +it('gives no blocks for a post that is gone or protected by a password', function (): void { + $request = Mockery::mock('WP_REST_Request'); + $request->shouldReceive('get_param')->with('_fields')->andReturn('headless_blocks'); + $post = Mockery::mock('WP_Post'); + Functions\when('get_post')->alias(static fn (int $id): ?WP_Post => $id === 12 ? $post : null); + Functions\when('post_password_required')->justReturn(true); + + expect((new BlocksField)->blocks(['id' => 99], 'headless_blocks', $request))->toBeNull() + ->and((new BlocksField)->blocks(['id' => 12], 'headless_blocks', $request))->toBeNull(); +}); + +it('reads the blocks setting', function (): void { + expect(Settings::fromArray(['frontend_url' => 'https://www.example.com'], 'https://cms.example.com')->blocks)->toBeTrue() + ->and(Settings::fromArray(['frontend_url' => 'https://www.example.com', 'blocks' => ['enabled' => false]], 'https://cms.example.com')->blocks)->toBeFalse() + ->and(Settings::fromArray([], 'https://cms.example.com')->blocks)->toBeFalse(); +}); diff --git a/tests/Unit/Infrastructure/ModulesTest.php b/tests/Unit/Infrastructure/ModulesTest.php index 041fb62..2e8e83e 100644 --- a/tests/Unit/Infrastructure/ModulesTest.php +++ b/tests/Unit/Infrastructure/ModulesTest.php @@ -120,10 +120,10 @@ function gateFor(FrontMode $mode, array &$ended): TemplateRedirectGate Functions\when('wp_salt')->justReturn('salt'); $settings = Settings::fromArray(['frontend_url' => 'https://www.example.com'], 'https://cms.example.com'); - expect(Bootstrap::modules($settings))->toHaveCount(13); + expect(Bootstrap::modules($settings))->toHaveCount(14); Actions\expectAdded('template_redirect')->once(); - Actions\expectAdded('rest_api_init')->times(5); + Actions\expectAdded('rest_api_init')->times(6); Filters\expectAdded('preview_post_link')->once(); Filters\expectAdded('rest_pre_dispatch')->once(); Filters\expectAdded('rest_post_dispatch')->once();