From 835fb74ebfdce88d7c65f796b28eca5b94c58444 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Tue, 11 Aug 2026 15:06:50 -0500 Subject: [PATCH] fix: harden CHRNX editor lifecycle --- assets/js/editor-podcast.js | 36 +++--- assets/js/editor-taxonomies.js | 31 +++-- inc/editor.php | 7 +- inc/podcast-meta.php | 18 ++- inc/taxonomies.php | 185 +++++++++++++++++++++------- package.json | 2 +- tests/e2e/editorial-editor.spec.mjs | 54 ++++++++ tests/js/editor-podcast.test.js | 34 ++++- tests/js/editor-taxonomies.test.js | 47 +++++-- tests/php/EditorAssetsTest.php | 3 +- tests/php/PodcastMetaTest.php | 19 ++- tests/php/TaxonomiesTest.php | 171 +++++++++++++++++++++++++ 12 files changed, 512 insertions(+), 95 deletions(-) create mode 100644 tests/e2e/editorial-editor.spec.mjs diff --git a/assets/js/editor-podcast.js b/assets/js/editor-podcast.js index 113660b..db40ecf 100644 --- a/assets/js/editor-podcast.js +++ b/assets/js/editor-podcast.js @@ -7,13 +7,25 @@ } )( function () { 'use strict'; + const maxParticipants = 50; + const maxParticipantLength = 100; + + function getTranslator( wp ) { + return wp.i18n && typeof wp.i18n.__ === 'function' + ? wp.i18n.__ + : function ( text ) { + return text; + }; + } + function participantsFromText( value ) { return String( value || '' ) .split( /\r?\n/ ) .map( function ( name ) { - return name.trim(); + return Array.from( name.trim() ).slice( 0, maxParticipantLength ).join( '' ); } ) - .filter( Boolean ); + .filter( Boolean ) + .slice( 0, maxParticipants ); } function participantsToText( value ) { @@ -53,15 +65,7 @@ return false; } - const editor = wp.data.select( 'core/editor' ); - if ( - ! editor || - typeof editor.getCurrentPostType !== 'function' || - typeof editor.getEditedPostAttribute !== 'function' || - editor.getCurrentPostType() !== 'post' - ) { - return false; - } + const __ = getTranslator( wp ); function PodcastPanel() { const editorState = wp.data.useSelect( function ( select ) { @@ -107,9 +111,9 @@ return wp.element.createElement( wp.editPost.PluginDocumentSettingPanel, - { name: 'chrnx-podcast', title: 'Podcast episode' }, + { name: 'chrnx-podcast', title: __( 'Podcast episode', 'chrnx' ) }, wp.element.createElement( wp.components.TextControl, { - label: 'Episode number', + label: __( 'Episode number', 'chrnx' ), type: 'number', min: 0, value: meta.chrnx_episode_number ?? '', @@ -122,21 +126,21 @@ }, } ), wp.element.createElement( wp.components.TextControl, { - label: 'Duration', + label: __( 'Duration', 'chrnx' ), value: meta.chrnx_episode_duration || '', onChange( value ) { setMeta( 'chrnx_episode_duration', value ); }, } ), wp.element.createElement( wp.components.TextareaControl, { - label: 'Participants (one per line)', + label: __( 'Participants (one per line)', 'chrnx' ), value: participantsToText( meta.chrnx_episode_participants ), onChange( value ) { setMeta( 'chrnx_episode_participants', participantsFromText( value ) ); }, } ), wp.element.createElement( wp.components.TextControl, { - label: 'Canonical episode URL', + label: __( 'Canonical episode URL', 'chrnx' ), type: 'url', value: meta.canonical_episode_url || '', onChange( value ) { diff --git a/assets/js/editor-taxonomies.js b/assets/js/editor-taxonomies.js index 637ab5e..bfb49bc 100644 --- a/assets/js/editor-taxonomies.js +++ b/assets/js/editor-taxonomies.js @@ -13,6 +13,14 @@ { name: 'chrnx_show', restBase: 'show', title: 'Show' }, ]; + function getTranslator( wp ) { + return wp.i18n && typeof wp.i18n.__ === 'function' + ? wp.i18n.__ + : function ( text ) { + return text; + }; + } + function orderTerms( terms ) { if ( ! Array.isArray( terms ) ) { return []; @@ -57,15 +65,12 @@ return false; } - const editor = wp.data.select( 'core/editor' ); - if ( - ! editor || - typeof editor.getCurrentPostType !== 'function' || - typeof editor.getEditedPostAttribute !== 'function' || - editor.getCurrentPostType() !== 'post' - ) { - return false; - } + const __ = getTranslator( wp ); + const titles = { + chrnx_topic: __( 'Topic', 'chrnx' ), + chrnx_language: __( 'Language', 'chrnx' ), + chrnx_show: __( 'Show', 'chrnx' ), + }; const panelDispatch = wp.data.dispatch( 'core/edit-post' ); if ( panelDispatch && typeof panelDispatch.removeEditorPanel === 'function' ) { @@ -98,7 +103,7 @@ return { selected: currentEditor.getEditedPostAttribute( taxonomy.restBase ), terms: core.getEntityRecords( 'taxonomy', taxonomy.name, { - per_page: -1, + per_page: 100, orderby: 'name', order: 'asc', } ), @@ -118,7 +123,7 @@ } const selected = editorState.taxonomies[ index ].selected; - const options = [ { label: 'Not set', value: '' } ].concat( + const options = [ { label: __( 'Not set', 'chrnx' ), value: '' } ].concat( terms.map( function ( term ) { return { label: term.name, value: String( term.id ) }; } ), @@ -129,10 +134,10 @@ { key: taxonomy.name, name: 'chrnx-' + taxonomy.restBase, - title: taxonomy.title, + title: titles[ taxonomy.name ], }, wp.element.createElement( wp.components.RadioControl, { - label: taxonomy.title, + label: titles[ taxonomy.name ], selected: Array.isArray( selected ) && selected.length ? String( selected[ 0 ] ) : '', options, onChange( value ) { diff --git a/inc/editor.php b/inc/editor.php index 3a76451..4880d24 100644 --- a/inc/editor.php +++ b/inc/editor.php @@ -32,7 +32,7 @@ function chrnx_enqueue_editor_assets() { wp_enqueue_script( 'chrnx-editor-taxonomies', get_theme_file_uri( 'assets/js/editor-taxonomies.js' ), - array( 'wp-components', 'wp-core-data', 'wp-data', 'wp-edit-post', 'wp-element', 'wp-plugins' ), + array( 'wp-components', 'wp-core-data', 'wp-data', 'wp-edit-post', 'wp-element', 'wp-i18n', 'wp-plugins' ), CHRNX_VERSION, true ); @@ -40,9 +40,12 @@ function chrnx_enqueue_editor_assets() { wp_enqueue_script( 'chrnx-editor-podcast', get_theme_file_uri( 'assets/js/editor-podcast.js' ), - array( 'wp-components', 'wp-core-data', 'wp-data', 'wp-edit-post', 'wp-element', 'wp-plugins' ), + array( 'wp-components', 'wp-core-data', 'wp-data', 'wp-edit-post', 'wp-element', 'wp-i18n', 'wp-plugins' ), CHRNX_VERSION, true ); + + wp_set_script_translations( 'chrnx-editor-taxonomies', 'chrnx', get_theme_file_path( 'languages' ) ); + wp_set_script_translations( 'chrnx-editor-podcast', 'chrnx', get_theme_file_path( 'languages' ) ); } add_action( 'enqueue_block_editor_assets', 'chrnx_enqueue_editor_assets' ); diff --git a/inc/podcast-meta.php b/inc/podcast-meta.php index badfd63..6dcecfe 100644 --- a/inc/podcast-meta.php +++ b/inc/podcast-meta.php @@ -5,6 +5,9 @@ * @package CHRNX */ +define( 'CHRNX_MAX_EPISODE_PARTICIPANTS', 50 ); +define( 'CHRNX_MAX_EPISODE_PARTICIPANT_LENGTH', 100 ); + /** * Sanitize an episode number. * @@ -39,7 +42,7 @@ function chrnx_sanitize_episode_duration( $value ) { * Sanitize participant names while preserving their order. * * @param mixed $value Submitted value. - * @return string[] Sanitized participant names. + * @return string[] Up to 50 sanitized names of up to 100 Unicode characters each. */ function chrnx_sanitize_episode_participants( $value ) { if ( ! is_array( $value ) ) { @@ -48,11 +51,16 @@ function chrnx_sanitize_episode_participants( $value ) { $participants = array(); foreach ( $value as $participant ) { + if ( count( $participants ) >= CHRNX_MAX_EPISODE_PARTICIPANTS ) { + break; + } + if ( ! is_scalar( $participant ) ) { continue; } $name = trim( sanitize_text_field( (string) $participant ) ); + $name = mb_substr( $name, 0, CHRNX_MAX_EPISODE_PARTICIPANT_LENGTH, 'UTF-8' ); if ( '' !== $name ) { $participants[] = $name; } @@ -113,8 +121,12 @@ function chrnx_register_podcast_meta() { 'type' => 'array', 'sanitize_callback' => 'chrnx_sanitize_episode_participants', 'schema' => array( - 'type' => 'array', - 'items' => array( 'type' => 'string' ), + 'type' => 'array', + 'maxItems' => CHRNX_MAX_EPISODE_PARTICIPANTS, + 'items' => array( + 'type' => 'string', + 'maxLength' => CHRNX_MAX_EPISODE_PARTICIPANT_LENGTH, + ), ), ), 'canonical_episode_url' => array( diff --git a/inc/taxonomies.php b/inc/taxonomies.php index 98cf178..bbdf96e 100644 --- a/inc/taxonomies.php +++ b/inc/taxonomies.php @@ -13,34 +13,34 @@ function chrnx_get_editorial_taxonomies() { return array( 'chrnx_topic' => array( - 'singular' => 'Topic', - 'plural' => 'Topics', + 'singular' => __( 'Topic', 'chrnx' ), + 'plural' => __( 'Topics', 'chrnx' ), 'rest_base' => 'topic', 'terms' => array( - 'research' => 'Research', - 'code' => 'Code', - 'literature' => 'Literature', - 'music' => 'Music', - 'podcasts' => 'Podcasts', - 'life' => 'Life', - 'gaming' => 'Gaming', + 'research' => __( 'Research', 'chrnx' ), + 'code' => __( 'Code', 'chrnx' ), + 'literature' => __( 'Literature', 'chrnx' ), + 'music' => __( 'Music', 'chrnx' ), + 'podcasts' => __( 'Podcasts', 'chrnx' ), + 'life' => __( 'Life', 'chrnx' ), + 'gaming' => __( 'Gaming', 'chrnx' ), ), ), 'chrnx_language' => array( - 'singular' => 'Language', - 'plural' => 'Languages', + 'singular' => __( 'Language', 'chrnx' ), + 'plural' => __( 'Languages', 'chrnx' ), 'rest_base' => 'language', 'terms' => array( - 'en' => 'English', - 'es' => 'Español', + 'en' => __( 'English', 'chrnx' ), + 'es' => __( 'Español', 'chrnx' ), ), ), 'chrnx_show' => array( - 'singular' => 'Show', - 'plural' => 'Shows', + 'singular' => __( 'Show', 'chrnx' ), + 'plural' => __( 'Shows', 'chrnx' ), 'rest_base' => 'show', 'terms' => array( - 'silicon-ranch' => 'Silicon Ranch', + 'silicon-ranch' => __( 'Silicon Ranch', 'chrnx' ), ), ), ); @@ -92,7 +92,10 @@ function chrnx_seed_editorial_terms() { foreach ( $definition['terms'] as $slug => $name ) { if ( ! term_exists( $slug, $taxonomy_name ) ) { - wp_insert_term( $name, $taxonomy_name, array( 'slug' => $slug ) ); + $result = wp_insert_term( $name, $taxonomy_name, array( 'slug' => $slug ) ); + if ( is_wp_error( $result ) || false === $result ) { + chrnx_store_editorial_notice( '', 'vocabulary_setup_failed' ); + } } } } @@ -100,24 +103,94 @@ function chrnx_seed_editorial_terms() { add_action( 'after_switch_theme', 'chrnx_seed_editorial_terms' ); /** - * Add or read request-local normalization notices. + * Return the current user's editorial notice transient key. * - * @param string $taxonomy_name Optional taxonomy name to add. - * @return string[] Taxonomies normalized during this request. + * @return string User-scoped transient key. */ -function chrnx_editorial_taxonomy_notices( $taxonomy_name = '' ) { - static $notices = array(); - $supported = array_keys( chrnx_get_editorial_taxonomies() ); - - if ( in_array( $taxonomy_name, $supported, true ) ) { - $notices[ $taxonomy_name ] = $taxonomy_name; - } - - return array_values( $notices ); +function chrnx_editorial_notice_key() { + return 'chrnx_editorial_notices_' . get_current_user_id(); } /** - * Enforce one editorial term per taxonomy. + * Store a generic, allowlisted editorial notice for the current user. + * + * @param string $taxonomy_name Supported taxonomy or empty for setup status. + * @param string $status Allowlisted status. + */ +function chrnx_store_editorial_notice( $taxonomy_name, $status ) { + $supported_taxonomies = array_keys( chrnx_get_editorial_taxonomies() ); + $allowed_statuses = array( 'normalized', 'normalization_failed', 'vocabulary_setup_failed' ); + + if ( ! in_array( $status, $allowed_statuses, true ) ) { + return; + } + + if ( 'vocabulary_setup_failed' === $status ) { + $taxonomy_name = ''; + } elseif ( ! in_array( $taxonomy_name, $supported_taxonomies, true ) ) { + return; + } + + $key = chrnx_editorial_notice_key(); + $notices = get_transient( $key ); + if ( ! is_array( $notices ) ) { + $notices = array(); + } + + $notice_key = $status . ':' . $taxonomy_name; + $notices[ $notice_key ] = array( + 'status' => $status, + 'taxonomy' => $taxonomy_name, + ); + set_transient( $key, $notices, 5 * MINUTE_IN_SECONDS ); +} + +/** + * Consume valid notices for the current user. + * + * @return array> Valid one-time notices. + */ +function chrnx_consume_editorial_notices() { + $key = chrnx_editorial_notice_key(); + $notices = get_transient( $key ); + delete_transient( $key ); + + if ( ! is_array( $notices ) ) { + return array(); + } + + $supported_taxonomies = array_keys( chrnx_get_editorial_taxonomies() ); + $allowed_statuses = array( 'normalized', 'normalization_failed', 'vocabulary_setup_failed' ); + $valid = array(); + foreach ( $notices as $notice ) { + if ( ! is_array( $notice ) || ! isset( $notice['status'], $notice['taxonomy'] ) ) { + continue; + } + if ( ! in_array( $notice['status'], $allowed_statuses, true ) ) { + continue; + } + if ( 'vocabulary_setup_failed' !== $notice['status'] && ! in_array( $notice['taxonomy'], $supported_taxonomies, true ) ) { + continue; + } + $valid[] = $notice; + } + + return $valid; +} + +/** + * Record a corrective assignment outcome without exposing its details. + * + * @param string $taxonomy_name Supported taxonomy. + * @param array|WP_Error|false $result Corrective assignment result. + */ +function chrnx_record_editorial_normalization_result( $taxonomy_name, $result ) { + $status = is_array( $result ) ? 'normalized' : 'normalization_failed'; + chrnx_store_editorial_notice( $taxonomy_name, $status ); +} + +/** + * Enforce one editorial term per taxonomy and object. * * @param int $object_id Object ID. * @param mixed $terms Assigned terms. @@ -127,8 +200,9 @@ function chrnx_editorial_taxonomy_notices( $taxonomy_name = '' ) { function chrnx_normalize_editorial_taxonomy_terms( $object_id, $terms, $term_taxonomy_ids, $taxonomy_name ) { static $normalizing = array(); $supported = array_keys( chrnx_get_editorial_taxonomies() ); + $guard_key = $taxonomy_name . ':' . absint( $object_id ); - if ( ! in_array( $taxonomy_name, $supported, true ) || ! empty( $normalizing[ $taxonomy_name ] ) ) { + if ( ! in_array( $taxonomy_name, $supported, true ) || ! empty( $normalizing[ $guard_key ] ) ) { return; } @@ -140,32 +214,51 @@ function chrnx_normalize_editorial_taxonomy_terms( $object_id, $terms, $term_tax $term_ids = array_map( 'absint', $term_ids ); sort( $term_ids, SORT_NUMERIC ); - $normalizing[ $taxonomy_name ] = true; - wp_set_object_terms( $object_id, array( $term_ids[0] ), $taxonomy_name, false ); - unset( $normalizing[ $taxonomy_name ] ); - - chrnx_editorial_taxonomy_notices( $taxonomy_name ); + $normalizing[ $guard_key ] = true; + try { + $result = wp_set_object_terms( $object_id, array( $term_ids[0] ), $taxonomy_name, false ); + chrnx_record_editorial_normalization_result( $taxonomy_name, $result ); + } catch ( Throwable $exception ) { + chrnx_store_editorial_notice( $taxonomy_name, 'normalization_failed' ); + throw $exception; + } finally { + unset( $normalizing[ $guard_key ] ); + } } add_action( 'set_object_terms', 'chrnx_normalize_editorial_taxonomy_terms', 10, 4 ); /** - * Display a concise request-local normalization notice. + * Display and consume concise user-scoped editorial notices. */ function chrnx_editorial_taxonomy_admin_notice() { $definitions = chrnx_get_editorial_taxonomies(); - foreach ( chrnx_editorial_taxonomy_notices() as $taxonomy_name ) { - if ( ! isset( $definitions[ $taxonomy_name ] ) ) { + foreach ( chrnx_consume_editorial_notices() as $notice ) { + $status = $notice['status']; + $taxonomy_name = $notice['taxonomy']; + $class_name = 'notice-info'; + + if ( 'vocabulary_setup_failed' === $status ) { + $message = __( 'Editorial vocabulary setup was incomplete. Please reactivate the theme or contact an administrator.', 'chrnx' ); + $class_name = 'notice-error'; + } elseif ( isset( $definitions[ $taxonomy_name ] ) && 'normalization_failed' === $status ) { + $message = sprintf( + /* translators: %s: taxonomy singular label. */ + __( 'The %s value could not be normalized. Please try again.', 'chrnx' ), + $definitions[ $taxonomy_name ]['singular'] + ); + $class_name = 'notice-error'; + } elseif ( isset( $definitions[ $taxonomy_name ] ) && 'normalized' === $status ) { + $message = sprintf( + /* translators: %s: taxonomy singular label. */ + __( '%s supports one value. The lowest existing term was kept.', 'chrnx' ), + $definitions[ $taxonomy_name ]['singular'] + ); + } else { continue; } - - $message = sprintf( - /* translators: %s: taxonomy singular label. */ - __( '%s supports one value. The lowest existing term was kept.', 'chrnx' ), - $definitions[ $taxonomy_name ]['singular'] - ); ?> -

+

{ + execFileSync( + 'npm', + [ 'exec', '--', 'wp-env', 'run', 'cli', 'wp', 'eval', 'chrnx_seed_editorial_terms();' ], + { cwd: process.cwd(), env: process.env, stdio: 'inherit' }, + ); +} ); + +test( 'editorial and podcast controls initialize in the real post editor', async ( { page } ) => { + const openPanel = async ( name ) => { + const button = page.getByRole( 'button', { name, exact: true } ); + if ( ( await button.getAttribute( 'aria-expanded' ) ) !== 'true' ) { + await button.click(); + } + }; + + await page.goto( '/wp-login.php' ); + await page.locator( '#user_login' ).fill( 'admin' ); + await page.locator( '#user_pass' ).fill( 'password' ); + await Promise.all( [ + page.waitForURL( /\/wp-admin\// ), + page.getByRole( 'button', { name: /log in/i } ).click(), + ] ); + + await page.goto( '/wp-admin/post-new.php' ); + const welcomeDialog = page.getByRole( 'dialog', { name: 'Welcome to the editor' } ); + if ( await welcomeDialog.isVisible() ) { + await welcomeDialog.getByRole( 'button', { name: 'Close' } ).click(); + } + await expect( page.getByRole( 'heading', { name: 'Add Post', exact: true } ) ).toBeVisible(); + + const podcasts = page.getByRole( 'radio', { name: 'Podcasts', exact: true } ); + const settings = page.getByRole( 'button', { name: /^settings$/i } ).last(); + if ( ( await settings.getAttribute( 'aria-expanded' ) ) !== 'true' ) { + await settings.click(); + } + + await openPanel( 'Topic' ); + await expect( podcasts ).toBeVisible(); + await openPanel( 'Language' ); + await expect( page.getByRole( 'radio', { name: 'English', exact: true } ) ).toBeVisible(); + await openPanel( 'Show' ); + await expect( page.getByRole( 'radio', { name: 'Silicon Ranch', exact: true } ) ).toBeVisible(); + + await podcasts.check(); + await openPanel( 'Podcast episode' ); + await expect( page.getByLabel( 'Episode number', { exact: true } ) ).toBeVisible(); + await expect( page.getByLabel( 'Duration', { exact: true } ) ).toBeVisible(); + await expect( page.getByLabel( 'Participants (one per line)', { exact: true } ) ).toBeVisible(); + await expect( page.getByLabel( 'Canonical episode URL', { exact: true } ) ).toBeVisible(); +} ); diff --git a/tests/js/editor-podcast.test.js b/tests/js/editor-podcast.test.js index 49a4cd1..fe635fe 100644 --- a/tests/js/editor-podcast.test.js +++ b/tests/js/editor-podcast.test.js @@ -18,6 +18,7 @@ function createWp( topicSlug = 'podcasts' ) { }; const wp = { components: { TextControl: 'TextControl', TextareaControl: 'TextareaControl' }, + i18n: { __: jest.fn( ( text ) => text ) }, data: { select: ( store ) => { if ( store === 'core/editor' ) { @@ -55,6 +56,19 @@ describe( 'podcast editor helpers', () => { ); } ); + test( 'bounds participant transport to 50 names and 100 Unicode characters each', () => { + const helpers = require( modulePath ); + const longUnicodeName = 'ñ'.repeat( 101 ); + const lines = [ longUnicodeName ].concat( + Array.from( { length: 55 }, ( _value, index ) => `Guest ${ index }` ), + ); + const participants = helpers.participantsFromText( lines.join( '\n' ) ); + + expect( participants ).toHaveLength( 50 ); + expect( Array.from( participants[ 0 ] ) ).toHaveLength( 100 ); + expect( participants[ 0 ] ).toBe( 'ñ'.repeat( 100 ) ); + } ); + test( 'updates one meta key while preserving unrelated metadata', () => { const helpers = require( modulePath ); const editPost = jest.fn(); @@ -93,7 +107,7 @@ describe( 'podcast editor helpers', () => { expect( nonPodcast.registerPlugin.mock.calls[ 0 ][ 1 ].render() ).toBeNull(); } ); - test( 'fails closed when required globals or initial editor selector methods are missing', () => { + test( 'registers immediately while initial editor selectors are unresolved', () => { const helpers = require( modulePath ); expect( helpers.initialize() ).toBe( false ); expect( helpers.initialize( {} ) ).toBe( false ); @@ -102,8 +116,8 @@ describe( 'podcast editor helpers', () => { const missingEditorMethod = createWp(); missingEditorMethod.wp.data.select = () => editorSelector; expect( () => helpers.initialize( missingEditorMethod.wp ) ).not.toThrow(); - expect( helpers.initialize( missingEditorMethod.wp ) ).toBe( false ); - expect( missingEditorMethod.registerPlugin ).not.toHaveBeenCalled(); + expect( helpers.initialize( missingEditorMethod.wp ) ).toBe( true ); + expect( missingEditorMethod.registerPlugin ).toHaveBeenCalledTimes( 2 ); expect( missingEditorMethod.editPost ).not.toHaveBeenCalled(); } @@ -152,4 +166,18 @@ describe( 'podcast editor helpers', () => { expect( unresolved.registerPlugin.mock.calls[ 0 ][ 1 ].render() ).toBeNull(); expect( unresolved.editPost ).not.toHaveBeenCalled(); } ); + + test( 'localizes podcast controls with the CHRNX text domain', () => { + const helpers = require( modulePath ); + const { wp, registerPlugin } = createWp(); + wp.i18n.__ = jest.fn( ( text, domain ) => `${ domain }:${ text }` ); + + helpers.initialize( wp ); + const tree = registerPlugin.mock.calls[ 0 ][ 1 ].render(); + expect( tree.props.title ).toBe( 'chrnx:Podcast episode' ); + expect( flatten( tree ).find( ( node ) => node.type === 'TextControl' ).props.label ).toBe( + 'chrnx:Episode number', + ); + expect( wp.i18n.__ ).toHaveBeenCalledWith( 'Podcast episode', 'chrnx' ); + } ); } ); diff --git a/tests/js/editor-taxonomies.test.js b/tests/js/editor-taxonomies.test.js index ffd2c3a..13af16d 100644 --- a/tests/js/editor-taxonomies.test.js +++ b/tests/js/editor-taxonomies.test.js @@ -14,9 +14,11 @@ function createWp( overrides = {} ) { chrnx_language: [ { id: 4, name: 'English' } ], chrnx_show: [ { id: 7, name: 'Silicon Ranch' } ], }; + const getEntityRecords = jest.fn( ( _kind, name ) => terms[ name ] ); const attributes = { type: 'post', topic: [ 3 ], language: [], show: [] }; const wp = { components: { RadioControl: 'RadioControl' }, + i18n: { __: jest.fn( ( text ) => text ) }, compose: { compose: ( ...funcs ) => @@ -31,7 +33,7 @@ function createWp( overrides = {} ) { getEditedPostAttribute: ( key ) => attributes[ key ], }; } - return { getEntityRecords: ( _kind, name ) => terms[ name ] }; + return { getEntityRecords }; }, dispatch: ( store ) => ( store === 'core/editor' ? { editPost } : {} ), useDispatch, @@ -48,7 +50,16 @@ function createWp( overrides = {} ) { plugins: { registerPlugin }, ...overrides, }; - return { wp, editPost, removeEditorPanel, registerPlugin, attributes, terms, useSelect }; + return { + wp, + editPost, + getEntityRecords, + removeEditorPanel, + registerPlugin, + attributes, + terms, + useSelect, + }; } describe( 'editor taxonomy helpers', () => { @@ -71,7 +82,7 @@ describe( 'editor taxonomy helpers', () => { test( 'removes native panels and registers three radio setting panels', () => { const helpers = require( modulePath ); - const { wp, removeEditorPanel, registerPlugin, useSelect } = createWp(); + const { wp, getEntityRecords, removeEditorPanel, registerPlugin, useSelect } = createWp(); wp.data.dispatch = ( store ) => store === 'core/edit-post' ? { removeEditorPanel } : { editPost: jest.fn() }; @@ -81,13 +92,18 @@ describe( 'editor taxonomy helpers', () => { const tree = registerPlugin.mock.calls[ 0 ][ 1 ].render(); expect( useSelect ).toHaveBeenCalled(); expect( tree.children ).toHaveLength( 3 ); + expect( getEntityRecords ).toHaveBeenCalledWith( 'taxonomy', 'chrnx_topic', { + per_page: 100, + orderby: 'name', + order: 'asc', + } ); tree.children.forEach( ( panel ) => { expect( panel.type ).toBe( 'PluginDocumentSettingPanel' ); expect( panel.children[ 0 ].type ).toBe( 'RadioControl' ); } ); } ); - test( 'fails closed when required globals or initial editor selector methods are missing', () => { + test( 'registers immediately while initial editor selectors are unresolved', () => { const helpers = require( modulePath ); expect( helpers.initialize() ).toBe( false ); expect( helpers.initialize( {} ) ).toBe( false ); @@ -96,8 +112,8 @@ describe( 'editor taxonomy helpers', () => { const missingEditorMethod = createWp(); missingEditorMethod.wp.data.select = () => editorSelector; expect( () => helpers.initialize( missingEditorMethod.wp ) ).not.toThrow(); - expect( helpers.initialize( missingEditorMethod.wp ) ).toBe( false ); - expect( missingEditorMethod.registerPlugin ).not.toHaveBeenCalled(); + expect( helpers.initialize( missingEditorMethod.wp ) ).toBe( true ); + expect( missingEditorMethod.registerPlugin ).toHaveBeenCalledTimes( 2 ); expect( missingEditorMethod.editPost ).not.toHaveBeenCalled(); } @@ -140,11 +156,24 @@ describe( 'editor taxonomy helpers', () => { expect( editPost ).not.toHaveBeenCalled(); } ); - test( 'does not register taxonomy panels outside post editors', () => { + test( 'registers safely but renders no taxonomy panels outside post editors', () => { const helpers = require( modulePath ); const { wp, registerPlugin, attributes } = createWp(); attributes.type = 'page'; - expect( helpers.initialize( wp ) ).toBe( false ); - expect( registerPlugin ).not.toHaveBeenCalled(); + expect( helpers.initialize( wp ) ).toBe( true ); + expect( registerPlugin ).toHaveBeenCalledTimes( 1 ); + expect( registerPlugin.mock.calls[ 0 ][ 1 ].render() ).toBeNull(); + } ); + + test( 'localizes taxonomy editor labels with the CHRNX text domain', () => { + const helpers = require( modulePath ); + const { wp, registerPlugin } = createWp(); + wp.i18n.__ = jest.fn( ( text, domain ) => `${ domain }:${ text }` ); + + helpers.initialize( wp ); + const tree = registerPlugin.mock.calls[ 0 ][ 1 ].render(); + expect( tree.children[ 0 ].props.title ).toBe( 'chrnx:Topic' ); + expect( tree.children[ 0 ].children[ 0 ].props.options[ 0 ].label ).toBe( 'chrnx:Not set' ); + expect( wp.i18n.__ ).toHaveBeenCalledWith( 'Topic', 'chrnx' ); } ); } ); diff --git a/tests/php/EditorAssetsTest.php b/tests/php/EditorAssetsTest.php index dca0b39..f25f1f3 100644 --- a/tests/php/EditorAssetsTest.php +++ b/tests/php/EditorAssetsTest.php @@ -84,7 +84,7 @@ class EditorAssetsTest extends WP_UnitTestCase { ); $this->assertSame( array( 'chrnx-editor-taxonomies', 'chrnx-editor-podcast' ), $handles ); - $expected_dependencies = array( 'wp-components', 'wp-core-data', 'wp-data', 'wp-edit-post', 'wp-element', 'wp-plugins' ); + $expected_dependencies = array( 'wp-components', 'wp-core-data', 'wp-data', 'wp-edit-post', 'wp-element', 'wp-i18n', 'wp-plugins' ); foreach ( array( @@ -96,6 +96,7 @@ class EditorAssetsTest extends WP_UnitTestCase { $this->assertSame( get_theme_file_uri( $asset ), $scripts->registered[ $handle ]->src ); $this->assertSame( $expected_dependencies, $scripts->registered[ $handle ]->deps ); $this->assertSame( CHRNX_VERSION, $scripts->registered[ $handle ]->ver ); + $this->assertSame( 'chrnx', $scripts->registered[ $handle ]->textdomain ); } } diff --git a/tests/php/PodcastMetaTest.php b/tests/php/PodcastMetaTest.php index 5ab22a1..50ce727 100644 --- a/tests/php/PodcastMetaTest.php +++ b/tests/php/PodcastMetaTest.php @@ -27,10 +27,14 @@ class PodcastMetaTest extends WP_UnitTestCase { $this->assertSame( 0, $registered['chrnx_episode_number']['show_in_rest']['schema']['minimum'] ); $this->assertSame( 'string', $registered['chrnx_episode_duration']['show_in_rest']['schema']['type'] ); $this->assertSame( - array( 'type' => 'string' ), + array( + 'type' => 'string', + 'maxLength' => 100, + ), $registered['chrnx_episode_participants']['show_in_rest']['schema']['items'] ); $this->assertSame( 'array', $registered['chrnx_episode_participants']['show_in_rest']['schema']['type'] ); + $this->assertSame( 50, $registered['chrnx_episode_participants']['show_in_rest']['schema']['maxItems'] ); $this->assertSame( 'string', $registered['canonical_episode_url']['show_in_rest']['schema']['type'] ); $this->assertArrayNotHasKey( 'chrnx_buzzsprout_embed', $registered ); $this->assertArrayNotHasKey( 'chrnx_episode_player', $registered ); @@ -78,6 +82,19 @@ class PodcastMetaTest extends WP_UnitTestCase { $this->assertSame( array(), chrnx_sanitize_episode_participants( 'Ada Example' ) ); } + /** + * Participant bounds preserve Unicode and intentional order. + */ + public function test_participants_are_bounded_by_count_and_unicode_length() { + $long_name = str_repeat( 'ñ', 101 ); + $input = array_merge( array( $long_name ), array_fill( 0, 55, 'Guest' ) ); + $actual = chrnx_sanitize_episode_participants( $input ); + + $this->assertCount( 50, $actual ); + $this->assertSame( str_repeat( 'ñ', 100 ), $actual[0] ); + $this->assertSame( 100, mb_strlen( $actual[0], 'UTF-8' ) ); + } + /** * Canonical URLs allow HTTPS only. */ diff --git a/tests/php/TaxonomiesTest.php b/tests/php/TaxonomiesTest.php index 87b2d15..08e489b 100644 --- a/tests/php/TaxonomiesTest.php +++ b/tests/php/TaxonomiesTest.php @@ -22,6 +22,7 @@ class TaxonomiesTest extends WP_UnitTestCase { public function set_up() { parent::set_up(); do_action( 'init' ); + wp_set_current_user( 0 ); $this->definitions = array( 'chrnx_topic' => array( 'rest_base' => 'topic', @@ -161,5 +162,175 @@ class TaxonomiesTest extends WP_UnitTestCase { $this->assertStringContainsString( 'Topic', $notice ); $this->assertStringNotContainsString( 'Zulu', $notice ); $this->assertStringNotContainsString( 'Alpha', $notice ); + + ob_start(); + chrnx_editorial_taxonomy_admin_notice(); + $this->assertSame( '', ob_get_clean(), 'The notice should be consumed after one render.' ); + } + + /** + * A nested assignment for another post in the same taxonomy still normalizes. + */ + public function test_normalization_guard_is_scoped_by_taxonomy_and_object_id() { + $first_post = self::factory()->post->create(); + $second_post = self::factory()->post->create(); + $first_term = self::factory()->term->create( array( 'taxonomy' => 'chrnx_topic' ) ); + $second_term = self::factory()->term->create( array( 'taxonomy' => 'chrnx_topic' ) ); + $term_ids = array( min( $first_term, $second_term ), max( $first_term, $second_term ) ); + + remove_action( 'set_object_terms', 'chrnx_normalize_editorial_taxonomy_terms', 10 ); + wp_set_object_terms( $second_post, array_reverse( $term_ids ), 'chrnx_topic' ); + add_action( 'set_object_terms', 'chrnx_normalize_editorial_taxonomy_terms', 10, 4 ); + + $nested = false; + $assign = static function ( $object_id, $terms, $term_taxonomy_ids, $taxonomy ) use ( $first_post, $second_post, $term_ids, &$nested ) { + if ( ! $nested && $first_post === $object_id && 'chrnx_topic' === $taxonomy && 1 === count( (array) $terms ) ) { + $nested = true; + wp_set_object_terms( $second_post, array_reverse( $term_ids ), 'chrnx_topic' ); + } + }; + add_action( 'set_object_terms', $assign, 20, 4 ); + + wp_set_object_terms( $first_post, array_reverse( $term_ids ), 'chrnx_topic' ); + remove_action( 'set_object_terms', $assign, 20 ); + + $this->assertTrue( $nested ); + $this->assertSame( array( $term_ids[0] ), wp_get_object_terms( $first_post, 'chrnx_topic', array( 'fields' => 'ids' ) ) ); + $this->assertSame( array( $term_ids[0] ), wp_get_object_terms( $second_post, 'chrnx_topic', array( 'fields' => 'ids' ) ) ); + } + + /** + * An exception during correction cannot leave the same-object guard stuck. + */ + public function test_normalization_guard_clears_after_an_exception() { + $post_id = self::factory()->post->create(); + $first_term = self::factory()->term->create( array( 'taxonomy' => 'chrnx_topic' ) ); + $second_term = self::factory()->term->create( array( 'taxonomy' => 'chrnx_topic' ) ); + $term_ids = array( min( $first_term, $second_term ), max( $first_term, $second_term ) ); + $throw = static function ( $object_id, $terms, $term_taxonomy_ids, $taxonomy ) use ( $post_id ) { + if ( $post_id === $object_id && 'chrnx_topic' === $taxonomy && 1 === count( (array) $terms ) ) { + throw new RuntimeException( 'Synthetic corrective failure.' ); + } + }; + add_action( 'set_object_terms', $throw, 5, 4 ); + + try { + wp_set_object_terms( $post_id, array_reverse( $term_ids ), 'chrnx_topic' ); + $this->fail( 'The synthetic corrective failure should escape the nested assignment.' ); + } catch ( RuntimeException $exception ) { + $this->assertSame( 'Synthetic corrective failure.', $exception->getMessage() ); + } finally { + remove_action( 'set_object_terms', $throw, 5 ); + } + + remove_action( 'set_object_terms', 'chrnx_normalize_editorial_taxonomy_terms', 10 ); + wp_set_object_terms( $post_id, array_reverse( $term_ids ), 'chrnx_topic' ); + add_action( 'set_object_terms', 'chrnx_normalize_editorial_taxonomy_terms', 10, 4 ); + wp_set_object_terms( $post_id, array_reverse( $term_ids ), 'chrnx_topic' ); + + $this->assertSame( array( $term_ids[0] ), wp_get_object_terms( $post_id, 'chrnx_topic', array( 'fields' => 'ids' ) ) ); + } + + /** + * Corrective failures produce only a generic one-time notice. + */ + public function test_corrective_failure_notice_is_generic_and_one_time() { + chrnx_record_editorial_normalization_result( 'chrnx_topic', new WP_Error( 'forced', 'Private detail' ) ); + chrnx_record_editorial_normalization_result( 'chrnx_language', false ); + + ob_start(); + chrnx_editorial_taxonomy_admin_notice(); + $notice = ob_get_clean(); + $this->assertStringContainsString( 'could not be normalized', $notice ); + $this->assertStringNotContainsString( 'Private detail', $notice ); + $this->assertStringNotContainsString( 'forced', $notice ); + + ob_start(); + chrnx_editorial_taxonomy_admin_notice(); + $this->assertSame( '', ob_get_clean() ); + } + + /** + * Notices cross requests for one user and never leak to another user. + */ + public function test_normalization_notice_is_user_scoped_and_cross_request_one_time() { + $first_user = self::factory()->user->create(); + $second_user = self::factory()->user->create(); + wp_set_current_user( $first_user ); + chrnx_record_editorial_normalization_result( 'chrnx_topic', array( 1 ) ); + + wp_set_current_user( $second_user ); + ob_start(); + chrnx_editorial_taxonomy_admin_notice(); + $this->assertSame( '', ob_get_clean() ); + + wp_set_current_user( $first_user ); + ob_start(); + chrnx_editorial_taxonomy_admin_notice(); + $this->assertStringContainsString( 'Topic supports one value', ob_get_clean() ); + + ob_start(); + chrnx_editorial_taxonomy_admin_notice(); + $this->assertSame( '', ob_get_clean() ); + } + + /** + * Term insertion failures create a generic, one-time setup diagnostic. + */ + public function test_term_seeding_failure_creates_generic_one_time_diagnostic() { + $term = get_term_by( 'slug', 'research', 'chrnx_topic' ); + if ( $term ) { + wp_delete_term( $term->term_id, 'chrnx_topic' ); + } + $fail_insert = static function ( $term_name, $taxonomy ) { + return 'chrnx_topic' === $taxonomy && 'Research' === $term_name + ? new WP_Error( 'forced_seed_error', 'Private seed detail' ) + : $term_name; + }; + add_filter( 'pre_insert_term', $fail_insert, 10, 2 ); + do_action( 'after_switch_theme' ); + remove_filter( 'pre_insert_term', $fail_insert, 10 ); + + ob_start(); + chrnx_editorial_taxonomy_admin_notice(); + $notice = ob_get_clean(); + $this->assertStringContainsString( 'vocabulary setup was incomplete', $notice ); + $this->assertStringNotContainsString( 'Private seed detail', $notice ); + $this->assertStringNotContainsString( 'forced_seed_error', $notice ); + + ob_start(); + chrnx_editorial_taxonomy_admin_notice(); + $this->assertSame( '', ob_get_clean() ); + } + + /** + * Successful term seeding does not create a diagnostic. + */ + public function test_successful_term_seeding_creates_no_notice() { + do_action( 'after_switch_theme' ); + ob_start(); + chrnx_editorial_taxonomy_admin_notice(); + $this->assertSame( '', ob_get_clean() ); + } + + /** + * Taxonomy labels and seed names use the CHRNX text domain. + */ + public function test_taxonomy_strings_are_localizable() { + $translate = static function ( $translated, $text, $domain ) { + if ( 'chrnx' !== $domain ) { + return $translated; + } + return array( + 'Topic' => 'Tema', + 'Research' => 'Investigación', + )[ $text ] ?? $translated; + }; + add_filter( 'gettext', $translate, 10, 3 ); + $definitions = chrnx_get_editorial_taxonomies(); + remove_filter( 'gettext', $translate, 10 ); + + $this->assertSame( 'Tema', $definitions['chrnx_topic']['singular'] ); + $this->assertSame( 'Investigación', $definitions['chrnx_topic']['terms']['research'] ); } }