From aad237b21154372f86d2446da49e99e6ac832ef4 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Tue, 11 Aug 2026 16:32:51 -0500 Subject: [PATCH] feat: add CHRNX theme preference and marks --- assets/icons/chrnx-cat.svg | 6 + assets/icons/chrnx-wordmark.svg | 7 + assets/js/theme-toggle.js | 160 ++++++++++++++++++ blocks/theme-toggle/block.json | 13 ++ blocks/theme-toggle/render.php | 30 ++++ inc/blocks.php | 2 +- inc/theme-preference.php | 14 ++ tests/js/theme-preference.test.js | 150 ++++++++++++++++ tests/php/BlockRenderingTest.php | 4 +- tests/php/ThemePreferenceTest.php | 51 ++++++ .../smoke/theme-preference-contract.test.mjs | 35 ++++ 11 files changed, 469 insertions(+), 3 deletions(-) create mode 100644 assets/icons/chrnx-cat.svg create mode 100644 assets/icons/chrnx-wordmark.svg create mode 100644 assets/js/theme-toggle.js create mode 100644 blocks/theme-toggle/block.json create mode 100644 blocks/theme-toggle/render.php create mode 100644 inc/theme-preference.php create mode 100644 tests/js/theme-preference.test.js create mode 100644 tests/php/ThemePreferenceTest.php create mode 100644 tests/smoke/theme-preference-contract.test.mjs diff --git a/assets/icons/chrnx-cat.svg b/assets/icons/chrnx-cat.svg new file mode 100644 index 0000000..6d57404 --- /dev/null +++ b/assets/icons/chrnx-cat.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/icons/chrnx-wordmark.svg b/assets/icons/chrnx-wordmark.svg new file mode 100644 index 0000000..788f432 --- /dev/null +++ b/assets/icons/chrnx-wordmark.svg @@ -0,0 +1,7 @@ + + + + + + CHRNX + diff --git a/assets/js/theme-toggle.js b/assets/js/theme-toggle.js new file mode 100644 index 0000000..1f36387 --- /dev/null +++ b/assets/js/theme-toggle.js @@ -0,0 +1,160 @@ +( function () { + 'use strict'; + + const STORAGE_KEY = 'chrnx-theme'; + let cleanupCurrent = null; + + function normalizePreference( value ) { + return typeof value === 'string' && ( value === 'light' || value === 'dark' ) ? value : null; + } + + function resolveTheme( explicitPreference, systemPrefersDark ) { + const preference = normalizePreference( explicitPreference ); + if ( preference ) { + return preference; + } + if ( typeof systemPrefersDark === 'boolean' ) { + return systemPrefersDark ? 'dark' : 'light'; + } + return 'dark'; + } + + function readPreference( storage ) { + try { + return normalizePreference( storage && storage.getItem( STORAGE_KEY ) ); + } catch { + return null; + } + } + + function writePreference( storage, preference ) { + try { + if ( ! storage ) { + return; + } + if ( preference === 'light' || preference === 'dark' ) { + storage.setItem( STORAGE_KEY, preference ); + } else { + storage.removeItem( STORAGE_KEY ); + } + } catch { + // Privacy modes may deny storage; the in-memory choice still applies. + } + } + + function applyTheme( doc, theme ) { + const resolved = resolveTheme( theme ); + doc.documentElement.dataset.theme = resolved; + doc.documentElement.style.colorScheme = resolved; + } + + function initialize( options = {} ) { + if ( cleanupCurrent ) { + cleanupCurrent(); + } + + const doc = options.document || ( typeof document === 'undefined' ? null : document ); + if ( ! doc ) { + cleanupCurrent = null; + return false; + } + + let storage = options.storage; + if ( storage === undefined ) { + try { + storage = window.localStorage; + } catch { + storage = null; + } + } + + let media = options.media; + if ( media === undefined ) { + try { + media = window.matchMedia( '(prefers-color-scheme: dark)' ); + } catch { + media = null; + } + } + + const controls = [ ...doc.querySelectorAll( '[data-chrnx-theme-toggle] input[type="radio"]' ) ]; + const groups = [ ...doc.querySelectorAll( '[data-chrnx-theme-toggle]' ) ]; + let explicitPreference = readPreference( storage ); + let listening = false; + + const systemPrefersDark = () => + media && typeof media.matches === 'boolean' ? media.matches : undefined; + const update = () => { + const resolved = resolveTheme( explicitPreference, systemPrefersDark() ); + applyTheme( doc, resolved ); + const selected = explicitPreference || 'system'; + controls.forEach( ( control ) => { + control.checked = control.value === selected; + } ); + groups.forEach( ( group ) => { + const status = group.querySelector( '[data-chrnx-theme-status]' ); + if ( status ) { + const label = + group.dataset[ `status${ resolved[ 0 ].toUpperCase() }${ resolved.slice( 1 ) }` ] || + `${ resolved === 'dark' ? 'Dark' : 'Light' } theme active`; + const systemSuffix = group.dataset.statusSystem || 'following system'; + status.textContent = explicitPreference ? label : `${ label }, ${ systemSuffix }`; + } + } ); + }; + const onMediaChange = () => { + if ( ! explicitPreference ) { + update(); + } + }; + const setMediaListening = ( shouldListen ) => { + if ( + ! media || + typeof media.addEventListener !== 'function' || + typeof media.removeEventListener !== 'function' || + listening === shouldListen + ) { + return; + } + media[ shouldListen ? 'addEventListener' : 'removeEventListener' ]( 'change', onMediaChange ); + listening = shouldListen; + }; + const onChange = ( event ) => { + const value = event.currentTarget.value; + explicitPreference = normalizePreference( value ); + writePreference( storage, value ); + setMediaListening( ! explicitPreference ); + update(); + }; + + controls.forEach( ( control ) => control.addEventListener( 'change', onChange ) ); + setMediaListening( ! explicitPreference ); + update(); + + cleanupCurrent = () => { + controls.forEach( ( control ) => control.removeEventListener( 'change', onChange ) ); + setMediaListening( false ); + cleanupCurrent = null; + }; + return true; + } + + const helpers = { + STORAGE_KEY, + normalizePreference, + resolveTheme, + readPreference, + writePreference, + applyTheme, + initialize, + }; + if ( typeof module !== 'undefined' && module.exports ) { + module.exports = helpers; + } else if ( typeof document !== 'undefined' ) { + if ( document.readyState === 'loading' ) { + document.addEventListener( 'DOMContentLoaded', () => initialize(), { once: true } ); + } else { + initialize(); + } + } +} )(); diff --git a/blocks/theme-toggle/block.json b/blocks/theme-toggle/block.json new file mode 100644 index 0000000..e0fe68a --- /dev/null +++ b/blocks/theme-toggle/block.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://schemas.wp.org/trunk/block.json", + "apiVersion": 3, + "name": "chrnx/theme-toggle", + "version": "0.1.0", + "title": "Theme Toggle", + "category": "theme", + "description": "Choose a light, dark, or system color theme.", + "textdomain": "chrnx", + "supports": { "html": false }, + "viewScript": "file:../../assets/js/theme-toggle.js", + "render": "file:./render.php" +} diff --git a/blocks/theme-toggle/render.php b/blocks/theme-toggle/render.php new file mode 100644 index 0000000..42c2df7 --- /dev/null +++ b/blocks/theme-toggle/render.php @@ -0,0 +1,30 @@ + +
'chrnx-theme-toggle', + 'data-chrnx-theme-toggle' => '', + ) + ); + ?> + data-status-light="" + data-status-dark="" + data-status-system="" +> + + + + + +
diff --git a/inc/blocks.php b/inc/blocks.php index 7aa7894..eb78979 100644 --- a/inc/blocks.php +++ b/inc/blocks.php @@ -74,7 +74,7 @@ function chrnx_get_editorial_card_markup( $post_id, $heading_level = 3, $class_n /** Register all block metadata directories that exist. */ function chrnx_register_editorial_blocks() { - $blocks = array( 'featured-stories', 'journal-stream', 'latest-podcast', 'podcast-meta', 'topic-hero', 'related-posts', 'subscribe-cta' ); + $blocks = array( 'featured-stories', 'journal-stream', 'latest-podcast', 'podcast-meta', 'topic-hero', 'related-posts', 'subscribe-cta', 'theme-toggle' ); foreach ( $blocks as $block ) { $name = 'chrnx/' . $block; if ( WP_Block_Type_Registry::get_instance()->is_registered( $name ) ) { diff --git a/inc/theme-preference.php b/inc/theme-preference.php new file mode 100644 index 0000000..9084613 --- /dev/null +++ b/inc/theme-preference.php @@ -0,0 +1,14 @@ + + + listeners.add( listener ) ), + removeEventListener: jest.fn( ( _type, listener ) => listeners.delete( listener ) ), + change( nextMatches ) { + this.matches = nextMatches; + listeners.forEach( ( listener ) => listener( { matches: nextMatches } ) ); + }, + listenerCount: () => listeners.size, + }; +} + +function toggleMarkup() { + document.body.innerHTML = ` +
+ Color theme + + + + Following system theme +
`; +} + +describe( 'theme preference helpers', () => { + beforeEach( () => { + jest.resetModules(); + document.documentElement.removeAttribute( 'data-theme' ); + document.documentElement.style.colorScheme = ''; + document.body.innerHTML = ''; + } ); + + test( 'saved explicit preference wins, then system, then dark fallback', () => { + const { resolveTheme } = require( modulePath ); + expect( resolveTheme( 'light', true ) ).toBe( 'light' ); + expect( resolveTheme( 'dark', false ) ).toBe( 'dark' ); + expect( resolveTheme( null, true ) ).toBe( 'dark' ); + expect( resolveTheme( null, false ) ).toBe( 'light' ); + expect( resolveTheme( null, undefined ) ).toBe( 'dark' ); + } ); + + test.each( [ 'system', null, '{broken', 'unexpected', 3, {}, true ] )( + 'treats %p as no explicit preference', + ( stored ) => { + const { normalizePreference } = require( modulePath ); + expect( normalizePreference( stored ) ).toBeNull(); + }, + ); + + test( 'only light and dark persist while system removes the single key', () => { + const { STORAGE_KEY, writePreference } = require( modulePath ); + const storage = { setItem: jest.fn(), removeItem: jest.fn() }; + writePreference( storage, 'light' ); + writePreference( storage, 'dark' ); + writePreference( storage, 'system' ); + expect( storage.setItem.mock.calls ).toEqual( [ + [ STORAGE_KEY, 'light' ], + [ STORAGE_KEY, 'dark' ], + ] ); + expect( storage.removeItem ).toHaveBeenCalledWith( STORAGE_KEY ); + expect( STORAGE_KEY ).toBe( 'chrnx-theme' ); + } ); + + test( 'storage denial never breaks initialization and falls back to system', () => { + const { initialize } = require( modulePath ); + toggleMarkup(); + const denied = { + getItem: () => { + throw new Error( 'denied' ); + }, + setItem: () => { + throw new Error( 'denied' ); + }, + removeItem: () => { + throw new Error( 'denied' ); + }, + }; + const media = createMedia( true ); + expect( () => initialize( { document, storage: denied, media } ) ).not.toThrow(); + expect( document.documentElement.dataset.theme ).toBe( 'dark' ); + const light = document.querySelector( 'input[value="light"]' ); + expect( () => light.click() ).not.toThrow(); + expect( document.documentElement.dataset.theme ).toBe( 'light' ); + } ); + + test( 'system media changes update only without an explicit choice', () => { + const { initialize } = require( modulePath ); + toggleMarkup(); + const media = createMedia( false ); + const storage = { getItem: () => null, setItem: jest.fn(), removeItem: jest.fn() }; + initialize( { document, storage, media } ); + expect( document.documentElement.dataset.theme ).toBe( 'light' ); + media.change( true ); + expect( document.documentElement.dataset.theme ).toBe( 'dark' ); + document.querySelector( 'input[value="light"]' ).click(); + media.change( false ); + expect( document.documentElement.dataset.theme ).toBe( 'light' ); + } ); + + test( 'synchronizes all native controls and reports the resolved state', () => { + const { initialize } = require( modulePath ); + toggleMarkup(); + document.body.insertAdjacentHTML( + 'beforeend', + document.body.innerHTML.replaceAll( 'theme-a', 'theme-b' ), + ); + const media = createMedia( true ); + initialize( { + document, + storage: { getItem: () => null, setItem: jest.fn(), removeItem: jest.fn() }, + media, + } ); + document.querySelector( 'input[name="theme-a"][value="light"]' ).click(); + expect( + [ ...document.querySelectorAll( 'input[value="light"]' ) ].every( + ( input ) => input.checked, + ), + ).toBe( true ); + expect( + [ ...document.querySelectorAll( '[data-chrnx-theme-status]' ) ].every( ( status ) => + status.textContent.includes( 'Light' ), + ), + ).toBe( true ); + expect( document.querySelector( 'fieldset' ).textContent ).toContain( 'Color theme' ); + } ); + + test( 'applies data-theme and color-scheme together', () => { + const { applyTheme } = require( modulePath ); + applyTheme( document, 'dark' ); + expect( document.documentElement.dataset.theme ).toBe( 'dark' ); + expect( document.documentElement.style.colorScheme ).toBe( 'dark' ); + } ); + + test( 'reinitialization replaces listeners and never makes remote calls', () => { + const { initialize } = require( modulePath ); + toggleMarkup(); + const media = createMedia(); + global.fetch = jest.fn(); + const fetchSpy = jest.spyOn( global, 'fetch' ); + initialize( { document, storage: null, media } ); + initialize( { document, storage: null, media } ); + expect( media.listenerCount() ).toBe( 1 ); + expect( fetchSpy ).not.toHaveBeenCalled(); + fetchSpy.mockRestore(); + delete global.fetch; + } ); +} ); diff --git a/tests/php/BlockRenderingTest.php b/tests/php/BlockRenderingTest.php index 10fae70..a69b85a 100644 --- a/tests/php/BlockRenderingTest.php +++ b/tests/php/BlockRenderingTest.php @@ -15,9 +15,9 @@ class BlockRenderingTest extends WP_UnitTestCase { delete_option( 'chrnx_subscribe_page_id' ); } - /** All seven block types register from metadata. */ + /** All eight block types register from metadata. */ public function test_all_editorial_blocks_are_registered() { - $names = array( 'featured-stories', 'journal-stream', 'latest-podcast', 'podcast-meta', 'topic-hero', 'related-posts', 'subscribe-cta' ); + $names = array( 'featured-stories', 'journal-stream', 'latest-podcast', 'podcast-meta', 'topic-hero', 'related-posts', 'subscribe-cta', 'theme-toggle' ); foreach ( $names as $name ) { $type = WP_Block_Type_Registry::get_instance()->get_registered( 'chrnx/' . $name ); $this->assertInstanceOf( WP_Block_Type::class, $type, $name ); diff --git a/tests/php/ThemePreferenceTest.php b/tests/php/ThemePreferenceTest.php new file mode 100644 index 0000000..ccfb001 --- /dev/null +++ b/tests/php/ThemePreferenceTest.php @@ -0,0 +1,51 @@ +assertSame( 0, has_action( 'wp_head', 'chrnx_print_theme_preference_bootstrap' ) ); + } + + /** Bootstrap applies theme before enqueued stylesheet markup. */ + public function test_bootstrap_precedes_styles_and_uses_only_local_preference_inputs() { + ob_start(); + do_action( 'wp_head' ); + $output = ob_get_clean(); + + $this->assertStringContainsString( 'chrnx-theme', $output ); + $this->assertStringContainsString( 'prefers-color-scheme: dark', $output ); + $this->assertStringContainsString( 'dataset.theme', $output ); + $this->assertStringContainsString( 'colorScheme', $output ); + $this->assertLessThan( strpos( $output, 'assertStringNotContainsString( 'cookie', strtolower( $output ) ); + $this->assertStringNotContainsString( 'fetch(', $output ); + } + + /** Toggle uses a labeled native radio group with a live status. */ + public function test_toggle_renders_accessible_native_controls() { + do_action( 'init' ); + $output = render_block( + array( + 'blockName' => 'chrnx/theme-toggle', + 'attrs' => array(), + 'innerBlocks' => array(), + 'innerHTML' => '', + 'innerContent' => array(), + ) + ); + + $this->assertStringContainsString( 'assertStringContainsString( 'assertSame( 3, substr_count( $output, 'type="radio"' ) ); + $this->assertStringContainsString( 'value="light"', $output ); + $this->assertStringContainsString( 'value="dark"', $output ); + $this->assertStringContainsString( 'value="system"', $output ); + $this->assertStringContainsString( 'aria-live="polite"', $output ); + } +} diff --git a/tests/smoke/theme-preference-contract.test.mjs b/tests/smoke/theme-preference-contract.test.mjs new file mode 100644 index 0000000..41fcc77 --- /dev/null +++ b/tests/smoke/theme-preference-contract.test.mjs @@ -0,0 +1,35 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import test from 'node:test'; + +const readProjectFile = (path) => readFile(new URL(`../../${path}`, import.meta.url), 'utf8'); + +test('theme toggle metadata is dynamic, localized, and frontend-only', async () => { + const metadata = JSON.parse(await readProjectFile('blocks/theme-toggle/block.json')); + assert.equal(metadata.apiVersion, 3); + assert.equal(metadata.name, 'chrnx/theme-toggle'); + assert.equal(metadata.textdomain, 'chrnx'); + assert.equal(metadata.render, 'file:./render.php'); + assert.equal(metadata.viewScript, 'file:../../assets/js/theme-toggle.js'); + assert.equal(metadata.script, undefined); +}); + +for (const asset of ['chrnx-cat.svg', 'chrnx-wordmark.svg']) { + test(`${asset} is an inert, local, vector-only asset`, async () => { + const svg = await readProjectFile(`assets/icons/${asset}`); + assert.match(svg, /^ { + const cat = await readProjectFile('assets/icons/chrnx-cat.svg'); + const wordmark = await readProjectFile('assets/icons/chrnx-wordmark.svg'); + const geometry = cat.match(/]*>([\s\S]*?)<\/g>/)?.[1].trim(); + assert.ok(geometry, 'standalone cat must expose its canonical geometry group'); + assert.ok(wordmark.includes(geometry), 'wordmark must contain the exact canonical cat geometry'); + assert.match(wordmark, /]*>CHRNX<\/text>/); + assert.match(wordmark, /Zen Maru Gothic/); +});