feat: add CHRNX theme preference and marks

This commit is contained in:
chrnx committed 2026-08-11 16:32:51 -05:00
1 parent ea62e9535d
commit aad237b211
11 files changed
+469 -3

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<g id="chrnx-cat-geometry">
<path fill="#7C6CF0" d="M8 24 12 5l15 11h10L52 5l4 19v18c0 10-8 18-18 18H26C16 60 8 52 8 42Z"/>
<path fill="none" stroke="#F6F2E9" stroke-linecap="round" stroke-linejoin="round" stroke-width="4" d="M26 29h-7v10h7m12 0h8"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 336 B

+7
View File
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 250 64">
<g id="chrnx-cat-geometry">
<path fill="#7C6CF0" d="M8 24 12 5l15 11h10L52 5l4 19v18c0 10-8 18-18 18H26C16 60 8 52 8 42Z"/>
<path fill="none" stroke="#F6F2E9" stroke-linecap="round" stroke-linejoin="round" stroke-width="4" d="M26 29h-7v10h7m12 0h8"/>
</g>
<text x="74" y="47" fill="#7C6CF0" font-family="'Zen Maru Gothic', ui-rounded, system-ui, sans-serif" font-size="43" font-weight="700" letter-spacing="1">CHRNX</text>
</svg>

After

Width:  |  Height:  |  Size: 506 B

+160
View File
@@ -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();
}
}
} )();
+13
View File
@@ -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"
}
+30
View File
@@ -0,0 +1,30 @@
<?php
/**
* Render the theme preference controls.
*
* @package CHRNX
*/
$chrnx_control_name = wp_unique_id( 'chrnx-theme-' );
?>
<fieldset
<?php
// WordPress escapes each generated wrapper attribute.
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
echo get_block_wrapper_attributes(
array(
'class' => 'chrnx-theme-toggle',
'data-chrnx-theme-toggle' => '',
)
);
?>
data-status-light="<?php esc_attr_e( 'Light theme active', 'chrnx' ); ?>"
data-status-dark="<?php esc_attr_e( 'Dark theme active', 'chrnx' ); ?>"
data-status-system="<?php esc_attr_e( 'following system', 'chrnx' ); ?>"
>
<legend><?php esc_html_e( 'Color theme', 'chrnx' ); ?></legend>
<label><input type="radio" name="<?php echo esc_attr( $chrnx_control_name ); ?>" value="light"> <?php esc_html_e( 'Light', 'chrnx' ); ?></label>
<label><input type="radio" name="<?php echo esc_attr( $chrnx_control_name ); ?>" value="dark"> <?php esc_html_e( 'Dark', 'chrnx' ); ?></label>
<label><input type="radio" name="<?php echo esc_attr( $chrnx_control_name ); ?>" value="system" checked> <?php esc_html_e( 'System', 'chrnx' ); ?></label>
<output data-chrnx-theme-status aria-live="polite"><?php esc_html_e( 'Following system theme', 'chrnx' ); ?></output>
</fieldset>
+1 -1
View File
@@ -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 ) ) {
+14
View File
@@ -0,0 +1,14 @@
<?php
/**
* Early, local-only theme preference bootstrap.
*
* @package CHRNX
*/
/** Print the no-flash theme resolution before stylesheet links. */
function chrnx_print_theme_preference_bootstrap() {
?>
<script id="chrnx-theme-preference-bootstrap">(function(){var t=null,m;try{var s=localStorage.getItem('chrnx-theme');if(s==='light'||s==='dark'){t=s;}}catch(e){}if(!t){try{m=matchMedia('(prefers-color-scheme: dark)').matches;t=m?'dark':'light';}catch(e){t='dark';}}document.documentElement.dataset.theme=t;document.documentElement.style.colorScheme=t;}());</script>
<?php
}
add_action( 'wp_head', 'chrnx_print_theme_preference_bootstrap', 0 );
+150
View File
@@ -0,0 +1,150 @@
const modulePath = '../../assets/js/theme-toggle.js';
function createMedia( matches = false ) {
const listeners = new Set();
return {
matches,
addEventListener: jest.fn( ( _type, listener ) => 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 = `
<fieldset class="chrnx-theme-toggle" data-chrnx-theme-toggle>
<legend>Color theme</legend>
<label><input type="radio" name="theme-a" value="light">Light</label>
<label><input type="radio" name="theme-a" value="dark">Dark</label>
<label><input type="radio" name="theme-a" value="system" checked>System</label>
<output data-chrnx-theme-status aria-live="polite">Following system theme</output>
</fieldset>`;
}
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;
} );
} );
+2 -2
View File
@@ -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 );
+51
View File
@@ -0,0 +1,51 @@
<?php
/**
* Tests for the early theme preference bootstrap.
*
* @package CHRNX
*/
/** Verify no-flash bootstrap and toggle block contracts. */
class ThemePreferenceTest extends WP_UnitTestCase {
/** Bootstrap runs at the earliest wp_head priority. */
public function test_bootstrap_is_registered_at_priority_zero() {
$this->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, '<link' ), strpos( $output, 'dataset.theme' ) );
$this->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( '<fieldset', $output );
$this->assertStringContainsString( '<legend', $output );
$this->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 );
}
}
@@ -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, /^<svg\b/);
assert.doesNotMatch(svg, /<(?:script|image|foreignObject)\b/i);
assert.doesNotMatch(svg, /(?:href|src)\s*=\s*["'](?:https?:|data:|javascript:)/i);
assert.doesNotMatch(svg, /\b(?:aria-|role=|<title\b)/i);
});
}
test('wordmark uses real fallback-aware SVG text and shares exact cat geometry', async () => {
const cat = await readProjectFile('assets/icons/chrnx-cat.svg');
const wordmark = await readProjectFile('assets/icons/chrnx-wordmark.svg');
const geometry = cat.match(/<g id="chrnx-cat-geometry"[^>]*>([\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, /<text\b[^>]*>CHRNX<\/text>/);
assert.match(wordmark, /Zen Maru Gothic/);
});