Refresh wp-asciiplayer with native block editor playback (#36)
Build and WordPress integration / PHP 7.4 syntax and regression tests (push) Canceled after 0s
Build and WordPress integration / PHP 8.3 syntax and regression tests (push) Canceled after 0s
Build and WordPress integration / WordPress 6.3 / PHP 7.4 (push) Canceled after 0s
Build and WordPress integration / WordPress latest / PHP 8.2 (push) Canceled after 0s

* Refresh player with native block editor preview and local assets

Preserve shortcode rendering, normalize options, bundle the player locally,
and add reproducible packaging and WordPress integration tests.

* Fix emitted frontend boot and verify bundled runtime initialization

* Record verified WordPress 7.1.3 compatibility

* Use WordPress readme major-version compatibility format

* Add responsive player layout, captions and native terminal sizing

* Keep editor caption geometry stable during block selection

* Respect WordPress editor gutters with border-box sizing

* Improve automatic previews and toolbar terminal sizing (1.2.1)

* Show native cast dimensions and add Media Library recordings (1.2.2)

* Fix Media Library test storage and scope sidebar selectors

* Document bounded temporary-upload stream exceptions

* Move block explanations into collapsed sidebar help (1.2.3)

* Add bundled English and Simplified Chinese UI translations (1.1.0-dev)

* Use native RichText labels and supported Chinese HTML language tags in locale tests
This commit is contained in:
2026-10-14 15:56:05 +08:00
committed by GitHub
parent 40e2bf0733
commit 85e5ffa0ec
109 changed files with 32680 additions and 2090 deletions
+171
View File
@@ -0,0 +1,171 @@
import { BlockAlignmentToolbar, BlockControls, InspectorControls, MediaUpload, MediaUploadCheck, RichText, useBlockProps } from '@wordpress/block-editor';
import { Button, Dropdown, Notice, PanelBody, Placeholder, RangeControl, SelectControl, TextControl, ToggleControl, ToolbarButton, ToolbarGroup } from '@wordpress/components';
import { useCallback, useEffect, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { finiteNumber, normalizeDisplayAlign, normalizeSource, normalizeWidth, terminalDimension } from './options.js';
import Preview from './preview.js';
/** One shared set of dimension controls in the block toolbar and settings sidebar. */
function TerminalSizeControls( { attributes, setAttributes, recordingSize } ) {
return <>
<div className="asciiplayer-editor__dimension-fields">
<TextControl label={ __( 'Columns', 'wp-asciiplayer' ) } type="number" min="1" max="1000" step="1" value={ attributes.cols ?? '' } placeholder={ recordingSize ? String( recordingSize.cols ) : __( 'From recording', 'wp-asciiplayer' ) } onChange={ ( value ) => setAttributes( { cols: terminalDimension( value ) } ) } />
<TextControl label={ __( 'Rows', 'wp-asciiplayer' ) } type="number" min="1" max="1000" step="1" value={ attributes.rows ?? '' } placeholder={ recordingSize ? String( recordingSize.rows ) : __( 'From recording', 'wp-asciiplayer' ) } onChange={ ( value ) => setAttributes( { rows: terminalDimension( value ) } ) } />
</div>
<p className="asciiplayer-editor__hint">{ __( 'Placeholders show the recording’s original columns and rows once loaded. Leave blank to follow its terminal size and recorded resize events. These overrides change the character grid, not the display width, and may alter or crop the layout.', 'wp-asciiplayer' ) }</p>
<Button variant="secondary" onClick={ () => setAttributes( { cols: undefined, rows: undefined } ) }>{ __( 'Use recording size', 'wp-asciiplayer' ) }</Button>
</>;
}
export default function Edit( { attributes, setAttributes, isSelected } ) {
const { source, theme, speed, loop, controls, fit, startAt, idleTimeLimit, autoPlay, preload, width, caption, displayAlign } = attributes;
const [ draftSource, setDraftSource ] = useState( source );
const [ urlError, setUrlError ] = useState( false );
const [ mediaError, setMediaError ] = useState( false );
const [ recording, setRecording ] = useState( null );
const onRecordingSize = useCallback( ( loadedSource, size ) => setRecording( { source: loadedSource, size } ), [] );
const [ attempt, setAttempt ] = useState( 0 );
const [ draftWidth, setDraftWidth ] = useState( width );
useEffect( () => setDraftWidth( width ), [ width ] );
useEffect( () => {
setDraftSource( source );
setRecording( null );
setUrlError( Boolean( source.trim() ) && ! normalizeSource( source ) );
}, [ source ] );
// Saved/undone sources load immediately. Typed changes wait until the user
// pauses, and submitting the form applies the same URL without that delay.
useEffect( () => {
if ( attributes.isExample || draftSource === source ) return undefined;
const timer = setTimeout( () => {
const next = normalizeSource( draftSource );
setUrlError( Boolean( draftSource.trim() ) && ! next );
if ( next || ! draftSource.trim() ) setAttributes( { source: next } );
}, 500 );
return () => clearTimeout( timer );
}, [ draftSource, source, attributes.isExample, setAttributes ] );
const previewSource = normalizeSource( source );
const showPreview = previewSource && previewSource === normalizeSource( draftSource );
const recordingSize = showPreview && recording?.source === previewSource ? recording.size : null;
const blockProps = useBlockProps( { className: 'asciiplayer-editor' } );
const applySource = ( event ) => {
event.preventDefault();
const next = normalizeSource( draftSource );
setUrlError( ! next );
if ( ! next ) return;
setAttributes( { source: next } );
setDraftSource( next );
setAttempt( ( current ) => current + 1 );
};
const selectRecording = ( media ) => {
const next = normalizeSource( media?.url );
if ( ! next || ! /\.cast$/i.test( next.split( /[?#]/ )[ 0 ] ) ) {
setMediaError( true );
return;
}
setMediaError( false );
setUrlError( false );
setRecording( null );
setDraftSource( next );
setAttributes( { source: next } );
setAttempt( ( current ) => current + 1 );
};
const themes = [
{ label: __( 'Asciinema', 'wp-asciiplayer' ), value: 'asciinema' },
{ label: __( 'Recording theme (automatic)', 'wp-asciiplayer' ), value: 'auto/asciinema' },
{ label: 'Dracula', value: 'dracula' }, { label: 'Monokai', value: 'monokai' },
{ label: 'Nord', value: 'nord' }, { label: 'Solarized Dark', value: 'solarized-dark' },
{ label: 'Solarized Light', value: 'solarized-light' }, { label: 'Tango', value: 'tango' },
];
if ( ! themes.some( ( option ) => option.value === theme ) ) themes.push( { label: theme, value: theme } );
const widthPresets = [ '100%', '80%', '60%', '50%', '25%' ];
const widthOptions = [ ...widthPresets.map( ( value ) => ( { label: value, value } ) ), { label: __( 'Custom', 'wp-asciiplayer' ), value: 'custom' } ];
const [ customWidth, setCustomWidth ] = useState( ! widthPresets.includes( width ) );
const widthValid = draftWidth.trim() !== '' && normalizeWidth( draftWidth ) === draftWidth.trim() && parseFloat( draftWidth ) > 0;
const placement = normalizeDisplayAlign( displayAlign );
const fitOptions = [
{ label: __( 'Width', 'wp-asciiplayer' ), value: 'width' },
{ label: __( 'Original size', 'wp-asciiplayer' ), value: 'none' },
];
if ( fit === 'height' || fit === 'both' ) fitOptions.push( { label: fit === 'height' ? __( 'Height (legacy)', 'wp-asciiplayer' ) : __( 'Width and height (legacy)', 'wp-asciiplayer' ), value: fit } );
if ( attributes.isExample ) {
return <div { ...blockProps }><figure className="asciiplayer-example" aria-label={ __( 'Example terminal recording', 'wp-asciiplayer' ) }><div className="asciiplayer-example__terminal"><span>$ printf 'Hello, terminal!\n'</span><br /><span>Hello, terminal!</span><br /><span>$ <span aria-hidden="true">▋</span></span></div><div className="asciiplayer-example__controls" aria-hidden="true">▶ ━━━━━━━━━━━ 0:00 / 0:12</div><figcaption>{ __( 'A terminal recording, right in your post.', 'wp-asciiplayer' ) }</figcaption></figure></div>;
}
return (
<>
<BlockControls group="other">
<BlockAlignmentToolbar value={ placement } controls={ [ 'left', 'center', 'right' ] } onChange={ ( value ) => setAttributes( { displayAlign: normalizeDisplayAlign( value ) } ) } />
<ToolbarGroup>
<Dropdown contentClassName="asciiplayer-terminal-popover" popoverProps={ { placement: 'bottom-start' } } renderToggle={ ( { isOpen, onToggle } ) => (
<ToolbarButton icon="editor-table" label={ __( 'Terminal size', 'wp-asciiplayer' ) } aria-expanded={ isOpen } onClick={ onToggle } />
) } renderContent={ ( { onClose } ) => (
<div className="asciiplayer-terminal-popover__content" role="dialog" aria-label={ __( 'Terminal size', 'wp-asciiplayer' ) }>
<p><strong>{ __( 'Terminal size (columns × rows)', 'wp-asciiplayer' ) }</strong></p>
<TerminalSizeControls attributes={ attributes } setAttributes={ setAttributes } recordingSize={ recordingSize } />
<Button variant="tertiary" onClick={ onClose }>{ __( 'Close', 'wp-asciiplayer' ) }</Button>
</div>
) } />
</ToolbarGroup>
</BlockControls>
<InspectorControls>
<PanelBody title={ __( 'Terminal size', 'wp-asciiplayer' ) } initialOpen={ false }>
<TerminalSizeControls attributes={ attributes } setAttributes={ setAttributes } recordingSize={ recordingSize } />
</PanelBody>
<PanelBody title={ __( 'Display', 'wp-asciiplayer' ) }>
<SelectControl label={ __( 'Player width', 'wp-asciiplayer' ) } value={ customWidth || ! widthPresets.includes( width ) ? 'custom' : width } options={ widthOptions } onChange={ ( value ) => { setCustomWidth( value === 'custom' ); if ( value !== 'custom' ) setAttributes( { width: value } ); } } />
{ ( customWidth || ! widthPresets.includes( width ) ) && <TextControl label={ __( 'Custom width', 'wp-asciiplayer' ) } value={ draftWidth } help={ widthValid ? __( 'Use a CSS length, such as 480px or 65%. The player stays within its available space.', 'wp-asciiplayer' ) : __( 'Enter a positive width with a unit, such as 480px or 65%. The last valid width is kept.', 'wp-asciiplayer' ) } aria-invalid={ ! widthValid } onChange={ ( value ) => { setDraftWidth( value ); if ( value.trim() && normalizeWidth( value ) === value.trim() && parseFloat( value ) > 0 ) setAttributes( { width: value.trim() } ); } } /> }
<SelectControl label={ __( 'Display alignment', 'wp-asciiplayer' ) } value={ placement } options={ [ { label: __( 'Left', 'wp-asciiplayer' ), value: 'left' }, { label: __( 'Center', 'wp-asciiplayer' ), value: 'center' }, { label: __( 'Right', 'wp-asciiplayer' ), value: 'right' } ] } onChange={ ( value ) => setAttributes( { displayAlign: value } ) } />
<p>{ __( 'Display width scales the recording without changing its terminal columns or rows. Add a caption directly below the player.', 'wp-asciiplayer' ) }</p>
</PanelBody>
<PanelBody title={ __( 'Playback', 'wp-asciiplayer' ) }>
<RangeControl label={ __( 'Playback speed', 'wp-asciiplayer' ) } value={ speed } min={ 0.25 } max={ Math.max( 8, speed ) } step={ 0.25 } onChange={ ( value ) => setAttributes( { speed: finiteNumber( value, 1, 0.01, 100 ) } ) } />
<ToggleControl label={ __( 'Loop playback', 'wp-asciiplayer' ) } checked={ loop } onChange={ ( value ) => setAttributes( { loop: value } ) } />
<ToggleControl label={ __( 'Autoplay on published page', 'wp-asciiplayer' ) } help={ __( 'The editor preview always waits for you to press play.', 'wp-asciiplayer' ) } checked={ autoPlay } onChange={ ( value ) => setAttributes( { autoPlay: value } ) } />
<ToggleControl label={ __( 'Preload on published page', 'wp-asciiplayer' ) } help={ __( 'Loads the recording before the visitor presses play. The editor preview always preloads a valid recording URL.', 'wp-asciiplayer' ) } checked={ preload } onChange={ ( value ) => setAttributes( { preload: value } ) } />
<TextControl label={ __( 'Start at (seconds)', 'wp-asciiplayer' ) } type="number" min="0" step="0.1" value={ startAt } onChange={ ( value ) => setAttributes( { startAt: finiteNumber( value, 0 ) } ) } />
<TextControl label={ __( 'Idle time limit (seconds)', 'wp-asciiplayer' ) } help={ __( 'Shorten long pauses. Use 0 to keep the recording’s default.', 'wp-asciiplayer' ) } type="number" min="0" step="0.1" value={ idleTimeLimit } onChange={ ( value ) => setAttributes( { idleTimeLimit: finiteNumber( value, 0 ) } ) } />
</PanelBody>
<PanelBody title={ __( 'Appearance', 'wp-asciiplayer' ) }>
<SelectControl label={ __( 'Theme', 'wp-asciiplayer' ) } value={ theme } options={ themes } onChange={ ( value ) => setAttributes( { theme: value } ) } />
<SelectControl label={ __( 'Player controls', 'wp-asciiplayer' ) } value={ controls } options={ [
{ label: __( 'Show on interaction', 'wp-asciiplayer' ), value: 'auto' },
{ label: __( 'Always show', 'wp-asciiplayer' ), value: 'always' },
{ label: __( 'Hide', 'wp-asciiplayer' ), value: 'never' },
] } onChange={ ( value ) => setAttributes( { controls: value } ) } />
<SelectControl label={ __( 'Fit', 'wp-asciiplayer' ) } value={ fit } options={ fitOptions } help={ [ 'height', 'both' ].includes( fit ) ? __( 'Height-based fitting requires a fixed container height in your site CSS.', 'wp-asciiplayer' ) : undefined } onChange={ ( value ) => setAttributes( { fit: value } ) } />
{ attributes.legacyStyle && <p>{ __( 'The custom container style from your shortcode is preserved on the published page.', 'wp-asciiplayer' ) }</p> }
</PanelBody>
<PanelBody title={ __( 'Help', 'wp-asciiplayer' ) } initialOpen={ false }>
<p className="asciiplayer-editor__privacy">{ __( 'A valid recording URL loads its preview automatically, including when reopening this editor. That server receives your browser’s request. Published players contact the same server. Use a direct .cast URL; external servers must allow CORS.', 'wp-asciiplayer' ) }</p>
<p className="asciiplayer-editor__hint">{ __( 'Use the player controls to play, pause, and seek. Autoplay is disabled only in the editor.', 'wp-asciiplayer' ) }</p>
</PanelBody>
</InspectorControls>
<div { ...blockProps }>
<div className="asciiplayer-editor__source">
<form onSubmit={ applySource }>
<TextControl label={ __( 'Recording URL', 'wp-asciiplayer' ) } placeholder="https://example.com/recording.cast" value={ draftSource } onChange={ ( value ) => { setDraftSource( value ); setUrlError( false ); setMediaError( false ); } } autoComplete="off" />
<Button type="submit" variant="primary">{ __( 'Apply URL', 'wp-asciiplayer' ) }</Button>
</form>
<MediaUploadCheck>
<MediaUpload title={ __( 'Choose an Asciicast recording', 'wp-asciiplayer' ) } allowedTypes={ [ 'application/x-asciicast', 'text/plain', 'application/json', 'application/octet-stream', 'application/jsonl', 'application/x-ndjson' ] } multiple={ false } onSelect={ selectRecording } render={ ( { open } ) => (
<Button className="asciiplayer-editor__media" variant="secondary" onClick={ open }>{ __( 'Choose recording', 'wp-asciiplayer' ) }</Button>
) } />
</MediaUploadCheck>
{ mediaError && <Notice status="error" isDismissible={ false }>{ __( 'Choose an Asciicast (.cast) file from the Media Library.', 'wp-asciiplayer' ) }</Notice> }
{ urlError && <Notice status="error" isDismissible={ false }>{ __( 'Enter an HTTP(S) recording URL or a path starting with a single /.', 'wp-asciiplayer' ) }</Notice> }
</div>
<figure className={ `asciiplayer-figure asciiplayer-align-${ placement }` } style={ { width: normalizeWidth( width ) } }>
{ showPreview ? (
<>
<Preview source={ previewSource } attributes={ attributes } attempt={ attempt } onRecordingSize={ onRecordingSize } onRetry={ () => setAttempt( ( current ) => current + 1 ) } />
</>
) : (
<Placeholder icon="editor-code" label={ __( 'Asciicast Player', 'wp-asciiplayer' ) } instructions={ __( 'Enter a recording URL to load its preview automatically. Playback starts only when you press play.', 'wp-asciiplayer' ) } />
) }
<RichText tagName="figcaption" className={ `wp-element-caption${ ! isSelected && ! caption ? ' asciiplayer-caption-empty' : '' }` } value={ caption } allowedFormats={ [] } onChange={ ( value ) => setAttributes( { caption: value } ) } placeholder={ __( 'Add a caption…', 'wp-asciiplayer' ) } aria-label={ __( 'Recording caption', 'wp-asciiplayer' ) } />
</figure>
{ [ 'height', 'both' ].includes( fit ) && <p className="asciiplayer-editor__hint">{ __( 'Height-based previews use the shortcode’s fixed height when available, or a 320px editor frame. Published height still comes from your container style.', 'wp-asciiplayer' ) }</p> }
</div>
</>
);
}
+75
View File
@@ -0,0 +1,75 @@
.asciiplayer-editor {
box-sizing: border-box;
border: 1px solid #ddd;
border-radius: 4px;
padding: 16px;
}
.asciiplayer-editor__source form {
display: flex;
align-items: flex-end;
gap: 12px;
}
.asciiplayer-editor__source .components-base-control {
flex: 1;
margin-bottom: 0;
}
.asciiplayer-editor__source .components-base-control__field {
margin-bottom: 0;
}
.asciiplayer-editor__privacy,
.asciiplayer-editor__hint {
font-size: 12px;
line-height: 1.5;
color: #50575e;
}
.asciiplayer-editor__preview {
margin-top: 16px;
}
/*! rtl:begin:ignore */
.asciiplayer-editor__player {
min-width: 0;
text-align: left;
}
/*! rtl:end:ignore */
.asciiplayer-editor__status {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
}
@media (max-width: 480px) {
.asciiplayer-editor__source form {
align-items: stretch;
flex-direction: column;
}
}
.asciiplayer-editor > .asciiplayer-figure { margin-top: 16px; }
.asciiplayer-editor .asciiplayer-editor__preview { margin-top: 0; }
.asciiplayer-example { margin: 0; background: #121314; color: #eee; border-radius: 5px; overflow: hidden; }
.asciiplayer-example__terminal { padding: 24px 16px; font: 14px/1.7 monospace; white-space: pre; }
.asciiplayer-example__terminal > span:first-child { color: #a9da76; }
.asciiplayer-example__controls { padding: 8px 16px; background: #222; font: 12px/1.5 monospace; }
.asciiplayer-example figcaption { padding: 8px; background: #fff; color: #333; text-align: center; font-size: 12px; }
/* Keep an empty caption's footprint stable when another block is selected.
* Removing it on pointerdown can move the next block's button before pointerup. */
.asciiplayer-editor .asciiplayer-figure > figcaption { min-height: 1.5em; }
.asciiplayer-editor .asciiplayer-caption-empty { visibility: hidden; }
.asciiplayer-editor__dimension-fields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
.asciiplayer-editor__dimension-fields input { max-width: 100%; }
.asciiplayer-terminal-popover__content { box-sizing: border-box; width: 300px; max-width: calc(100vw - 32px); padding: 16px; }
.asciiplayer-terminal-popover__content > p:first-child { margin-top: 0; }
.asciiplayer-terminal-popover__content > .components-button { margin-top: 8px; margin-right: 8px; }
.asciiplayer-editor__source .asciiplayer-editor__media { margin-top: 12px; }
+46
View File
@@ -0,0 +1,46 @@
import { createBlock, registerBlockType } from '@wordpress/blocks';
import { next } from '@wordpress/shortcode';
import { decodeEntities } from '@wordpress/html-entities';
import metadata from '../block.json';
import { _x } from '@wordpress/i18n';
import Edit from './edit.js';
import { attributesFromShortcode, canTransformShortcode, normalizeSource } from './options.js';
import './style.css';
import './editor.css';
function matchShortcodeBlock( text = '' ) {
const match = next( 'asciiplayer', text );
return match && text.trim() === match.content.trim() && canTransformShortcode( match.shortcode.attrs ) && normalizeSource( decodeEntities( match.shortcode.content ) ) ? match : null;
}
registerBlockType( metadata.name, {
...metadata,
title: _x( 'Asciicast Player', 'block title', 'wp-asciiplayer' ),
description: _x( 'Embed and preview a terminal recording with the locally bundled asciinema player.', 'block description', 'wp-asciiplayer' ),
keywords: [ _x( 'asciinema', 'block keyword', 'wp-asciiplayer' ), _x( 'terminal', 'block keyword', 'wp-asciiplayer' ), _x( 'recording', 'block keyword', 'wp-asciiplayer' ) ],
edit: Edit,
save: () => null,
transforms: {
from: [
{
type: 'shortcode',
tag: 'asciiplayer',
isMatch: canTransformShortcode,
transform: ( { named }, match ) => {
const source = decodeEntities( match.shortcode.content || '' );
if ( ! normalizeSource( source ) ) return createBlock( 'core/shortcode', { text: match.content } );
return createBlock( metadata.name, attributesFromShortcode( named, source ) );
},
},
{
type: 'block',
blocks: [ 'core/shortcode' ],
isMatch: ( { text } ) => Boolean( matchShortcodeBlock( text ) ),
transform: ( { text } ) => {
const match = matchShortcodeBlock( text );
return createBlock( metadata.name, attributesFromShortcode( match.shortcode.attrs.named, decodeEntities( match.shortcode.content ) ) );
},
},
],
},
} );
+149
View File
@@ -0,0 +1,149 @@
/** Shared, side-effect-free validation for the editor and front-end adapter. */
export const DEFAULTS = Object.freeze( {
theme: 'asciinema', speed: 1, loop: false, controls: 'auto', fit: 'width',
startAt: 0, idleTimeLimit: 0, autoPlay: false, preload: true, width: '100%',
} );
export function booleanValue( value, fallback = false ) {
if ( typeof value === 'boolean' ) return value;
if ( value === 1 || /^(true|1|yes|on)$/i.test( String( value ).trim() ) ) return true;
if ( value === 0 || /^(false|0|no|off)$/i.test( String( value ).trim() ) ) return false;
return fallback;
}
export function finiteNumber( value, fallback, min = 0, max = Number.MAX_SAFE_INTEGER ) {
if ( typeof value !== 'number' && typeof value !== 'string' ) return fallback;
if ( typeof value === 'string' && ! /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test( value.trim() ) ) return fallback;
const number = Number( value );
return Number.isFinite( number ) && number >= min && number <= max ? number : fallback;
}
/** Accept explicit web URLs and site-root-relative URLs; never executable schemes. */
export function normalizeSource( input ) {
if ( typeof input !== 'string' ) return '';
const source = input.trim();
if ( ! source || /[\u0000-\u0020\u007f<>"\\]/.test( source ) ) return '';
if ( /^\/(?!\/)/.test( source ) ) return source;
// URL() repairs missing/extra authority slashes; PHP deliberately does not.
if ( ! /^https?:\/\/[^/]/i.test( source ) ) return '';
try {
const url = new URL( source );
return [ 'http:', 'https:' ].includes( url.protocol ) && ! url.username && ! url.password ? source : '';
} catch {
return '';
}
}
export function normalizeWidth( value ) {
return typeof value === 'string' && /^(?:0|(?:\d+(?:\.\d+)?|\.\d+)(?:px|%|em|rem|vw|vh|vmin|vmax|ch))$/.test( value.trim() )
? value.trim() : DEFAULTS.width;
}
/** Presentation placement never changes the terminal's character grid. */
export function normalizeDisplayAlign( value ) {
return [ 'left', 'center', 'right' ].includes( value ) ? value : 'center';
}
export function terminalDimension( value ) {
const number = finiteNumber( value, 0, 1, 1000 );
return Number.isInteger( number ) && number > 0 ? number : undefined;
}
/** A bounded editor frame for old height-fitting shortcodes; never persisted. */
export function previewHeight( attributes ) {
if ( ! [ 'height', 'both' ].includes( attributes.fit ) ) return undefined;
let height = '320px';
for ( const declaration of String( attributes.legacyStyle || '' ).split( ';' ) ) {
const match = declaration.match( /^\s*height\s*:\s*((?:\d+(?:\.\d+)?|\.\d+)(?:px|em|rem|vh|vw|vmin|vmax|ch))\s*$/i );
if ( match ) height = match[ 1 ];
}
return height;
}
export function normalizeControls( value ) {
if ( typeof value === 'string' ) value = value.trim().toLowerCase();
if ( value === 'always' || booleanValue( value, null ) === true ) return true;
if ( value === 'never' || booleanValue( value, null ) === false ) return false;
return 'auto';
}
export function secondsValue( value ) {
if ( typeof value === 'string' && /^\d+(?::[0-5]?\d){1,2}(?:\.\d+)?$/.test( value.trim() ) ) {
return value.trim().split( ':' ).reduce( ( total, part ) => total * 60 + Number( part ), 0 );
}
return finiteNumber( value, 0 );
}
export function normalizePlayerOptions( attributes = {}, { preview = false } = {} ) {
const fit = typeof attributes.fit === 'string' ? attributes.fit.trim().toLowerCase() : attributes.fit;
const fontSize = typeof attributes.terminalFontSize === 'string' ? attributes.terminalFontSize.trim().toLowerCase() : '';
const fontFamily = typeof attributes.terminalFontFamily === 'string' ? attributes.terminalFontFamily.trim() : '';
const options = {
theme: typeof attributes.theme === 'string' && /^(?:auto\/)?[\w-]{1,64}$/.test( attributes.theme ) ? attributes.theme : DEFAULTS.theme,
speed: finiteNumber( attributes.speed, 1, 0.01, 100 ),
loop: booleanValue( attributes.loop ),
controls: normalizeControls( attributes.controls ),
fit: [ 'width', 'height', 'both', 'none' ].includes( fit ) ? fit : booleanValue( fit, null ) === false ? 'none' : 'width',
startAt: secondsValue( attributes.startAt ),
autoPlay: preview ? false : booleanValue( attributes.autoPlay ?? attributes.autoplay ),
preload: preview ? true : booleanValue( attributes.preload, true ),
};
// Shortcodes may intentionally request a finite number of loops.
if ( typeof attributes.loop === 'number' && attributes.loop > 0 && Number.isInteger( attributes.loop ) ) options.loop = attributes.loop;
const idle = finiteNumber( attributes.idleTimeLimit, 0 );
if ( idle > 0 ) options.idleTimeLimit = idle;
for ( const key of [ 'cols', 'rows' ] ) {
const number = finiteNumber( attributes[ key ], 0, 1, 1000 );
if ( Number.isInteger( number ) && number > 0 ) options[ key ] = number;
}
const lineHeight = finiteNumber( attributes.terminalLineHeight, 0, 0.1, 10 );
if ( lineHeight ) options.terminalLineHeight = lineHeight;
if ( fontFamily.length <= 300 && /^[a-zA-Z0-9 _.,'"-]+$/.test( fontFamily ) ) options.terminalFontFamily = fontFamily;
if ( /^(small|medium|big|0|(?:\d+(?:\.\d+)?|\.\d+)(?:px|%|em|rem|vw|vh|vmin|vmax|ch))$/.test( fontSize ) ) options.terminalFontSize = fontSize;
if ( typeof attributes.poster === 'string' && attributes.poster.length <= 32768 && /^(npt:\d+(?::[0-5]?\d){0,2}(?:\.\d+)?|data:text\/plain,[\s\S]*)$/.test( attributes.poster ) ) options.poster = attributes.poster;
return options;
}
const SHORTCODE_KEYS = {
theme: 'theme', speed: 'speed', loop: 'loop', controls: 'controls', fit: 'fit',
startat: 'startAt', idletimelimit: 'idleTimeLimit', autoplay: 'autoPlay', preload: 'preload',
cols: 'cols', rows: 'rows', terminalfontfamily: 'terminalFontFamily',
terminalfontsize: 'terminalFontSize', terminallineheight: 'terminalLineHeight', poster: 'poster', style: 'legacyStyle',
fontsize: 'terminalFontSize', fontfamily: 'terminalFontFamily', lineheight: 'terminalLineHeight', width: 'width',
};
/** Unknown legacy options stay in their original shortcode rather than being lost. */
export function canTransformShortcode( { named = {}, numeric = [] } = {} ) {
return numeric.length === 0 && Object.entries( named ).every( ( [ key, value ] ) => {
const lower = key.toLowerCase();
if ( ! Object.prototype.hasOwnProperty.call( SHORTCODE_KEYS, lower ) ) return false;
if ( lower === 'loop' && booleanValue( value, null ) === null ) return false;
if ( lower === 'style' ) {
const widths = String( value ).matchAll( /(?:^|;)\s*width\s*:\s*([^;]+)/gi );
for ( const match of widths ) if ( normalizeWidth( match[ 1 ] ) !== match[ 1 ].trim() ) return false;
}
return true;
} );
}
export function attributesFromShortcode( named = {}, content = '' ) {
const values = {};
for ( const [ key, value ] of Object.entries( named ) ) {
const target = SHORTCODE_KEYS[ key.toLowerCase() ];
if ( target ) values[ target ] = value;
}
if ( values.fit === 'false' || values.fit === false ) values.fit = 'none';
const normalized = normalizePlayerOptions( values );
const attributes = {
...normalized,
source: normalizeSource( content ),
controls: normalized.controls === true ? 'always' : normalized.controls === false ? 'never' : 'auto',
idleTimeLimit: normalized.idleTimeLimit ?? 0,
};
if ( values.legacyStyle ) {
attributes.legacyStyle = values.legacyStyle;
for ( const match of String( values.legacyStyle ).matchAll( /(?:^|;)\s*width\s*:\s*([^;]+)/gi ) ) attributes.width = normalizeWidth( match[ 1 ] );
}
if ( values.width ) attributes.width = normalizeWidth( values.width );
return attributes;
}
+103
View File
@@ -0,0 +1,103 @@
/**
* asciinema uses realm-global document/HTMLButtonElement internally. Execute its
* bundled script in the canvas document, not in the parent React document.
*/
const pendingDocuments = new WeakMap();
const pendingStyles = new WeakMap();
function findAsset( document, selector, property ) {
return document.querySelector( selector )?.[ property ];
}
export function playerAssets( hostWindow = window ) {
const settings = hostWindow.wpAsciiplayerSettings || {};
return {
script: settings.playerScriptUrl || findAsset( hostWindow.document, '#lamgc-asciiplayer-player-js', 'src' ),
style: settings.playerStyleUrl || findAsset( hostWindow.document, '#lamgc-asciiplayer-player-style-css', 'href' ),
};
}
function ensureStyle( document, url ) {
if ( ! url ) return Promise.reject( new Error( 'The local player stylesheet is unavailable.' ) );
let link = Array.from( document.querySelectorAll( 'link[rel="stylesheet"]' ) ).find( ( item ) => item.href === url && ( item.sheet || ! item.dataset.asciiplayerFailed ) );
if ( link?.sheet ) return Promise.resolve();
if ( pendingStyles.has( document ) ) return pendingStyles.get( document );
const created = ! link;
if ( created ) {
link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.href = url;
link.dataset.asciiplayerAsset = 'style';
}
const promise = new Promise( ( resolve, reject ) => {
let timer;
const cleanup = () => {
document.defaultView.clearTimeout( timer );
link.removeEventListener( 'load', loaded );
link.removeEventListener( 'error', failed );
};
const loaded = () => { cleanup(); resolve(); };
const failed = () => {
cleanup();
link.dataset.asciiplayerFailed = 'true';
if ( created ) link.remove();
reject( new Error( 'The local player stylesheet could not be loaded.' ) );
};
link.addEventListener( 'load', loaded );
link.addEventListener( 'error', failed );
timer = document.defaultView.setTimeout( failed, 20000 );
if ( created ) document.head.appendChild( link );
if ( link.sheet ) loaded();
} );
pendingStyles.set( document, promise );
promise.then( () => pendingStyles.delete( document ), () => pendingStyles.delete( document ) );
return promise;
}
export async function playerForDocument( document, assets ) {
const canvasWindow = document.defaultView;
if ( ! canvasWindow ) return Promise.reject( new Error( 'The editor canvas is unavailable.' ) );
// Player metrics are measured at create(), so CSS must finish first.
await ensureStyle( document, assets.style );
if ( typeof canvasWindow.AsciinemaPlayer?.create === 'function' ) return Promise.resolve( canvasWindow.AsciinemaPlayer );
if ( pendingDocuments.has( document ) ) return pendingDocuments.get( document );
if ( ! assets.script ) return Promise.reject( new Error( 'The local player script is unavailable.' ) );
const pending = new Promise( ( resolve, reject ) => {
let script = Array.from( document.scripts ).find( ( item ) => item.src === assets.script && ! item.dataset.asciiplayerFailed );
const created = ! script;
if ( created ) {
script = document.createElement( 'script' );
script.src = assets.script;
script.async = true;
script.dataset.asciiplayerAsset = 'script';
}
let timer;
const cleanup = () => {
canvasWindow.clearTimeout( timer );
script.removeEventListener( 'load', loaded );
script.removeEventListener( 'error', failed );
};
const failed = () => {
cleanup();
script.dataset.asciiplayerFailed = 'true';
// Only remove a script we own. A retry can then load a fresh copy.
if ( created ) script.remove();
reject( new Error( 'The local player script could not be loaded.' ) );
};
const loaded = () => {
if ( typeof canvasWindow.AsciinemaPlayer?.create !== 'function' ) return failed();
cleanup();
resolve( canvasWindow.AsciinemaPlayer );
};
script.addEventListener( 'load', loaded );
script.addEventListener( 'error', failed );
timer = canvasWindow.setTimeout( failed, 20000 );
if ( created ) document.head.appendChild( script );
// Covers a script that finished between the global check and listener setup.
if ( typeof canvasWindow.AsciinemaPlayer?.create === 'function' ) loaded();
} );
pendingDocuments.set( document, pending );
pending.catch( () => pendingDocuments.delete( document ) );
return pending;
}
+88
View File
@@ -0,0 +1,88 @@
import { Button, Notice, Spinner } from '@wordpress/components';
import { useRefEffect } from '@wordpress/compose';
import { useRef, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { normalizePlayerOptions, previewHeight } from './options.js';
import { playerAssets, playerForDocument } from './player-bridge.js';
import { readRecordingSize } from './recording-metadata.js';
export default function Preview( { source, attributes, attempt, onRetry, onRecordingSize } ) {
const [ status, setStatus ] = useState( 'loading' );
const [ problem, setProblem ] = useState( '' );
const onRecordingSizeRef = useRef( onRecordingSize );
onRecordingSizeRef.current = onRecordingSize;
const optionsJSON = JSON.stringify( normalizePlayerOptions( attributes, { preview: true } ) );
const playerRef = useRefEffect( ( container ) => {
let disposed = false;
let failed = false;
let player;
let readinessTimer;
let deadline;
const canvasWindow = container.ownerDocument.defaultView;
const request = new canvasWindow.AbortController();
const reportSize = ( size ) => {
if ( ! disposed ) onRecordingSizeRef.current?.( source, size );
};
setStatus( 'loading' );
setProblem( '' );
reportSize( null );
const fail = ( message ) => {
if ( disposed || failed ) return;
failed = true;
request.abort();
canvasWindow.clearInterval( readinessTimer );
canvasWindow.clearTimeout( deadline );
reportSize( null );
setProblem( message );
setStatus( 'error' );
};
const ready = () => {
if ( disposed || failed ) return;
canvasWindow.clearInterval( readinessTimer );
canvasWindow.clearTimeout( deadline );
setStatus( 'ready' );
};
playerForDocument( container.ownerDocument, playerAssets() ).then( ( api ) => {
if ( disposed ) return;
player = api.create( {
data: async () => {
// The parser checks instanceof Response in the canvas realm.
// Reuse this one request for playback and original-size hints.
const response = await canvasWindow.fetch( source, { signal: request.signal } );
if ( ! response.ok ) throw new Error( `Recording request failed: ${ response.status }` );
readRecordingSize( response ).then( ( size ) => {
if ( ! failed ) reportSize( size );
} );
return response;
},
}, container, JSON.parse( optionsJSON ) );
player.addEventListener( 'error', () => fail( __( 'Unable to load the recording. Check the URL, file format, and the source server’s CORS permissions.', 'wp-asciiplayer' ) ) );
player.addEventListener( 'playing', ready );
// getDuration is public API; a mounted wrapper alone does not mean the
// recording loaded successfully. Works across supported player versions.
const checkReady = () => {
const duration = player.getDuration();
if ( typeof duration === 'number' && Number.isFinite( duration ) ) ready();
};
readinessTimer = canvasWindow.setInterval( checkReady, 150 );
deadline = canvasWindow.setTimeout( () => fail( __( 'The recording is taking too long to load. Check your connection and try again.', 'wp-asciiplayer' ) ), 30000 );
checkReady();
} ).catch( () => fail( __( 'The local player could not start. Try again, or check that the plugin’s built assets are installed.', 'wp-asciiplayer' ) ) );
return () => {
disposed = true;
request.abort();
canvasWindow.clearInterval( readinessTimer );
canvasWindow.clearTimeout( deadline );
if ( player ) player.dispose();
container.replaceChildren();
};
}, [ source, optionsJSON, attempt ] );
return (
<div className="asciiplayer-editor__preview" data-preview-status={ status }>
{ status === 'loading' && <div className="asciiplayer-editor__status" role="status"><Spinner />{ __( 'Loading recording…', 'wp-asciiplayer' ) }</div> }
{ status === 'error' && <Notice status="error" isDismissible={ false }><p>{ problem }</p><Button variant="secondary" onClick={ onRetry }>{ __( 'Retry preview', 'wp-asciiplayer' ) }</Button></Notice> }
<div className="asciiplayer-editor__player" style={ { height: previewHeight( attributes ) } } ref={ playerRef } aria-label={ __( 'Interactive terminal recording preview', 'wp-asciiplayer' ) } />
</div>
);
}
+114
View File
@@ -0,0 +1,114 @@
/** Only inspect a small prefix; metadata must never buffer a second full cast. */
export const MAX_HEADER_BYTES = 64 * 1024;
/** Original dimensions, without the player's fallback or editor overrides. */
export function recordingSizeFromHeader( header ) {
if ( ! header || typeof header !== 'object' || Array.isArray( header ) ) return null;
let cols;
let rows;
if ( header.version === 1 || header.version === 2 ) {
cols = header.width;
rows = header.height;
} else if ( header.version === 3 ) {
cols = header.term?.cols;
rows = header.term?.rows;
} else {
return null;
}
// These are display-only hints, so do not apply the editor override limit.
const valid = ( value ) => Number.isSafeInteger( value ) && value > 0;
return valid( cols ) && valid( rows ) ? { cols, rows } : null;
}
/**
* Read complete top-level JSON members, never regex-match nested fields/output.
* v1 is one large JSON object, often pretty-printed, so its dimensions can be
* returned before stdout. v2/v3 require their complete first header object.
*/
function createHeaderReader() {
let text = '';
let cursor = 0;
let memberStart;
let quoted = false;
let escaped = false;
let members = 0;
const stack = [];
const header = Object.create( null );
const unknown = { done: true, size: null };
return ( chunk ) => {
text += chunk;
for ( ; cursor < text.length; cursor++ ) {
const character = text[ cursor ];
if ( memberStart === undefined ) {
if ( /\s/.test( character ) ) continue;
if ( character !== '{' ) return unknown;
stack.push( '{' );
memberStart = cursor + 1;
continue;
}
if ( quoted ) {
if ( escaped ) escaped = false;
else if ( character === '\\' ) escaped = true;
else if ( character === '"' ) quoted = false;
continue;
}
if ( character === '"' ) {
quoted = true;
continue;
}
if ( character === '{' || character === '[' ) {
stack.push( character );
continue;
}
const closing = character === '}' || character === ']';
if ( closing && stack.at( -1 ) !== ( character === '}' ? '{' : '[' ) ) return unknown;
if ( stack.length === 1 && ( character === ',' || closing ) ) {
const member = text.slice( memberStart, cursor ).trim();
if ( ! member && ( members || ! closing ) ) return unknown;
try {
Object.assign( header, JSON.parse( `{${ member }}` ) );
} catch {
return unknown;
}
members++;
const size = recordingSizeFromHeader( header );
if ( closing || ( header.version === 1 && size ) ) return { done: true, size };
memberStart = cursor + 1;
}
if ( closing ) stack.pop();
}
return { done: false, size: null };
};
}
/**
* Inspect a clone of the player's existing response. The original response is
* untouched, and callers can pass it to the player while this branch is read.
* Missing streams, invalid/oversized headers and read failures stay unknown.
*/
export async function readRecordingSize( response ) {
let reader;
try {
if ( ! response.ok || ! response.body?.getReader ) return null;
reader = response.clone().body.getReader();
const decode = new TextDecoder( 'utf-8', { fatal: true } );
const readHeader = createHeaderReader();
let bytes = 0;
while ( bytes < MAX_HEADER_BYTES ) {
const { value, done } = await reader.read();
if ( done ) return readHeader( decode.decode() ).size;
const prefix = value.subarray( 0, MAX_HEADER_BYTES - bytes );
bytes += prefix.byteLength;
const result = readHeader( decode.decode( prefix, { stream: true } ) );
if ( result.done ) return result.size;
}
return null;
} catch {
return null;
} finally {
// A cloned Response tees the stream. Awaiting cancellation can wait for
// the player's other branch to finish, delaying metadata or deadlocking.
if ( reader ) reader.cancel().catch( () => {} );
}
}
+77
View File
@@ -0,0 +1,77 @@
.asciiplayer-container {
box-sizing: border-box;
max-width: 100%;
margin-inline: auto;
}
/*! rtl:begin:ignore */
.asciiplayer-container .ap-wrapper {
text-align: left;
}
/*! rtl:end:ignore */
.asciiplayer-container[data-ap-status="error"] .asciiplayer-error {
padding: 1em;
border: 1px solid #b32d2e;
}
/* Keep placement separate from terminal dimensions and from theme floats. */
.asciiplayer-figure {
box-sizing: border-box;
max-width: 100%;
min-width: 0;
margin-block: 0 1em;
}
/*! rtl:begin:ignore */
.asciiplayer-figure.asciiplayer-align-left { margin-left: 0 !important; margin-right: auto !important; }
.asciiplayer-figure.asciiplayer-align-center { margin-left: auto !important; margin-right: auto !important; }
.asciiplayer-figure.asciiplayer-align-right { margin-left: auto !important; margin-right: 0 !important; }
/*! rtl:end:ignore */
.asciiplayer-figure > .asciiplayer-container { width: 100%; }
.asciiplayer-figure > figcaption {
margin-block: 0.5em 0;
font-size: 0.875em;
line-height: 1.5;
text-align: center;
overflow-wrap: anywhere;
}
/* Terminal glyph geometry must inherit the size calculated by the player,
* not a theme's code-block typography. Scope every reset to our mount points. */
:is(.asciiplayer-container, .asciiplayer-editor__player) .ap-term pre.ap-term-text {
border: 0 !important;
border-radius: 0 !important;
box-shadow: none !important;
padding: 0 !important;
margin: 0 !important;
font-family: inherit !important;
font-size: inherit !important;
line-height: var(--term-line-height) !important;
white-space: pre !important;
word-break: normal !important;
overflow-wrap: normal !important;
text-transform: none !important;
}
:is(.asciiplayer-container, .asciiplayer-editor__player) .ap-term .ap-line,
:is(.asciiplayer-container, .asciiplayer-editor__player) .ap-term .ap-line span {
font-family: inherit !important;
font-size: inherit !important;
line-height: inherit !important;
letter-spacing: normal !important;
white-space: pre !important;
text-transform: none !important;
}
:is(.asciiplayer-container, .asciiplayer-editor__player) .ap-control-bar button.ap-button {
border: 0 !important;
box-shadow: none !important;
border-radius: 0;
}
:is(.asciiplayer-container, .asciiplayer-editor__player) .ap-control-bar button.ap-button:focus-visible {
outline: 2px solid currentColor;
outline-offset: 3px;
}
+66
View File
@@ -0,0 +1,66 @@
import { __ } from '@wordpress/i18n';
import { normalizePlayerOptions, normalizeSource } from './options.js';
const instances = new WeakMap();
function showError( container ) {
container.dataset.apStatus = 'error';
if ( container.querySelector( '.asciiplayer-error' ) ) return;
const notice = container.ownerDocument.createElement( 'p' );
notice.className = 'asciiplayer-error';
notice.setAttribute( 'role', 'status' );
notice.textContent = __( 'Unable to load this terminal recording. The file may be unavailable, invalid, or blocked by the source server’s CORS policy.', 'wp-asciiplayer' );
container.appendChild( notice );
}
/** One explicit instance per front-end container; never scan an editor canvas. */
export function mountPlayers( root = document ) {
const ownerDocument = root.ownerDocument || root;
if ( ownerDocument.body?.classList.contains( 'wp-admin' ) || ownerDocument.querySelector( '.editor-styles-wrapper, .block-editor-block-list__layout' ) ) return;
const api = ownerDocument.defaultView?.AsciinemaPlayer;
if ( typeof api?.create !== 'function' ) return;
root.querySelectorAll( '.asciiplayer-container' ).forEach( ( container ) => {
if ( instances.has( container ) ) return;
const source = normalizeSource( container.dataset.apSrc );
if ( ! source ) return showError( container );
let options;
try {
// New markup uses escaped plain JSON. The legacy adapter used URL-encoded
// JSON; accepting it also lets cached old pages use the new local player.
const serialized = container.dataset.apOptions;
options = serialized ? JSON.parse( serialized ) : JSON.parse( decodeURIComponent( container.dataset.apOpts || '{}' ) );
if ( ! options || Array.isArray( options ) || typeof options !== 'object' ) throw new Error( 'Invalid player options.' );
options = normalizePlayerOptions( options );
} catch {
showError( container );
return;
}
try {
container.dataset.apStatus = 'loading';
const player = api.create( source, container, options );
instances.set( container, player );
player.addEventListener( 'error', () => showError( container ) );
player.addEventListener( 'playing', () => { container.dataset.apStatus = 'ready'; } );
// The upstream player owns loading/error/controls; readiness is confirmed
// by its parsed duration rather than merely by a mounted DOM wrapper.
if ( options.preload || options.autoPlay || options.poster?.startsWith( 'npt:' ) ) {
let ticks = 0;
const timer = ownerDocument.defaultView.setInterval( () => {
const duration = player.getDuration();
if ( typeof duration === 'number' && Number.isFinite( duration ) ) container.dataset.apStatus = 'ready';
if ( ! container.isConnected || container.dataset.apStatus !== 'loading' || ++ticks > 200 ) ownerDocument.defaultView.clearInterval( timer );
}, 150 );
} else {
container.dataset.apStatus = 'idle';
}
} catch {
showError( container );
}
} );
}
if ( document.readyState === 'loading' ) {
document.addEventListener( 'DOMContentLoaded', () => mountPlayers(), { once: true } );
} else {
mountPlayers();
}