From 8e28d41c7992d12edd605662fe10a90a6f41185d Mon Sep 17 00:00:00 2001 From: Jeffrey Carandang Date: Sat, 21 Nov 2026 01:54:35 +0800 Subject: [PATCH 1/5] Send Custom HTML blocks to beehiiv as HTML Snippets with a Newsletter only option --- includes/Editor/NewsletterOnlyHtml.php | 92 ++++++++ includes/Newsletter/BlockConverter.php | 62 ++++- .../Converters/HtmlBlockConverter.php | 72 ++++++ includes/Newsletter/SupportedBlocks.php | 4 +- includes/Plugin.php | 1 + .../css/_newsletter-only-html.scss | 14 ++ src/js/editor/post-settings/editor.scss | 1 + .../filters/with-newsletter-only-html.js | 107 +++++++++ src/js/editor/post-settings/index.js | 1 + .../editor/post-settings/utils/html-block.js | 18 ++ tests/phpunit/BlockConverterHtmlTest.php | 213 ++++++++++++++++++ 11 files changed, 576 insertions(+), 9 deletions(-) create mode 100644 includes/Editor/NewsletterOnlyHtml.php create mode 100644 includes/Newsletter/Converters/HtmlBlockConverter.php create mode 100644 src/js/editor/post-settings/css/_newsletter-only-html.scss create mode 100644 src/js/editor/post-settings/filters/with-newsletter-only-html.js create mode 100644 src/js/editor/post-settings/utils/html-block.js create mode 100644 tests/phpunit/BlockConverterHtmlTest.php diff --git a/includes/Editor/NewsletterOnlyHtml.php b/includes/Editor/NewsletterOnlyHtml.php new file mode 100644 index 0000000..0ba81e9 --- /dev/null +++ b/includes/Editor/NewsletterOnlyHtml.php @@ -0,0 +1,92 @@ + $args Block type arguments. + * @param string $block_name Block name. + * @return array + * @since 1.3.0 + */ + public static function register_attribute( array $args, string $block_name ): array { + if ( 'core/html' !== $block_name ) { + return $args; + } + + $attributes = isset( $args['attributes'] ) && is_array( $args['attributes'] ) ? $args['attributes'] : []; + + $args['attributes'] = $attributes; + $args['attributes'][ self::ATTRIBUTE ] = [ + 'type' => 'boolean', + 'default' => false, + ]; + + return $args; + } + + /** + * Output nothing for a newsletter-only Custom HTML block. + * + * @param string $block_content Rendered block content. + * @param array $block Parsed block. + * @return string + * @since 1.3.0 + */ + public static function hide_block( string $block_content, array $block ): string { + if ( self::is_newsletter_only( $block ) ) { + return ''; + } + + return $block_content; + } + + /** + * Whether a parsed block is a Custom HTML block set to "Newsletter only". + * + * @param array $block Parsed block. + * @return bool + * @since 1.3.0 + */ + public static function is_newsletter_only( array $block ): bool { + return 'core/html' === ( $block['blockName'] ?? '' ) + && ! empty( $block['attrs'][ self::ATTRIBUTE ] ); + } +} diff --git a/includes/Newsletter/BlockConverter.php b/includes/Newsletter/BlockConverter.php index 3fabc24..0e15f8b 100644 --- a/includes/Newsletter/BlockConverter.php +++ b/includes/Newsletter/BlockConverter.php @@ -11,6 +11,7 @@ use Beehiiv\API\Resources\AdvertisementOpportunities; use Beehiiv\Editor\Meta; use Beehiiv\Newsletter\Converters\ColumnsBlockConverter; +use Beehiiv\Newsletter\Converters\HtmlBlockConverter; use Beehiiv\Newsletter\Converters\GroupBlockConverter; use Beehiiv\Newsletter\Converters\MediaTextBlockConverter; use Beehiiv\Newsletter\Converters\TableBlockConverter; @@ -154,6 +155,18 @@ private static function convert_blocks( continue; } + if ( 'core/media-text' === $block_name ) { + $trailing_blocks = []; + $media_text = self::convert_media_text_block( $wp_block, $trailing_blocks ); + + if ( ! empty( $media_text ) ) { + $beehiiv_blocks[] = $media_text; + } + + $beehiiv_blocks = array_merge( $beehiiv_blocks, $trailing_blocks ); + continue; + } + $beehiiv_block = self::convert_block( $wp_block ); if ( ! empty( $beehiiv_block ) ) { @@ -235,6 +248,8 @@ private static function convert_block( array $wp_block ): array { return self::convert_embed_block( $wp_block ); case 'core/media-text': return self::convert_media_text_block( $wp_block ); + case 'core/html': + return HtmlBlockConverter::convert( $wp_block ); case 'beehiiv/advertisement': return self::convert_advertisement_block( $wp_block ); } @@ -631,6 +646,7 @@ public static function convert_columns_block_to_blocks( array $wp_block ): array $column_blocks = []; $converted_columns = []; $nested_blocks = []; + $html_blocks = []; foreach ( $wp_block['innerBlocks'] ?? [] as $column_block ) { if ( 'core/column' !== ( $column_block['blockName'] ?? '' ) ) { @@ -640,7 +656,8 @@ public static function convert_columns_block_to_blocks( array $wp_block ): array $column_blocks[] = $column_block; $converted_columns[] = self::convert_layout_block_inner_blocks( $column_block['innerBlocks'] ?? [], - $nested_blocks + $nested_blocks, + $html_blocks ); } @@ -678,7 +695,7 @@ public static function convert_columns_block_to_blocks( array $wp_block ): array ColumnsBlockConverter::resolve_stack_on_mobile( $attrs, $inner_html ) ); - return array_values( array_filter( array_merge( [ $columns_block ], $nested_blocks ) ) ); + return array_values( array_filter( array_merge( [ $columns_block ], $nested_blocks, $html_blocks ) ) ); } /** @@ -692,12 +709,15 @@ public static function convert_columns_block_to_blocks( array $wp_block ): array * * @param array> $wp_blocks Parsed inner blocks. * @param array>|null $nested_blocks Receives the inner blocks of nested columns. + * @param array>|null $html_blocks Receives the HTML blocks of inner Custom HTML + * blocks, which a column cannot hold. * @return array> * @since 1.0.0 */ private static function convert_layout_block_inner_blocks( array $wp_blocks, - ?array &$nested_blocks = null + ?array &$nested_blocks = null, + ?array &$html_blocks = null ): array { $beehiiv_blocks = []; @@ -714,7 +734,8 @@ private static function convert_layout_block_inner_blocks( if ( 'core/column' === ( $nested_column['blockName'] ?? '' ) ) { $nested_converted = self::convert_layout_block_inner_blocks( $nested_column['innerBlocks'] ?? [], - $nested_blocks + $nested_blocks, + $html_blocks ); $nested_blocks = array_merge( $nested_blocks, $nested_converted ); } @@ -724,6 +745,18 @@ private static function convert_layout_block_inner_blocks( continue; } + // A beehiiv column cannot hold an HTML block, so the snippet is handed to the caller + // to emit right after the parent block. Without a caller to receive it, it is omitted. + if ( 'core/html' === $block_name ) { + $html_block = HtmlBlockConverter::convert( $wp_block ); + + if ( null !== $html_blocks && ! empty( $html_block ) ) { + $html_blocks[] = $html_block; + } + + continue; + } + if ( 'core/buttons' === $block_name ) { $beehiiv_blocks = array_merge( $beehiiv_blocks, self::convert_buttons_block( $wp_block ) ); continue; @@ -1110,11 +1143,13 @@ public static function convert_embed_block( array $wp_block ): array { * entirely. Respects media position, column widths, vertical alignment, and * mobile stacking. * - * @param array $wp_block Parsed block. + * @param array $wp_block Parsed block. + * @param array>|null $trailing_blocks Receives the HTML blocks of inner Custom HTML + * blocks, to emit after the returned block. * @return array * @since 1.0.0 */ - public static function convert_media_text_block( array $wp_block ): array { + public static function convert_media_text_block( array $wp_block, ?array &$trailing_blocks = null ): array { $attrs = $wp_block['attrs'] ?? []; $inner_html = (string) ( $wp_block['innerHTML'] ?? '' ); $inner_blocks = $wp_block['innerBlocks'] ?? []; @@ -1134,13 +1169,20 @@ public static function convert_media_text_block( array $wp_block ): array { return []; } - $content_blocks = self::convert_layout_block_inner_blocks( $inner_blocks ); + $html_blocks = []; + $content_nested = null; + $content_blocks = self::convert_layout_block_inner_blocks( $inner_blocks, $content_nested, $html_blocks ); if ( empty( $content_blocks ) && '' !== $inner_html ) { $content_html = MediaTextBlockConverter::extract_content_inner_html( $inner_html ); if ( '' !== $content_html ) { - $content_blocks = self::convert_layout_block_inner_blocks( parse_blocks( $content_html ) ); + $html_blocks = []; + $content_blocks = self::convert_layout_block_inner_blocks( + parse_blocks( $content_html ), + $content_nested, + $html_blocks + ); } } @@ -1174,6 +1216,10 @@ public static function convert_media_text_block( array $wp_block ): array { return []; } + if ( null !== $trailing_blocks ) { + $trailing_blocks = $html_blocks; + } + return ColumnsBlockConverter::build_beehiiv_columns_block( $columns, $stack_on_mobile ); } diff --git a/includes/Newsletter/Converters/HtmlBlockConverter.php b/includes/Newsletter/Converters/HtmlBlockConverter.php new file mode 100644 index 0000000..58fce1b --- /dev/null +++ b/includes/Newsletter/Converters/HtmlBlockConverter.php @@ -0,0 +1,72 @@ +` and `' ) + . $this->html_block( '' ) + ); + + $blocks = BlockConverter::convert_supported_blocks( $post ); + + $this->assertCount( 1, $blocks ); + $this->assertSame( '

Keep

', $blocks[0]['html'] ); + } + + /** + * AC-015, AC-021: a newsletter-only block still syncs and carries no visibility rule. + */ + public function test_newsletter_only_block_still_syncs_without_visibility_rule(): void { + $post = $this->create_post( $this->html_block( '

Ad

', true ) ); + $blocks = BlockConverter::convert_supported_blocks( $post ); + + $this->assertCount( 1, $blocks ); + $this->assertSame( 'html', $blocks[0]['type'] ); + $this->assertArrayNotHasKey( 'visibility_settings', $blocks[0] ); + } + + /** + * AC-014, AC-016, AC-017, AC-019: a newsletter-only block renders nothing, others render as today. + */ + public function test_newsletter_only_block_is_hidden_from_rendered_content_and_the_feed(): void { + $post = $this->create_post( + $this->html_block( '

Visible block

' ) . $this->html_block( '

Newsletter ad

', true ) + ); + + $rendered = apply_filters( 'the_content', $post->post_content ); + + $this->assertStringContainsString( 'Visible block', $rendered ); + $this->assertStringNotContainsString( 'Newsletter ad', $rendered ); + + $feed = apply_filters( 'the_content_feed', $rendered ); + $this->assertStringNotContainsString( 'Newsletter ad', $feed ); + + $excerpt = wp_trim_excerpt( '', $post ); + $this->assertStringNotContainsString( 'Newsletter ad', $excerpt ); + + $request = new WP_REST_Request( 'GET', '/wp/v2/posts/' . $post->ID ); + $response = rest_do_request( $request ); + $data = $response->get_data(); + $this->assertStringNotContainsString( 'Newsletter ad', $data['content']['rendered'] ); + $this->assertStringContainsString( 'Visible block', $data['content']['rendered'] ); + } + + /** + * AC-020: turning the option off shows the block again. + */ + public function test_turning_the_option_off_restores_the_block(): void { + $post = $this->create_post( $this->html_block( '

Ad

', true ) ); + $this->assertStringNotContainsString( 'Ad', apply_filters( 'the_content', $post->post_content ) ); + + wp_update_post( + array( + 'ID' => $post->ID, + 'post_content' => $this->html_block( '

Ad

' ), + ) + ); + + $this->assertStringContainsString( + 'Ad', + apply_filters( 'the_content', get_post( $post->ID )->post_content ) + ); + } +} From 9b353a31b89e8f4fb9dadf6d76e6a07cb394fb04 Mon Sep 17 00:00:00 2001 From: Jeffrey Carandang Date: Sat, 21 Nov 2026 01:58:19 +0800 Subject: [PATCH 2/5] Add E2E specs for Custom HTML snippet conversion and the Newsletter only option --- .../html-snippet-block-conversion.spec.js | 866 ++++++++++++++++++ 1 file changed, 866 insertions(+) create mode 100644 tests/e2e/specs/html-snippet-block-conversion.spec.js diff --git a/tests/e2e/specs/html-snippet-block-conversion.spec.js b/tests/e2e/specs/html-snippet-block-conversion.spec.js new file mode 100644 index 0000000..9c215c4 --- /dev/null +++ b/tests/e2e/specs/html-snippet-block-conversion.spec.js @@ -0,0 +1,866 @@ +const { test, expect } = require( '@playwright/test' ); +const { loginAsAdmin } = require( '../utils/auth' ); +const { openPostEditor, saveDraft } = require( '../utils/editor' ); +const { + wpCli, + wpCliSafe, + ensurePluginActive, + ensurePrettyPermalinks, +} = require( '../utils/wp-cli' ); + +/** + * PRD: requirements/07-newsletter-publishing/2-block-conversion/html-snippet-block-conversion.prd.md (v1.0) + * + * Independent behavioral coverage (qa-e2e-author), written from the PRD's + * Acceptance Criteria plus the real code at: + * - includes/Newsletter/Converters/HtmlBlockConverter.php -- snippet building. + * - includes/Newsletter/BlockConverter.php -- block walk, Group, Columns and + * Media & Text routing. + * - includes/Editor/NewsletterOnlyHtml.php -- the render-time hiding. + * - src/js/editor/post-settings/filters/with-newsletter-only-html.js -- the + * sidebar option, label and notice. + * + * Payload tests save a post through the REST endpoint the block editor uses + * (POST /wp/v2/posts/{id}, cookie + nonce). The test-only `pre_http_request` + * mock in tests/e2e/plugins/beehiiv-options.php answers the beehiiv call and + * records it, so each test asserts on the exact `blocks` payload the plugin + * sent. Nothing reaches the live API. + * + * AUTHORED, NOT RUN: these specs were written on a machine with no Docker, so + * they have never executed. A failure may be the spec's own fault. + */ + +const META = { + send: '_beehiiv_send_to_newsletter', + postId: '_beehiiv_post_id', +}; + +const PUBLICATION_ID = 'pub_qa_e2e_html'; +const TEMPLATE_ID = 'tpl_qa_e2e_html'; +const MOCK_CREATED_ID = 'post_qa_e2e_html_created'; +const IMG = 'https://example.com/qa-image.jpg'; +const OMITTED_NOTICE = '.beehiiv-post-settings-notice__omitted'; +const UNSUPPORTED_NOTICE = '.beehiiv-html-unsupported-notice'; +const NEWSLETTER_ONLY_LABEL = '.beehiiv-newsletter-only-label'; + +const createdPosts = []; + +const b64 = ( value ) => + Buffer.from( JSON.stringify( value ) ).toString( 'base64' ); + +/** + * Runs PHP inside the tests env; the payload travels base64-encoded. + * + * @param {Object} payload Values exposed to the PHP snippet as `$a`. + * @param {string} php PHP code to evaluate. + * @return {string} wp-cli output. + */ +function wpEvalWith( payload, php ) { + return wpCli( + `eval '$a = json_decode( base64_decode( "${ b64( + payload + ) }" ), true ); ${ php }'` + ); +} + +/** + * Seeds a connected, ready-to-send site and mocks the beehiiv posts endpoint. + */ +function seed() { + wpEvalWith( + {}, + `beehiiv_e2e_reset_all(); + beehiiv_e2e_seed_connection(); + beehiiv_e2e_mock_permissions( [ "posts" => [ "read", "write" ] ] ); + update_option( "beehiiv_settings", [ "publication_id" => "${ PUBLICATION_ID }", "post_template_id" => "${ TEMPLATE_ID }" ] ); + beehiiv_e2e_seed_publications( [ [ "id" => "${ PUBLICATION_ID }", "name" => "QA E2E Publication" ] ] ); + beehiiv_e2e_seed_post_templates( "${ PUBLICATION_ID }", [ [ "id" => "${ TEMPLATE_ID }", "name" => "QA E2E Template" ] ] ); + beehiiv_e2e_mock_http( "/posts", [ "body" => [ "data" => [ "id" => "${ MOCK_CREATED_ID }" ] ] ] ); + beehiiv_e2e_clear_http_log();` + ); +} + +/** + * Creates a draft post fixture in the DB. + * + * The current user is set to the admin first, so WordPress does not strip + * script, iframe and style elements from the fixture content. + * + * @param {Object} options Post fields. + * @param {string} options.content Post content (block markup). + * @param {boolean} [options.send] Whether "Send to Newsletter" is on. + * @return {string} Post ID. + */ +function createPost( { content, send = false } ) { + const post = { + post_type: 'post', + post_title: 'QA E2E html snippet', + post_content: content, + post_status: 'draft', + post_author: 1, + }; + const id = wpEvalWith( + { post, send }, + `wp_set_current_user( 1 ); + $id = wp_insert_post( $a["post"] ); + if ( $a["send"] ) { update_post_meta( $id, "${ META.send }", "1" ); } + beehiiv_e2e_clear_http_log(); + echo $id . "\\n";` + ); + createdPosts.push( id ); + return id; +} + +/** + * Returns the recorded outbound beehiiv requests. + * + * @return {Array} Request log entries. + */ +function getLog() { + return JSON.parse( + wpCli( `eval 'beehiiv_e2e_print_http_log();'` ) || '[]' + ); +} + +/** + * Clears the recorded request log. + */ +function clearLog() { + wpCli( `eval 'beehiiv_e2e_clear_http_log();'` ); +} + +const creates = ( log ) => + log.filter( + ( r ) => + r.method === 'POST' && /\/publications\/[^/]+\/posts$/.test( r.url ) + ); +const updates = ( log ) => log.filter( ( r ) => r.method === 'PATCH' ); + +/** + * Logs in as admin and returns a REST caller bound to that session. + * + * @param {import('@playwright/test').Page} page Playwright page. + * @return {Promise} `( method, path, data ) => { status, body }`. + */ +async function restAs( page ) { + await loginAsAdmin( page ); + const nonceRes = await page.request.get( + '/wp-admin/admin-ajax.php?action=rest-nonce' + ); + const nonce = ( await nonceRes.text() ).trim(); + return async ( method, path, data ) => { + const res = await page.request.fetch( `/wp-json${ path }`, { + method, + headers: { 'X-WP-Nonce': nonce }, + data, + } ); + let body = null; + try { + body = await res.json(); + } catch { + // Non-JSON response; leave body null. + } + return { status: res.status(), body }; + }; +} + +/** + * Publishes a new post and returns what was sent to beehiiv, when it was sent. + * + * @param {import('@playwright/test').Page} page Playwright page. + * @param {string} content Post content (block markup). + * @param {Object} [options] Options. + * @param {boolean} [options.send] Send to the newsletter (default true). + * @return {Promise<{id: string, link: string, blocks: Array, rest: Function}>} Result. + */ +async function publish( page, content, { send = true } = {} ) { + seed(); + const id = createPost( { content, send } ); + const rest = await restAs( page ); + const res = await rest( 'POST', `/wp/v2/posts/${ id }`, { + status: 'publish', + } ); + expect( res.status ).toBe( 200 ); + let blocks = []; + if ( send ) { + const created = creates( getLog() ); + expect( created, 'beehiiv create-post request was sent' ).toHaveLength( + 1 + ); + blocks = created[ 0 ].body.blocks || []; + } + return { id, link: res.body.link, blocks, rest }; +} + +// --------------------------------------------------------------------------- +// Block markup builders. +// --------------------------------------------------------------------------- + +const p = ( text ) => + `

${ text }

`; +const code = ( text ) => + `
${ text }
`; + +/** + * Builds a Custom HTML block. + * + * @param {string} source The HTML the publisher typed. + * @param {Object} [options] Options. + * @param {boolean} [options.only] "Newsletter only" option value. + * @return {string} Serialized block. + */ +const html = ( source, { only } = {} ) => { + const attrs = + only === undefined + ? '' + : ` ${ JSON.stringify( { beehiivNewsletterOnly: only } ) }`; + return `\n${ source }\n`; +}; + +const group = ( inner ) => + `
${ inner }
`; + +const col = ( inner ) => + `
${ inner }
`; + +const columns = ( cols ) => + `
${ cols.join( + '' + ) }
`; + +const mediaText = ( inner ) => + `
a
${ inner }
`; + +const types = ( blocks ) => blocks.map( ( b ) => b.type ); +const snippets = ( blocks ) => blocks.filter( ( b ) => b.type === 'html' ); +const snippetHtml = ( blocks ) => snippets( blocks ).map( ( b ) => b.html ); + +// Sample advertiser HTML. +const STYLED = + ''; +const PIXEL = + ''; + +test.describe.configure( { timeout: 150 * 1000 } ); + +test.beforeAll( async () => { + ensurePluginActive(); + ensurePrettyPermalinks(); +} ); + +test.afterAll( async () => { + if ( createdPosts.length ) { + wpCliSafe( + `eval 'foreach ( array( ${ createdPosts.join( + ', ' + ) } ) as $id ) { delete_post_meta( $id, "${ + META.postId + }" ); wp_delete_post( $id, true ); } + delete_option( "beehiiv_settings" ); beehiiv_e2e_reset_all();'` + ); + } +} ); + +// --------------------------------------------------------------------------- +test.describe( 'US-001: send Custom HTML to the newsletter', () => { + test( 'AC-001: each non-empty Custom HTML block converts to one HTML snippet in its original position', async ( { + page, + } ) => { + const { blocks } = await publish( + page, + p( 'Before' ) + html( '
QA_ONE
' ) + p( 'After' ) + ); + expect( types( blocks ) ).toEqual( [ + 'paragraph', + 'html', + 'paragraph', + ] ); + expect( blocks[ 1 ].html ).toBe( '
QA_ONE
' ); + } ); + + test( 'AC-002: the HTML arrives as written, with inline styles, tracking pixel and tracking links unchanged and no wrapper', async ( { + page, + } ) => { + const source = `${ STYLED }\n
QA_CELL
\n${ PIXEL }`; + const { blocks } = await publish( page, html( source ) ); + const found = snippets( blocks ); + expect( found ).toHaveLength( 1 ); + // Exact string: no added wrapper, no reformatting (BR-001). + expect( found[ 0 ].html ).toBe( source ); + expect( found[ 0 ].html ).toContain( 'utm_source=qa&utm_medium=email' ); + expect( found[ 0 ].html ).toContain( 'width="1" height="1"' ); + expect( Object.keys( found[ 0 ] ).sort() ).toEqual( [ + 'html', + 'type', + ] ); + } ); + + test( 'AC-003: several Custom HTML blocks produce several snippets in the original order and are never merged', async ( { + page, + } ) => { + const { blocks } = await publish( + page, + html( '
QA_FIRST
' ) + + p( 'Between' ) + + html( '
QA_SECOND
' ) + + html( '
QA_THIRD
' ) + ); + expect( types( blocks ) ).toEqual( [ + 'html', + 'paragraph', + 'html', + 'html', + ] ); + expect( snippetHtml( blocks ) ).toEqual( [ + '
QA_FIRST
', + '
QA_SECOND
', + '
QA_THIRD
', + ] ); + } ); + + test( 'AC-004: an empty or whitespace-only Custom HTML block produces no snippet', async ( { + page, + } ) => { + const { blocks } = await publish( + page, + p( 'Before' ) + + '' + + html( ' \n\t ' ) + + p( 'After' ) + ); + expect( types( blocks ) ).toEqual( [ 'paragraph', 'paragraph' ] ); + } ); + + test( 'AC-005: a Custom HTML block inside a Group stays inside the Group section, in its original position', async ( { + page, + } ) => { + const { blocks } = await publish( + page, + p( 'Top' ) + + group( + p( 'Group first' ) + + html( '
QA_IN_GROUP
' ) + + p( 'Group last' ) + ) + ); + expect( types( blocks ) ).toEqual( [ 'paragraph', 'section' ] ); + const section = blocks[ 1 ]; + expect( types( section.blocks ) ).toEqual( [ + 'paragraph', + 'html', + 'paragraph', + ] ); + expect( section.blocks[ 1 ].html ).toBe( '
QA_IN_GROUP
' ); + } ); + + test( "AC-006: a Custom HTML block inside Columns or Media & Text is sent right after that block's columns block, in order, never dropped", async ( { + page, + } ) => { + const inColumns = await publish( + page, + p( 'Top' ) + + columns( [ + col( p( 'Left text' ) + html( '
QA_COL_A
' ) ), + col( html( '
QA_COL_B
' ) + p( 'Right text' ) ), + ] ) + + p( 'Tail' ) + ); + expect( types( inColumns.blocks ) ).toEqual( [ + 'paragraph', + 'columns', + 'html', + 'html', + 'paragraph', + ] ); + expect( snippetHtml( inColumns.blocks ) ).toEqual( [ + '
QA_COL_A
', + '
QA_COL_B
', + ] ); + // The columns block itself holds none of the HTML. + expect( JSON.stringify( inColumns.blocks[ 1 ] ) ).not.toContain( + 'QA_COL_' + ); + + const inMediaText = await publish( + page, + p( 'Top' ) + + mediaText( p( 'Side text' ) + html( '
QA_MEDIA
' ) ) + + p( 'Tail' ) + ); + expect( types( inMediaText.blocks ) ).toEqual( [ + 'paragraph', + 'columns', + 'html', + 'paragraph', + ] ); + expect( inMediaText.blocks[ 2 ].html ).toBe( '
QA_MEDIA
' ); + expect( JSON.stringify( inMediaText.blocks[ 1 ] ) ).not.toContain( + 'QA_MEDIA' + ); + } ); + + test( 'AC-007: syncing an updated post updates the snippet content and does not add a second snippet', async ( { + page, + } ) => { + const { id, rest } = await publish( + page, + p( 'Intro' ) + html( '
QA_VERSION_ONE
' ) + ); + clearLog(); + const res = await rest( 'POST', `/wp/v2/posts/${ id }`, { + content: p( 'Intro' ) + html( '
QA_VERSION_TWO
' ), + } ); + expect( res.status ).toBe( 200 ); + const log = getLog(); + // The linked post is updated in place, never created again. + expect( creates( log ) ).toHaveLength( 0 ); + const patched = updates( log ); + expect( patched ).toHaveLength( 1 ); + expect( types( patched[ 0 ].body.blocks ) ).toEqual( [ + 'paragraph', + 'html', + ] ); + expect( snippetHtml( patched[ 0 ].body.blocks ) ).toEqual( [ + '
QA_VERSION_TWO
', + ] ); + } ); + + test( 'AC-008: a Custom HTML block is not marked omitted in the editor and is not counted in the omitted-block notice', async ( { + page, + } ) => { + seed(); + // A Code block is omitted today, so it proves the marks are working + // and that only it is counted. + const id = createPost( { + content: + p( 'Kept text' ) + + html( '
QA_EDITOR_HTML
' ) + + code( 'Left out' ), + send: true, + } ); + await loginAsAdmin( page ); + await openPostEditor( page, id ); + await page + .getByRole( 'button', { name: 'beehiiv', exact: true } ) + .first() + .click(); + await expect( + page.locator( '.beehiiv-post-settings-content' ) + ).toBeVisible(); + + await expect( page.locator( OMITTED_NOTICE ) ).toContainText( + '1 block will be omitted from this newsletter.' + ); + const canvas = page.frameLocator( 'iframe[name="editor-canvas"]' ); + await expect( canvas.locator( '.beehiiv-omitted-block' ) ).toHaveCount( + 1 + ); + await expect( + canvas.locator( '.wp-block-code.beehiiv-omitted-block' ) + ).toHaveCount( 1 ); + await expect( canvas.locator( '[data-type="core/html"]' ) ).toHaveCount( + 1 + ); + await expect( + canvas.locator( '[data-type="core/html"].beehiiv-omitted-block' ) + ).toHaveCount( 0 ); + } ); +} ); + +// --------------------------------------------------------------------------- +test.describe( 'US-002: keep unsupported elements out of the newsletter', () => { + test( 'AC-009: script elements are removed and the rest of the HTML arrives unchanged', async ( { + page, + } ) => { + const { blocks } = await publish( + page, + html( + `${ STYLED }

QA_AFTER_SCRIPT

` + ) + ); + expect( snippetHtml( blocks ) ).toEqual( [ + `${ STYLED }

QA_AFTER_SCRIPT

`, + ] ); + expect( JSON.stringify( blocks ) ).not.toMatch( /' ) + + html( '' ) + + html( + '\n' + ) + + p( 'After' ) + ); + expect( types( blocks ) ).toEqual( [ 'paragraph', 'paragraph' ] ); + } ); + + test( 'AC-012: the editor shows a notice on a Custom HTML block holding a script or iframe, and none on a block without them', async ( { + page, + } ) => { + seed(); + const id = createPost( { + content: + html( + '

QA_NOTICE_SCRIPT

' + ) + + html( '' ) + + html( '
QA_NOTICE_PLAIN
' ), + } ); + await loginAsAdmin( page ); + await openPostEditor( page, id ); + const canvas = page.frameLocator( 'iframe[name="editor-canvas"]' ); + const blocks = canvas.locator( '[data-type="core/html"]' ); + await expect( blocks ).toHaveCount( 3 ); + + const message = + 'Script and iframe elements are not included in the newsletter.'; + await expect( + blocks.nth( 0 ).locator( UNSUPPORTED_NOTICE ) + ).toContainText( message ); + await expect( + blocks.nth( 1 ).locator( UNSUPPORTED_NOTICE ) + ).toContainText( message ); + await expect( + blocks.nth( 2 ).locator( UNSUPPORTED_NOTICE ) + ).toHaveCount( 0 ); + } ); +} ); + +// --------------------------------------------------------------------------- +test.describe( 'US-003: send advertiser HTML to the newsletter only', () => { + const VISIBLE = 'QA_SITE_VISIBLE'; + const HIDDEN = 'QA_NEWSLETTER_ONLY'; + + /** + * Reads the front end, feed, excerpt and REST content of a published post. + * + * @param {import('@playwright/test').Page} page Playwright page. + * @param {string} id Post ID. + * @param {string} link Post permalink. + * @return {Promise} The four channels as strings. + */ + async function channels( page, id, link ) { + const front = await page.request.get( link ); + const feed = await page.request.get( '/?feed=rss2' ); + const rest = await page.request.get( `/wp-json/wp/v2/posts/${ id }` ); + const body = await rest.json(); + const excerpt = wpCli( + `eval 'echo get_the_excerpt( get_post( ${ id } ) );'` + ); + return { + front: await front.text(), + feed: await feed.text(), + restContent: body.content.rendered, + restExcerpt: body.excerpt.rendered, + excerpt, + }; + } + + test( 'AC-013: the sidebar of a Custom HTML block has a "Newsletter only" option, off by default', async ( { + page, + } ) => { + seed(); + const id = createPost( { content: html( '
QA_SIDEBAR
' ) } ); + await loginAsAdmin( page ); + await openPostEditor( page, id ); + const canvas = page.frameLocator( 'iframe[name="editor-canvas"]' ); + await canvas.locator( '[data-type="core/html"]' ).waitFor(); + await page.evaluate( () => { + const store = window.wp.data.select( 'core/block-editor' ); + const block = store + .getBlocks() + .find( ( b ) => b.name === 'core/html' ); + window.wp.data + .dispatch( 'core/block-editor' ) + .selectBlock( block.clientId ); + } ); + + const toggle = page.getByRole( 'checkbox', { + name: 'Newsletter only', + } ); + const visible = await toggle + .waitFor( { state: 'visible', timeout: 3000 } ) + .then( () => true ) + .catch( () => false ); + if ( ! visible ) { + // Settings sidebar is closed or showing another panel. + await page + .getByRole( 'button', { name: 'Settings', exact: true } ) + .first() + .click(); + } + await expect( toggle ).toBeVisible(); + await expect( toggle ).not.toBeChecked(); + + // Turning it on saves a per-block attribute (AC-019 data shape). + await toggle.check(); + await expect( canvas.locator( NEWSLETTER_ONLY_LABEL ) ).toBeVisible(); + await saveDraft( page ); + const saved = wpEvalWith( + { id }, + 'echo get_post_field( "post_content", $a["id"] );' + ); + expect( saved ).toContain( '"beehiivNewsletterOnly":true' ); + } ); + + test( 'AC-014: with the option off, the block shows on the site and also syncs as a snippet', async ( { + page, + } ) => { + const { id, link, blocks } = await publish( + page, + p( 'Intro' ) + html( `
${ VISIBLE }
`, { only: false } ) + ); + expect( snippetHtml( blocks ) ).toEqual( [ + `
${ VISIBLE }
`, + ] ); + const seen = await channels( page, id, link ); + expect( seen.front ).toContain( VISIBLE ); + } ); + + test( 'AC-015: with the option on, the block syncs as a snippet in its original position', async ( { + page, + } ) => { + const { blocks } = await publish( + page, + p( 'Before' ) + + html( `
${ HIDDEN }
`, { only: true } ) + + p( 'After' ) + ); + expect( types( blocks ) ).toEqual( [ + 'paragraph', + 'html', + 'paragraph', + ] ); + expect( blocks[ 1 ].html ).toBe( `
${ HIDDEN }
` ); + } ); + + test( 'AC-016: with the option on, the block shows nothing on the WordPress front end', async ( { + page, + } ) => { + const { id, link } = await publish( + page, + p( 'QA_PARAGRAPH_KEPT' ) + + html( `
${ HIDDEN }
`, { + only: true, + } ), + { send: false } + ); + const seen = await channels( page, id, link ); + expect( seen.front ).toContain( 'QA_PARAGRAPH_KEPT' ); + expect( seen.front ).not.toContain( HIDDEN ); + expect( seen.front ).not.toContain( 'qa-hidden' ); + } ); + + test( 'AC-017: with the option on, the HTML is missing from the RSS feed, the excerpt and the REST rendered content', async ( { + page, + } ) => { + const { id, link } = await publish( + page, + p( 'QA_PARAGRAPH_KEPT' ) + + html( `
${ VISIBLE }
` ) + + html( `
${ HIDDEN }
`, { only: true } ), + { send: false } + ); + const seen = await channels( page, id, link ); + + // The site-visible block reaches every channel, so each check is meaningful. + expect( seen.feed ).toContain( VISIBLE ); + expect( seen.restContent ).toContain( VISIBLE ); + expect( seen.excerpt ).toContain( VISIBLE ); + + expect( seen.feed ).not.toContain( HIDDEN ); + expect( seen.restContent ).not.toContain( HIDDEN ); + expect( seen.restExcerpt ).not.toContain( HIDDEN ); + expect( seen.excerpt ).not.toContain( HIDDEN ); + } ); + + test( 'AC-018: in the editor a block with the option on shows a "Newsletter only" label and stays editable', async ( { + page, + } ) => { + seed(); + const id = createPost( { + content: + html( '
QA_LABEL_ON
', { only: true } ) + + html( '
QA_LABEL_OFF
' ), + } ); + await loginAsAdmin( page ); + await openPostEditor( page, id ); + const canvas = page.frameLocator( 'iframe[name="editor-canvas"]' ); + const blocks = canvas.locator( '[data-type="core/html"]' ); + await expect( blocks ).toHaveCount( 2 ); + + await expect( + blocks.nth( 0 ).locator( NEWSLETTER_ONLY_LABEL ) + ).toHaveText( 'Newsletter only' ); + await expect( + blocks.nth( 1 ).locator( NEWSLETTER_ONLY_LABEL ) + ).toHaveCount( 0 ); + // BR-007: the block is still shown in full so it can be edited. + await expect( blocks.nth( 0 ) ).toBeVisible(); + } ); + + test( 'AC-019: the option is per block, so one post can hold site-visible and newsletter-only blocks', async ( { + page, + } ) => { + const { id, link, blocks } = await publish( + page, + html( `
${ VISIBLE }
`, { only: false } ) + + html( `
${ HIDDEN }
`, { only: true } ) + + html( '
QA_DEFAULT_BLOCK
' ) + ); + expect( snippetHtml( blocks ) ).toEqual( [ + `
${ VISIBLE }
`, + `
${ HIDDEN }
`, + '
QA_DEFAULT_BLOCK
', + ] ); + const seen = await channels( page, id, link ); + expect( seen.front ).toContain( VISIBLE ); + expect( seen.front ).toContain( 'QA_DEFAULT_BLOCK' ); + expect( seen.front ).not.toContain( HIDDEN ); + } ); + + test( 'AC-020: turning the option on for a published post removes the block from the site after the update, and turning it off shows it again', async ( { + page, + } ) => { + const source = `
${ HIDDEN }
`; + const { id, link, rest } = await publish( + page, + p( 'QA_PARAGRAPH_KEPT' ) + html( source ), + { send: false } + ); + expect( ( await channels( page, id, link ) ).front ).toContain( + HIDDEN + ); + + await rest( 'POST', `/wp/v2/posts/${ id }`, { + content: p( 'QA_PARAGRAPH_KEPT' ) + html( source, { only: true } ), + } ); + const hidden = await channels( page, id, link ); + expect( hidden.front ).toContain( 'QA_PARAGRAPH_KEPT' ); + expect( hidden.front ).not.toContain( HIDDEN ); + expect( hidden.feed ).not.toContain( HIDDEN ); + + await rest( 'POST', `/wp/v2/posts/${ id }`, { + content: p( 'QA_PARAGRAPH_KEPT' ) + html( source, { only: false } ), + } ); + expect( ( await channels( page, id, link ) ).front ).toContain( + HIDDEN + ); + } ); + + test( 'AC-021: a newsletter-only snippet carries no rule that hides it on the beehiiv web version or in the email', async ( { + page, + } ) => { + const { blocks } = await publish( + page, + html( `
${ HIDDEN }
`, { only: true } ) + ); + const found = snippets( blocks ); + expect( found ).toHaveLength( 1 ); + // Only a type and the HTML: no visibility or display setting of any kind. + expect( Object.keys( found[ 0 ] ).sort() ).toEqual( [ + 'html', + 'type', + ] ); + expect( JSON.stringify( found[ 0 ] ) ).not.toMatch( + /visib|hidden|hide|web_only|email_only|display/i + ); + // And the option itself is not sent as a setting on the snippet. + expect( JSON.stringify( found[ 0 ] ) ).not.toContain( + 'beehiivNewsletterOnly' + ); + } ); +} ); + +// --------------------------------------------------------------------------- +test.describe( 'US-004: verify the full flow on a test post', () => { + test( 'AC-022: a post mixing a site-visible and a newsletter-only Custom HTML block behaves as agreed from the editor to the newsletter', async ( { + page, + } ) => { + const visibleSource = + '
QA22_VISIBLE_DIV
\n
QA22_VISIBLE_TABLE
'; + const linkedImage = + 'QA22_BANNER'; + const pixel = + ''; + const script = ''; + const hiddenSource = `${ linkedImage }\n${ pixel }\n${ script }`; + const hiddenSent = `${ linkedImage }\n${ pixel }`; + + const content = + p( 'QA22_PARAGRAPH_ONE' ) + + html( visibleSource, { only: false } ) + + p( 'QA22_PARAGRAPH_TWO' ) + + html( hiddenSource, { only: true } ); + + const { id, link, blocks } = await publish( page, content ); + + // Front end and feed: first block present, second absent. + const front = await ( await page.request.get( link ) ).text(); + const feed = await ( await page.request.get( '/?feed=rss2' ) ).text(); + for ( const channel of [ front, feed ] ) { + expect( channel ).toContain( 'QA22_PARAGRAPH_ONE' ); + expect( channel ).toContain( 'QA22_VISIBLE_DIV' ); + expect( channel ).toContain( 'QA22_VISIBLE_TABLE' ); + expect( channel ).toContain( 'QA22_PARAGRAPH_TWO' ); + expect( channel ).not.toContain( 'utm_source=qa22' ); + expect( channel ).not.toContain( 'qa22-track' ); + expect( channel ).not.toContain( 'QA22_BANNER' ); + } + + // beehiiv: same order, two separate snippets, script removed. + expect( types( blocks ) ).toEqual( [ + 'paragraph', + 'html', + 'paragraph', + 'html', + ] ); + expect( snippetHtml( blocks ) ).toEqual( [ + visibleSource, + hiddenSent, + ] ); + + // Editor: label and script notice on the second block only. + await openPostEditor( page, id ); + const canvas = page.frameLocator( 'iframe[name="editor-canvas"]' ); + const editorBlocks = canvas.locator( '[data-type="core/html"]' ); + await expect( editorBlocks ).toHaveCount( 2 ); + await expect( + editorBlocks.nth( 1 ).locator( NEWSLETTER_ONLY_LABEL ) + ).toHaveText( 'Newsletter only' ); + await expect( + editorBlocks.nth( 1 ).locator( UNSUPPORTED_NOTICE ) + ).toBeVisible(); + await expect( + editorBlocks.nth( 0 ).locator( NEWSLETTER_ONLY_LABEL ) + ).toHaveCount( 0 ); + await expect( + editorBlocks.nth( 0 ).locator( UNSUPPORTED_NOTICE ) + ).toHaveCount( 0 ); + } ); +} ); From 4d99abfac3db3800d08b3264352468f2a4a7863c Mon Sep 17 00:00:00 2001 From: Jeffrey Carandang Date: Sat, 21 Nov 2026 02:48:48 +0800 Subject: [PATCH 3/5] Run the Custom HTML conversion tests as an administrator so script tags survive saving --- tests/phpunit/BlockConverterHtmlTest.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/phpunit/BlockConverterHtmlTest.php b/tests/phpunit/BlockConverterHtmlTest.php index 235bd16..8c08885 100644 --- a/tests/phpunit/BlockConverterHtmlTest.php +++ b/tests/phpunit/BlockConverterHtmlTest.php @@ -26,6 +26,11 @@ class BlockConverterHtmlTest extends WP_UnitTestCase { public function set_up(): void { parent::set_up(); + // Run as an administrator, who may save unfiltered HTML. Without a user, WordPress strips + // script tags when a post is saved and leaves their text behind, which is not what a + // publisher who can add a Custom HTML block gets. + wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) ); + update_option( Config::OPTION_NAME, array( From e2e8533414c545bbb02f87e51ce2770280c2105f Mon Sep 17 00:00:00 2001 From: Jeffrey Carandang Date: Sat, 21 Nov 2026 03:20:31 +0800 Subject: [PATCH 4/5] Add the demo walkthrough script for the Custom HTML snippet intake --- tests/e2e/demo/251e59b4.demo.js | 286 ++++++++++++++++++++++++++++++++ 1 file changed, 286 insertions(+) create mode 100644 tests/e2e/demo/251e59b4.demo.js diff --git a/tests/e2e/demo/251e59b4.demo.js b/tests/e2e/demo/251e59b4.demo.js new file mode 100644 index 0000000..1042354 --- /dev/null +++ b/tests/e2e/demo/251e59b4.demo.js @@ -0,0 +1,286 @@ +// @demo-acs AC-001 AC-002 AC-003 AC-009 AC-013 AC-014 AC-015 AC-016 AC-017 AC-018 AC-019 AC-022 +/** + * One-take demo for intake 251e59b4: Custom HTML blocks sent to beehiiv as + * HTML Snippets, with a per-block "Newsletter only" option (PRD-07.2.02). + * + * Run through the record-intake-demo skill (config: playwright.demo.config.js). + * State is arranged with wp-cli and the plugin's test-only beehiiv mock, so + * nothing reaches the live API. The editor steps go through the real UI. The + * post is published through the same REST endpoint the editor uses, and every + * caption about the site, the feed or the beehiiv payload follows an assertion. + */ +const path = require( 'path' ); +const os = require( 'os' ); +const fs = require( 'fs' ); +const kit = require( './kit' ); +const { saveDraft } = require( '../utils/editor' ); +const { test, expect, wp, installOverlay, caption, glideClick, point } = kit; + +const PUBLICATION_ID = 'pub_demo_html'; +const TEMPLATE_ID = 'tpl_demo_html'; +const CREATED_ID = 'post_demo_html_created'; +const STATE = path.join( os.tmpdir(), 'demo-251e59b4-auth.json' ); +const NEWSLETTER_ONLY_LABEL = '.beehiiv-newsletter-only-label'; +const ids = []; + +const b64 = ( value ) => + Buffer.from( JSON.stringify( value ) ).toString( 'base64' ); + +const evalWith = ( payload, php ) => + wp.wpCli( + `eval '$a = json_decode( base64_decode( "${ b64( + payload + ) }" ), true ); ${ php }'` + ); + +const p = ( text ) => + `

${ text }

`; +const html = ( source ) => `\n${ source }\n`; + +const VISIBLE = + '
Spring offer for readers
\n
Offer details
'; +const LINKED_IMAGE = + 'Sponsor banner'; +const PIXEL = + ''; +const SCRIPT = ''; +const AD_SOURCE = `${ LINKED_IMAGE }\n${ PIXEL }\n${ SCRIPT }`; +const AD_SENT = `${ LINKED_IMAGE }\n${ PIXEL }`; + +function seed() { + evalWith( + {}, + `beehiiv_e2e_reset_all(); + beehiiv_e2e_seed_connection(); + beehiiv_e2e_mock_permissions( [ "posts" => [ "read", "write" ] ] ); + update_option( "beehiiv_settings", [ "publication_id" => "${ PUBLICATION_ID }", "post_template_id" => "${ TEMPLATE_ID }" ] ); + beehiiv_e2e_seed_publications( [ [ "id" => "${ PUBLICATION_ID }", "name" => "Demo Publication" ] ] ); + beehiiv_e2e_seed_post_templates( "${ PUBLICATION_ID }", [ [ "id" => "${ TEMPLATE_ID }", "name" => "Demo Template" ] ] ); + beehiiv_e2e_mock_http( "/posts", [ "body" => [ "data" => [ "id" => "${ CREATED_ID }" ] ] ] ); + beehiiv_e2e_clear_http_log();` + ); +} + +function createPost() { + const post = { + post_type: 'post', + post_title: 'Spring newsletter', + post_content: + p( 'Welcome to this week’s issue.' ) + + html( VISIBLE ) + + p( 'More news below.' ) + + html( AD_SOURCE ), + post_status: 'draft', + post_author: 1, + }; + const id = evalWith( + { post }, + `wp_set_current_user( 1 ); + $id = wp_insert_post( $a["post"] ); + update_post_meta( $id, "_beehiiv_send_to_newsletter", "1" ); + beehiiv_e2e_clear_http_log(); + echo $id . "\\n";` + ); + ids.push( id ); + return id; +} + +async function dismissGuide( page ) { + const close = page.locator( '.components-modal__header button' ).first(); + if ( await close.isVisible().catch( () => false ) ) { + await close.click(); + } +} + +test.use( { storageState: STATE, viewport: { width: 1280, height: 720 } } ); + +test.beforeAll( async ( { browser } ) => { + wp.ensurePluginActive(); + wp.ensurePrettyPermalinks(); + seed(); + const ctx = await browser.newContext( { + storageState: undefined, + baseURL: process.env.WP_BASE_URL || 'http://localhost:8891', + } ); + const page = await ctx.newPage(); + await kit.loginAsAdmin( page ); + await ctx.storageState( { path: STATE } ); + await ctx.close(); +} ); + +test.afterAll( () => { + wp.wpCliSafe( + `eval 'beehiiv_e2e_reset_all(); foreach ( array( ${ + ids.join( ', ' ) || '0' + } ) as $id ) { wp_delete_post( $id, true ); } delete_option( "beehiiv_settings" );'` + ); + fs.rmSync( STATE, { force: true } ); +} ); + +test( 'Custom HTML to beehiiv: full walkthrough', async ( { page } ) => { + await installOverlay( page ); + const id = createPost(); + + // 1. Editor: a post with two Custom HTML blocks ----------------------- + await page.goto( `/wp-admin/post.php?post=${ id }&action=edit` ); + await page.waitForSelector( 'iframe[name="editor-canvas"]', { + timeout: 20000, + } ); + await dismissGuide( page ); + const canvas = page.frameLocator( 'iframe[name="editor-canvas"]' ); + const blocks = canvas.locator( '[data-type="core/html"]' ); + await expect( blocks ).toHaveCount( 2 ); + await caption( + page, + 'Custom HTML to beehiiv · demo of the beehiiv plugin build', + 3000 + ); + await caption( + page, + '1/4 · The post has a paragraph, a Custom HTML block, a paragraph and a second Custom HTML block', + 3500 + ); + await point( page, blocks.nth( 1 ), 800 ); + await caption( + page, + 'The second block is advertiser HTML: a linked image, a tracking pixel and a script', + 4000 + ); + + // 2. The Newsletter only option ----------------------------------------- + await glideClick( page, blocks.nth( 1 ) ); + await page.evaluate( () => { + const store = window.wp.data.select( 'core/block-editor' ); + const found = store + .getBlocks() + .filter( ( b ) => b.name === 'core/html' ); + window.wp.data + .dispatch( 'core/block-editor' ) + .selectBlock( found[ 1 ].clientId ); + } ); + const toggle = page.getByRole( 'checkbox', { name: 'Newsletter only' } ); + const settingsButton = page + .getByRole( 'button', { name: 'Settings', exact: true } ) + .first(); + if ( ( await settingsButton.getAttribute( 'aria-pressed' ) ) !== 'true' ) { + await settingsButton.click(); + } + const blockTab = page.getByRole( 'tab', { name: 'Block', exact: true } ); + if ( await blockTab.isVisible().catch( () => false ) ) { + await blockTab.click(); + } + const innerTab = page.getByRole( 'tab', { name: 'Settings', exact: true } ); + if ( await innerTab.isVisible().catch( () => false ) ) { + await innerTab.click(); + } + await expect( toggle ).toBeVisible(); + await expect( toggle ).not.toBeChecked(); + await caption( + page, + '2/4 · The block settings have a "Newsletter only" option, off by default (AC-013)', + 4000 + ); + await glideClick( page, toggle ); + await expect( toggle ).toBeChecked(); + // One label for the one block that has the option on. It renders next to + // the block, not inside the block element, on current WordPress. + const label = canvas.locator( NEWSLETTER_ONLY_LABEL ); + await expect( label ).toHaveCount( 1 ); + await expect( label ).toHaveText( 'Newsletter only' ); + await point( page, label, 800 ); + await caption( + page, + 'Turned on for this block only. It is labelled in the editor, and only this block is labelled (AC-018, AC-019)', + 4500 + ); + await saveDraft( page ); + await caption( page, 'Saved', 1200 ); + + // 3. Publish and look at the site and the feed ------------------------- + await caption( + page, + '3/4 · Publish the post. The site and the feed show only the first Custom HTML block', + 3000 + ); + const nonce = ( + await ( + await page.request.get( + '/wp-admin/admin-ajax.php?action=rest-nonce' + ) + ).text() + ).trim(); + const res = await page.request.fetch( `/wp-json/wp/v2/posts/${ id }`, { + method: 'POST', + headers: { 'X-WP-Nonce': nonce }, + data: { status: 'publish' }, + } ); + expect( res.status() ).toBe( 200 ); + const post = await res.json(); + const front = await ( await page.request.get( post.link ) ).text(); + const feed = await ( await page.request.get( '/?feed=rss2' ) ).text(); + const rendered = await ( + await page.request.get( `/wp-json/wp/v2/posts/${ id }` ) + ).json(); + for ( const channel of [ + front, + feed, + rendered.content.rendered, + rendered.excerpt.rendered, + ] ) { + expect( channel ).not.toContain( 'utm_source=demo' ); + expect( channel ).not.toContain( 'demo-track' ); + expect( channel ).not.toContain( 'Sponsor banner' ); + } + expect( front ).toContain( 'Spring offer for readers' ); + expect( front ).toContain( 'Offer details' ); + expect( feed ).toContain( 'Spring offer for readers' ); + await page.goto( post.link ); + await expect( page.getByText( 'Spring offer for readers' ) ).toBeVisible(); + await caption( + page, + 'Front end: the first Custom HTML block shows. The sponsor block is not on the page (AC-014, AC-016)', + 4500 + ); + await page.goto( '/?feed=rss2' ); + await caption( + page, + 'RSS feed: same result. The sponsor block is also missing from the excerpt and the REST content (AC-017)', + 4500 + ); + + // 4. What beehiiv received ---------------------------------------------- + const log = JSON.parse( + wp.wpCli( `eval 'beehiiv_e2e_print_http_log();'` ) || '[]' + ); + const created = log.filter( + ( r ) => + r.method === 'POST' && /\/publications\/[^/]+\/posts$/.test( r.url ) + ); + expect( created ).toHaveLength( 1 ); + const sent = created[ 0 ].body.blocks || []; + expect( sent.map( ( b ) => b.type ) ).toEqual( [ + 'paragraph', + 'html', + 'paragraph', + 'html', + ] ); + const snippets = sent.filter( ( b ) => b.type === 'html' ); + expect( snippets.map( ( b ) => b.html ) ).toEqual( [ VISIBLE, AD_SENT ] ); + expect( snippets[ 1 ].html ).not.toContain( ' Date: Sat, 21 Nov 2026 03:34:40 +0800 Subject: [PATCH 5/5] Show the script notice on saved Custom HTML blocks in newer WordPress and fix the editor spec selectors --- .../filters/with-newsletter-only-html.js | 22 +++- .../html-snippet-block-conversion.spec.js | 109 ++++++++++++------ 2 files changed, 94 insertions(+), 37 deletions(-) diff --git a/src/js/editor/post-settings/filters/with-newsletter-only-html.js b/src/js/editor/post-settings/filters/with-newsletter-only-html.js index d2dcc44..a216c05 100644 --- a/src/js/editor/post-settings/filters/with-newsletter-only-html.js +++ b/src/js/editor/post-settings/filters/with-newsletter-only-html.js @@ -8,7 +8,11 @@ import { __ } from '@wordpress/i18n'; import { addFilter } from '@wordpress/hooks'; import { createHigherOrderComponent } from '@wordpress/compose'; -import { InspectorControls } from '@wordpress/block-editor'; +import { useSelect } from '@wordpress/data'; +import { + InspectorControls, + store as blockEditorStore, +} from '@wordpress/block-editor'; import { Notice, PanelBody, ToggleControl } from '@wordpress/components'; import { @@ -43,13 +47,27 @@ function addNewsletterOnlyAttribute( settings, name ) { const withNewsletterOnlyHtml = createHigherOrderComponent( ( BlockEdit ) => { return function BeehiivHtmlBlockEdit( props ) { + // Newer WordPress versions leave a saved Custom HTML block without a + // `content` attribute until it is edited. The saved markup is then only + // on the parsed block, so read it from there as a fallback. + const savedContent = useSelect( + ( select ) => + props.name === HTML_BLOCK + ? select( blockEditorStore ).getBlock( props.clientId ) + ?.originalContent + : undefined, + [ props.name, props.clientId ] + ); + if ( props.name !== HTML_BLOCK ) { return ; } const { attributes, setAttributes } = props; const isNewsletterOnly = !! attributes[ NEWSLETTER_ONLY_ATTRIBUTE ]; - const hasUnsupported = hasUnsupportedHtmlElements( attributes.content ); + const hasUnsupported = hasUnsupportedHtmlElements( + attributes.content ?? savedContent + ); return ( <> diff --git a/tests/e2e/specs/html-snippet-block-conversion.spec.js b/tests/e2e/specs/html-snippet-block-conversion.spec.js index 9c215c4..d3c63a1 100644 --- a/tests/e2e/specs/html-snippet-block-conversion.spec.js +++ b/tests/e2e/specs/html-snippet-block-conversion.spec.js @@ -43,6 +43,35 @@ const OMITTED_NOTICE = '.beehiiv-post-settings-notice__omitted'; const UNSUPPORTED_NOTICE = '.beehiiv-html-unsupported-notice'; const NEWSLETTER_ONLY_LABEL = '.beehiiv-newsletter-only-label'; +/** + * Returns, for each element matching `selector`, the position among the Custom + * HTML blocks of the block it belongs to. + * + * The label and the notice render just before their block, as siblings of the + * block element, not inside it. So each one belongs to the next Custom HTML + * block after it. + * + * @param {import('@playwright/test').FrameLocator} canvas Editor canvas. + * @param {string} selector CSS selector of the label or notice. + * @return {Promise} Block positions, in document order. + */ +async function ownersOf( canvas, selector ) { + return canvas.locator( selector ).evaluateAll( ( elements ) => + elements.map( ( element ) => { + const all = [ + ...element.ownerDocument.querySelectorAll( + '[data-type="core/html"]' + ), + ]; + let next = element.nextElementSibling; + while ( next && next.dataset.type !== 'core/html' ) { + next = next.nextElementSibling; + } + return all.indexOf( next ); + } ) + ); +} + const createdPosts = []; const b64 = ( value ) => @@ -539,15 +568,14 @@ test.describe( 'US-002: keep unsupported elements out of the newsletter', () => const message = 'Script and iframe elements are not included in the newsletter.'; + await expect( canvas.locator( UNSUPPORTED_NOTICE ) ).toHaveCount( 2 ); await expect( - blocks.nth( 0 ).locator( UNSUPPORTED_NOTICE ) + canvas.locator( UNSUPPORTED_NOTICE ).first() ).toContainText( message ); - await expect( - blocks.nth( 1 ).locator( UNSUPPORTED_NOTICE ) - ).toContainText( message ); - await expect( - blocks.nth( 2 ).locator( UNSUPPORTED_NOTICE ) - ).toHaveCount( 0 ); + // Blocks 1 and 2 hold a script and an iframe. Block 3 holds neither. + expect( await ownersOf( canvas, UNSUPPORTED_NOTICE ) ).toEqual( [ + 0, 1, + ] ); } ); } ); @@ -603,16 +631,29 @@ test.describe( 'US-003: send advertiser HTML to the newsletter only', () => { const toggle = page.getByRole( 'checkbox', { name: 'Newsletter only', } ); - const visible = await toggle - .waitFor( { state: 'visible', timeout: 3000 } ) - .then( () => true ) - .catch( () => false ); - if ( ! visible ) { - // Settings sidebar is closed or showing another panel. - await page - .getByRole( 'button', { name: 'Settings', exact: true } ) - .first() - .click(); + // Open the settings sidebar on the Block tab and its Settings sub-tab, + // where the option sits. Open it only if it is closed, so a click does not close it. + const settingsButton = page + .getByRole( 'button', { name: 'Settings', exact: true } ) + .first(); + if ( + ( await settingsButton.getAttribute( 'aria-pressed' ) ) !== 'true' + ) { + await settingsButton.click(); + } + const blockTab = page.getByRole( 'tab', { + name: 'Block', + exact: true, + } ); + if ( await blockTab.isVisible().catch( () => false ) ) { + await blockTab.click(); + } + const settingsTab = page.getByRole( 'tab', { + name: 'Settings', + exact: true, + } ); + if ( await settingsTab.isVisible().catch( () => false ) ) { + await settingsTab.click(); } await expect( toggle ).toBeVisible(); await expect( toggle ).not.toBeChecked(); @@ -714,12 +755,13 @@ test.describe( 'US-003: send advertiser HTML to the newsletter only', () => { const blocks = canvas.locator( '[data-type="core/html"]' ); await expect( blocks ).toHaveCount( 2 ); - await expect( - blocks.nth( 0 ).locator( NEWSLETTER_ONLY_LABEL ) - ).toHaveText( 'Newsletter only' ); - await expect( - blocks.nth( 1 ).locator( NEWSLETTER_ONLY_LABEL ) - ).toHaveCount( 0 ); + await expect( canvas.locator( NEWSLETTER_ONLY_LABEL ) ).toHaveText( + 'Newsletter only' + ); + // Only the first block has the option on. + expect( await ownersOf( canvas, NEWSLETTER_ONLY_LABEL ) ).toEqual( [ + 0, + ] ); // BR-007: the block is still shown in full so it can be edited. await expect( blocks.nth( 0 ) ).toBeVisible(); } ); @@ -850,17 +892,14 @@ test.describe( 'US-004: verify the full flow on a test post', () => { const canvas = page.frameLocator( 'iframe[name="editor-canvas"]' ); const editorBlocks = canvas.locator( '[data-type="core/html"]' ); await expect( editorBlocks ).toHaveCount( 2 ); - await expect( - editorBlocks.nth( 1 ).locator( NEWSLETTER_ONLY_LABEL ) - ).toHaveText( 'Newsletter only' ); - await expect( - editorBlocks.nth( 1 ).locator( UNSUPPORTED_NOTICE ) - ).toBeVisible(); - await expect( - editorBlocks.nth( 0 ).locator( NEWSLETTER_ONLY_LABEL ) - ).toHaveCount( 0 ); - await expect( - editorBlocks.nth( 0 ).locator( UNSUPPORTED_NOTICE ) - ).toHaveCount( 0 ); + await expect( canvas.locator( NEWSLETTER_ONLY_LABEL ) ).toHaveText( + 'Newsletter only' + ); + await expect( canvas.locator( UNSUPPORTED_NOTICE ) ).toBeVisible(); + // The label and the notice belong to the second block only. + expect( await ownersOf( canvas, NEWSLETTER_ONLY_LABEL ) ).toEqual( [ + 1, + ] ); + expect( await ownersOf( canvas, UNSUPPORTED_NOTICE ) ).toEqual( [ 1 ] ); } ); } );