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 `` elements are removed, + * because beehiiv HTML Snippets do not accept them. Nothing is added around the HTML and + * no visibility rule is set, so a snippet follows beehiiv's own default. + * + * @since 1.3.0 + */ +final class HtmlBlockConverter { + + /** + * Remove `'; +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( '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( canvas.locator( UNSUPPORTED_NOTICE ) ).toHaveCount( 2 ); + await expect( + canvas.locator( UNSUPPORTED_NOTICE ).first() + ).toContainText( message ); + // Blocks 1 and 2 hold a script and an iframe. Block 3 holds neither. + expect( await ownersOf( canvas, UNSUPPORTED_NOTICE ) ).toEqual( [ + 0, 1, + ] ); + } ); +} ); + +// --------------------------------------------------------------------------- +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', + } ); + // 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(); + + // 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( 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(); + } ); + + 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\nQA22_VISIBLE_TABLE'; + const linkedImage = + ''; + 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( 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 ] ); + } ); +} ); diff --git a/tests/phpunit/BlockConverterHtmlTest.php b/tests/phpunit/BlockConverterHtmlTest.php new file mode 100644 index 0000000..8c08885 --- /dev/null +++ b/tests/phpunit/BlockConverterHtmlTest.php @@ -0,0 +1,218 @@ +user->create( array( 'role' => 'administrator' ) ) ); + + update_option( + Config::OPTION_NAME, + array( + 'publication_id' => 'pub_test', + 'post_template_id' => 'tmpl_test', + ) + ); + } + + /** + * Build a paragraph block's markup. + * + * @param string $text Paragraph text. + * @return string + */ + private function paragraph( string $text ): string { + return "\n{$text}\n"; + } + + /** + * Build a Custom HTML block's markup. + * + * @param string $html Block HTML. + * @param bool $newsletter_only Whether the block is newsletter only. + * @return string + */ + private function html_block( string $html, bool $newsletter_only = false ): string { + $attrs = $newsletter_only ? ' {"beehiivNewsletterOnly":true}' : ''; + + return "\n{$html}\n"; + } + + /** + * Create a published post with the given content. + * + * @param string $content Block markup. + * @return WP_Post + */ + private function create_post( string $content ): WP_Post { + $post_id = self::factory()->post->create( + array( + 'post_title' => 'HTML post', + 'post_status' => 'publish', + 'post_content' => $content, + ) + ); + + return get_post( $post_id ); + } + + /** + * AC-001, AC-002, AC-003: each Custom HTML block is one snippet, in order, with the HTML as written. + */ + public function test_each_html_block_becomes_one_snippet_in_order(): void { + $first = 'A'; + $second = ''; + $post = $this->create_post( + $this->paragraph( 'Before' ) + . $this->html_block( $first ) + . $this->paragraph( 'Middle' ) + . $this->html_block( $second ) + ); + + $blocks = BlockConverter::convert_supported_blocks( $post ); + + $this->assertSame( array( 'paragraph', 'html', 'paragraph', 'html' ), array_column( $blocks, 'type' ) ); + $this->assertSame( $first, $blocks[1]['html'] ); + $this->assertSame( $second, $blocks[3]['html'] ); + } + + /** + * AC-004: an empty or whitespace-only block sends no snippet. + */ + public function test_empty_html_block_sends_no_snippet(): void { + $post = $this->create_post( $this->html_block( ' ' ) . $this->paragraph( 'Text' ) ); + $blocks = BlockConverter::convert_supported_blocks( $post ); + + $this->assertSame( array( 'paragraph' ), array_column( $blocks, 'type' ) ); + } + + /** + * AC-005: a Custom HTML block inside a Group stays inside the section. + */ + public function test_html_block_inside_group_stays_in_the_section(): void { + $group = "\n" + . $this->paragraph( 'In' ) . $this->html_block( 'Snippet' ) + . "\n"; + $post = $this->create_post( $group ); + + $blocks = BlockConverter::convert_supported_blocks( $post, true ); + + $this->assertSame( array( 'section' ), array_column( $blocks, 'type' ) ); + $this->assertSame( array( 'paragraph', 'html' ), array_column( $blocks[0]['blocks'], 'type' ) ); + } + + /** + * AC-006: a Custom HTML block inside Columns is sent right after the columns block. + */ + public function test_html_block_inside_columns_follows_the_columns_block(): void { + $columns = "\n" + . "\n" + . $this->paragraph( 'Col' ) . $this->html_block( 'Snippet' ) + . "\n\n"; + $post = $this->create_post( $columns ); + + $blocks = BlockConverter::convert_supported_blocks( $post ); + + $this->assertSame( array( 'columns', 'html' ), array_column( $blocks, 'type' ) ); + $this->assertSame( 'Snippet', $blocks[1]['html'] ); + $this->assertSame( array( 'paragraph' ), array_column( $blocks[0]['columns'][0]['blocks'], 'type' ) ); + } + + /** + * AC-009, AC-010, AC-011: script and iframe elements are removed, and a block of only those sends nothing. + */ + public function test_script_and_iframe_elements_are_removed(): void { + $post = $this->create_post( + $this->html_block( 'Keep' ) + . $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 ) + ); + } +}
QA_AFTER_SCRIPT
QA_NOTICE_SCRIPT
{$text}
Snippet
Keep
Ad
Visible block
Newsletter ad