mirror of
https://github.com/LamGC/wp-asciiplayer.git
synced 2026-11-26 20:55:48 +00:00
Add responsive player layout, captions and native terminal sizing
This commit is contained in:
@@ -0,0 +1 @@
|
||||
{ "preset": ["default", { "discardComments": { "removeAll": false } }] }
|
||||
+9
-2
@@ -10,9 +10,16 @@ GitHub 源码 ZIP 需要先构建,不能直接当发行包安装。构建方
|
||||
要求 WordPress 6.3+、PHP 7.4+;具体测试版本见仓库 CI。
|
||||
|
||||
插入「Asciicast Player」区块,粘贴录制文件的 HTTP(S) URL,应用后即可在编辑器内播放、
|
||||
暂停和拖动。主题、速度、循环、控制栏、尺寸、起始时间和空闲压缩等选项在区块设置中调整。
|
||||
暂停和拖动。「Display」面板提供展示宽度预设、自定义宽度(例如 `480px`、`65%`)以及左、中、右对齐;
|
||||
展示宽度会限制在当前页面可用空间内。点击播放器下方即可添加描述文字。
|
||||
|
||||
「Terminal size」与展示大小分别控制:Columns / Rows 留空时,使用 cast 文件记录的终端尺寸,
|
||||
并跟随录制中的 resize 事件。只有需要改变终端网格时才覆盖行列数,点击「Use recording size」可恢复。
|
||||
展示宽度与 `fit: width` 只缩放画面,不会修改终端行列数;覆盖网格可能影响录屏排版或裁切内容。
|
||||
主题、速度、循环、控制栏、起始时间和空闲压缩等选项仍在区块设置中调整。
|
||||
保存文章或页面后,前台使用同一播放器。重新打开已有区块时点击「Load preview」加载预览;
|
||||
编辑预览不会自动播放,前台自动播放设置仍会保留。
|
||||
编辑预览不会自动播放,前台自动播放设置仍会保留。区块插入器使用本地静态示例,不请求录制文件。
|
||||
播放器增加了局部样式隔离,避免常见主题的代码块边框、阴影和字体设置干扰终端;键盘焦点提示仍保留。
|
||||
|
||||
URL 必须指向录制文件(例如 `.cast`),不能直接使用分享页面地址。跨域文件需要允许
|
||||
来自你站点的 CORS 请求;HTTPS 页面上的 HTTP 文件可能被浏览器阻止。优先使用同源 HTTPS。
|
||||
|
||||
@@ -16,13 +16,26 @@ site and theme; CI tests the versions listed in `.github/workflows/ci.yml`.
|
||||
|
||||
1. Insert **Asciicast Player**.
|
||||
2. Paste an HTTP(S) recording-file URL (for example a `.cast` file), then apply it.
|
||||
3. Play, pause and seek in the editor. Change theme, speed, looping, controls,
|
||||
width/fit, start time and idle-time limit from the block settings.
|
||||
4. Save the post or page; the same locally bundled player is used on the front end.
|
||||
3. Play, pause and seek in the editor. **Display** offers width presets or a custom
|
||||
CSS length (for example `480px` or `65%`), plus left/center/right alignment.
|
||||
The width stays within the available space. Add a caption below the player.
|
||||
4. **Terminal size** is separate: leave Columns and Rows blank to use the cast
|
||||
file's dimensions and recorded resize events. Override either axis only when
|
||||
intentional; use **Use recording size** to clear both. Display width and
|
||||
`fit: width` scale the existing grid without changing terminal columns.
|
||||
5. Change theme, speed, looping, controls, fit, start time and idle-time limit
|
||||
from the remaining block settings.
|
||||
6. Save the post or page; the same locally bundled player is used on the front end.
|
||||
|
||||
Existing saved blocks show a **Load preview** action on reopening the editor.
|
||||
This keeps external recordings from loading until you choose to preview them.
|
||||
Preview does not autoplay even when front-end autoplay is enabled.
|
||||
The inserter preview is a local static example and never loads a recording.
|
||||
|
||||
Terminal typography is scoped against common theme `pre`/`span` styles so
|
||||
character scaling stays aligned with the player grid. A theme with additional
|
||||
custom rules may still require compatibility testing; keyboard focus indicators
|
||||
remain visible.
|
||||
|
||||
The source must be a recording-file URL, not an asciinema share-page URL.
|
||||
A recording on another origin must allow CORS requests from your WordPress site.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* Plugin Name: Asciicast Player
|
||||
* Plugin URI: https://github.com/LamGC/wp-asciiplayer
|
||||
* Description: Add interactive terminal recordings to posts and pages with a block or shortcode.
|
||||
* Version: 1.1.0
|
||||
* Version: 1.2.0
|
||||
* Requires at least: 6.3
|
||||
* Requires PHP: 7.4
|
||||
* Author: LamGC
|
||||
@@ -21,7 +21,7 @@ if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
const VERSION = '1.1.0';
|
||||
const VERSION = '1.2.0';
|
||||
const PLUGIN_FILE = __FILE__;
|
||||
const SHORTCODE = 'asciiplayer';
|
||||
|
||||
|
||||
+5
-1
@@ -2,7 +2,7 @@
|
||||
"$schema": "https://schemas.wp.org/trunk/block.json",
|
||||
"apiVersion": 3,
|
||||
"name": "lamgc/asciiplayer",
|
||||
"version": "1.1.0",
|
||||
"version": "1.2.0",
|
||||
"title": "Asciicast Player",
|
||||
"category": "media",
|
||||
"icon": "editor-code",
|
||||
@@ -21,6 +21,9 @@
|
||||
"autoPlay": { "type": "boolean", "default": false },
|
||||
"preload": { "type": "boolean", "default": true },
|
||||
"width": { "type": "string", "default": "100%" },
|
||||
"displayAlign": { "type": "string", "default": "center", "enum": ["left", "center", "right"] },
|
||||
"caption": { "type": "string", "default": "" },
|
||||
"isExample": { "type": "boolean", "default": false },
|
||||
"legacyStyle": { "type": "string", "default": "" },
|
||||
"cols": { "type": "number" },
|
||||
"rows": { "type": "number" },
|
||||
@@ -29,6 +32,7 @@
|
||||
"terminalLineHeight": { "type": "number" },
|
||||
"poster": { "type": "string" }
|
||||
},
|
||||
"example": { "attributes": { "isExample": true } },
|
||||
"supports": { "html": false, "align": ["wide", "full"] },
|
||||
"editorScript": "lamgc-asciiplayer-editor",
|
||||
"viewScript": "lamgc-asciiplayer-view",
|
||||
|
||||
@@ -45,6 +45,8 @@ function normalize_attributes( $attributes ) {
|
||||
'terminallineheight' => 'terminalLineHeight',
|
||||
'poster' => 'poster',
|
||||
'width' => 'width',
|
||||
'displayalign' => 'displayAlign',
|
||||
'caption' => 'caption',
|
||||
'style' => 'legacyStyle',
|
||||
'legacystyle' => 'legacyStyle',
|
||||
);
|
||||
|
||||
+24
-6
@@ -33,15 +33,33 @@ function render_player( $attributes = array(), $content = null, $block = false )
|
||||
|
||||
enqueue_player_assets();
|
||||
$style = player_style( $attributes );
|
||||
$wrapper = $block
|
||||
? get_block_wrapper_attributes( array( 'class' => 'asciiplayer-container', 'style' => $style ) )
|
||||
: 'class="asciiplayer-container"' . ( '' === $style ? '' : ' style="' . esc_attr( $style ) . '"' );
|
||||
return sprintf(
|
||||
'<div %1$s data-ap-src="%2$s" data-ap-options="%3$s"></div>',
|
||||
$wrapper,
|
||||
// The mount point owns only the player. Captions must stay outside it so
|
||||
// upstream disposal/reinitialization cannot remove author-written content.
|
||||
$mount_style = $style;
|
||||
$figure_style = '';
|
||||
if ( $block ) {
|
||||
// Keep height and other legacy player-container declarations on the
|
||||
// mount point. Only width moves to the figure, so captions add height.
|
||||
if ( preg_match_all( '/(?:^|;)\s*width\s*:\s*([^;]+)/i', $style, $widths ) ) {
|
||||
$figure_style = 'width:' . end( $widths[1] ) . ';';
|
||||
}
|
||||
$mount_style = trim( preg_replace( '/(^|;)\s*width\s*:[^;]*/i', '$1', $style ), '; ' );
|
||||
}
|
||||
$player = sprintf(
|
||||
'<div class="asciiplayer-container"%1$s data-ap-src="%2$s" data-ap-options="%3$s"></div>',
|
||||
'' !== $mount_style ? ' style="' . esc_attr( $mount_style ) . '"' : '',
|
||||
esc_url( $source, array( 'http', 'https' ) ),
|
||||
esc_attr( $options )
|
||||
);
|
||||
if ( ! $block ) {
|
||||
return $player;
|
||||
}
|
||||
$alignment = isset( $attributes['displayAlign'] ) && in_array( $attributes['displayAlign'], array( 'left', 'center', 'right' ), true ) ? $attributes['displayAlign'] : 'center';
|
||||
$wrapper = get_block_wrapper_attributes( array( 'class' => 'asciiplayer-block' ) );
|
||||
$figure = 'class="asciiplayer-figure asciiplayer-align-' . esc_attr( $alignment ) . '"' . ( '' !== $figure_style ? ' style="' . esc_attr( $figure_style ) . '"' : '' );
|
||||
// RichText emits escaped text and line breaks. No other markup is needed.
|
||||
$caption = isset( $attributes['caption'] ) ? wp_kses( (string) $attributes['caption'], array( 'br' => array() ) ) : '';
|
||||
return '<div ' . $wrapper . '><figure ' . $figure . '>' . $player . ( '' !== trim( $caption ) ? '<figcaption class="wp-element-caption">' . $caption . '</figcaption>' : '' ) . '</figure></div>';
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "wp-asciiplayer",
|
||||
"version": "1.1.0",
|
||||
"version": "1.2.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "wp-asciiplayer",
|
||||
"version": "1.1.0",
|
||||
"version": "1.2.0",
|
||||
"license": "GPL-3.0-only",
|
||||
"dependencies": {
|
||||
"asciinema-player": "3.17.0"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "wp-asciiplayer",
|
||||
"version": "1.1.0",
|
||||
"version": "1.2.0",
|
||||
"private": true,
|
||||
"description": "Native WordPress asciicast block with real playback previews and compatible shortcodes",
|
||||
"type": "module",
|
||||
|
||||
+7
-1
@@ -4,7 +4,7 @@ Tags: asciicast, asciiplayer, asciinema, terminal, block
|
||||
Requires at least: 6.3
|
||||
Tested up to: 7.1
|
||||
Requires PHP: 7.4
|
||||
Stable tag: 1.1.0
|
||||
Stable tag: 1.2.0
|
||||
License: GPL-3.0-only
|
||||
License URI: https://www.gnu.org/licenses/gpl-3.0.html
|
||||
|
||||
@@ -54,6 +54,12 @@ Existing shortcodes work in the Classic Editor. The new visual controls and inli
|
||||
|
||||
== Changelog ==
|
||||
|
||||
= 1.2.0 =
|
||||
* Add responsive display-width presets/custom lengths, left/center/right placement and captions.
|
||||
* Preserve recorded terminal dimensions and resize events by default; expose optional row/column overrides.
|
||||
* Isolate terminal typography and frames from common host-theme code-block styles.
|
||||
* Add a local static block-inserter preview without recording requests.
|
||||
|
||||
= 1.1.0 =
|
||||
* Add a native block with typed controls and interactive, iframe-aware preview.
|
||||
* Preserve shortcode support and normalize historical parameter names and types.
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ const readme = await readFile(path.join(root, 'readme.txt'), 'utf8');
|
||||
if (!php.includes(`Version: ${pkg.version}`) || !readme.includes(`Stable tag: ${pkg.version}`)) throw new Error('Version headers disagree.');
|
||||
const temp = await mkdtemp(path.join(os.tmpdir(), 'wp-asciiplayer-package-'));
|
||||
const target = path.join(temp, 'wp-asciiplayer');
|
||||
const inputs = ['asciicast-player.php', 'includes', 'build', 'LICENSE', 'licenses', 'THIRD-PARTY-NOTICES.md', 'README.md', 'README-zh.md', 'readme.txt', 'SOURCE.md', 'src', 'block.json', 'package.json', 'package-lock.json', 'webpack.config.cjs', 'babel.config.json', 'scripts'];
|
||||
const inputs = ['asciicast-player.php', 'includes', 'build', 'LICENSE', 'licenses', 'THIRD-PARTY-NOTICES.md', 'README.md', 'README-zh.md', 'readme.txt', 'SOURCE.md', 'src', 'block.json', 'package.json', 'package-lock.json', 'webpack.config.cjs', '.cssnanorc.json', 'babel.config.json', 'scripts'];
|
||||
try {
|
||||
await mkdir(target);
|
||||
for (const file of inputs) await cp(path.join(root, file), path.join(target, file), { recursive: true });
|
||||
|
||||
@@ -51,3 +51,11 @@ for (const readyState of ['loading', 'complete']) {
|
||||
assert.equal(container.dataset.apStatus, 'idle');
|
||||
}
|
||||
console.log('Verified WordPress 6.3 dependencies, block metadata, exact vendor files, and emitted frontend boot.');
|
||||
|
||||
// Physical placement and terminal direction must not be mirrored by RTLCSS.
|
||||
for (const suffix of ['', '-rtl']) {
|
||||
const css = await readFile(`build/style-index${suffix}.css`, 'utf8');
|
||||
assert.match(css, /asciiplayer-align-left\{[^}]*margin-left:0!important[^}]*margin-right:auto!important/);
|
||||
assert.match(css, /asciiplayer-align-right\{[^}]*margin-left:auto!important[^}]*margin-right:0!important/);
|
||||
assert.match(css, /asciiplayer-container \.ap-wrapper\{text-align:left/);
|
||||
}
|
||||
|
||||
+34
-9
@@ -1,16 +1,18 @@
|
||||
import { InspectorControls, useBlockProps } from '@wordpress/block-editor';
|
||||
import { BlockAlignmentToolbar, BlockControls, InspectorControls, RichText, useBlockProps } from '@wordpress/block-editor';
|
||||
import { Button, Notice, PanelBody, Placeholder, RangeControl, SelectControl, TextControl, ToggleControl } from '@wordpress/components';
|
||||
import { useEffect, useState } from '@wordpress/element';
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import { finiteNumber, normalizeSource, normalizeWidth } from './options.js';
|
||||
import { finiteNumber, normalizeDisplayAlign, normalizeSource, normalizeWidth, terminalDimension } from './options.js';
|
||||
import Preview from './preview.js';
|
||||
|
||||
export default function Edit( { attributes, setAttributes } ) {
|
||||
const { source, theme, speed, loop, controls, fit, startAt, idleTimeLimit, autoPlay, preload, width } = attributes;
|
||||
export default function Edit( { attributes, setAttributes, isSelected } ) {
|
||||
const { source, theme, speed, loop, controls, fit, startAt, idleTimeLimit, autoPlay, preload, width, caption, displayAlign, cols, rows } = attributes;
|
||||
const [ draftSource, setDraftSource ] = useState( source );
|
||||
const [ approvedSource, setApprovedSource ] = useState( '' );
|
||||
const [ urlError, setUrlError ] = useState( false );
|
||||
const [ attempt, setAttempt ] = useState( 0 );
|
||||
const [ draftWidth, setDraftWidth ] = useState( width );
|
||||
useEffect( () => setDraftWidth( width ), [ width ] );
|
||||
useEffect( () => setDraftSource( source ), [ source ] );
|
||||
const blockProps = useBlockProps( { className: 'asciiplayer-editor' } );
|
||||
const applySource = ( event ) => {
|
||||
@@ -31,16 +33,35 @@ export default function Edit( { attributes, setAttributes } ) {
|
||||
{ label: 'Solarized Light', value: 'solarized-light' }, { label: 'Tango', value: 'tango' },
|
||||
];
|
||||
if ( ! themes.some( ( option ) => option.value === theme ) ) themes.push( { label: theme, value: theme } );
|
||||
const widthOptions = [ '100%', '80%', '60%', '50%' ].map( ( value ) => ( { label: value, value } ) );
|
||||
if ( ! widthOptions.some( ( option ) => option.value === width ) ) widthOptions.push( { label: width, value: width } );
|
||||
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 ) } ) } /></BlockControls>
|
||||
<InspectorControls>
|
||||
<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={ __( 'Terminal size', 'wp-asciiplayer' ) } initialOpen={ false }>
|
||||
<p>{ __( 'Leave blank to use the size recorded in the cast file, including recorded resize events. Overrides change the terminal grid and can alter or crop the recording’s layout.', 'wp-asciiplayer' ) }</p>
|
||||
<TextControl label={ __( 'Columns', 'wp-asciiplayer' ) } type="number" min="1" max="1000" step="1" value={ cols ?? '' } placeholder={ __( 'From recording', 'wp-asciiplayer' ) } onChange={ ( value ) => setAttributes( { cols: terminalDimension( value ) } ) } />
|
||||
<TextControl label={ __( 'Rows', 'wp-asciiplayer' ) } type="number" min="1" max="1000" step="1" value={ rows ?? '' } placeholder={ __( 'From recording', 'wp-asciiplayer' ) } onChange={ ( value ) => setAttributes( { rows: terminalDimension( value ) } ) } />
|
||||
<Button variant="secondary" onClick={ () => setAttributes( { cols: undefined, rows: undefined } ) }>{ __( 'Use recording size', 'wp-asciiplayer' ) }</Button>
|
||||
</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 } ) } />
|
||||
@@ -57,7 +78,6 @@ export default function Edit( { attributes, setAttributes } ) {
|
||||
{ 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 } ) } />
|
||||
<SelectControl label={ __( 'Player width', 'wp-asciiplayer' ) } value={ width } options={ widthOptions } onChange={ ( value ) => setAttributes( { width: value } ) } />
|
||||
{ attributes.legacyStyle && <p>{ __( 'The custom container style from your shortcode is preserved on the published page.', 'wp-asciiplayer' ) }</p> }
|
||||
</PanelBody>
|
||||
</InspectorControls>
|
||||
@@ -70,15 +90,20 @@ export default function Edit( { attributes, setAttributes } ) {
|
||||
<p className="asciiplayer-editor__privacy">{ __( 'Applying a URL loads the recording directly from that server, which receives your browser’s request. Published players contact the same server. Use a direct .cast URL; external servers must allow CORS.', 'wp-asciiplayer' ) }</p>
|
||||
{ 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 ) } }>
|
||||
{ approvedSource && approvedSource === source ? (
|
||||
<div style={ { width: normalizeWidth( width ), maxWidth: '100%' } }>
|
||||
<>
|
||||
<Preview source={ source } attributes={ attributes } attempt={ attempt } onRetry={ () => setAttempt( ( current ) => current + 1 ) } />
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<Placeholder icon="editor-code" label={ __( 'Asciicast Player', 'wp-asciiplayer' ) } instructions={ source ? __( 'Load the saved recording to play and adjust it here.', 'wp-asciiplayer' ) : __( 'Paste a terminal recording URL above, then apply it to see an interactive preview.', 'wp-asciiplayer' ) }>
|
||||
{ source && <Button variant="secondary" onClick={ () => { setApprovedSource( source ); setAttempt( ( current ) => current + 1 ); } }>{ __( 'Load preview', 'wp-asciiplayer' ) }</Button> }
|
||||
</Placeholder>
|
||||
) }
|
||||
{ ( isSelected || caption ) && <RichText tagName="figcaption" className="wp-element-caption" value={ caption } allowedFormats={ [] } onChange={ ( value ) => setAttributes( { caption: value } ) } placeholder={ __( 'Add a caption…', 'wp-asciiplayer' ) } aria-label={ __( 'Recording caption', 'wp-asciiplayer' ) } /> }
|
||||
</figure>
|
||||
{ approvedSource === source && source && <p className="asciiplayer-editor__hint">{ __( 'Use the player controls to play, pause, and seek. Autoplay is disabled only in the editor.', 'wp-asciiplayer' ) }</p> }
|
||||
{ [ '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>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -30,10 +30,12 @@
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
/*! rtl:begin:ignore */
|
||||
.asciiplayer-editor__player {
|
||||
min-width: 0;
|
||||
text-align: left;
|
||||
}
|
||||
/*! rtl:end:ignore */
|
||||
|
||||
.asciiplayer-editor__status {
|
||||
display: flex;
|
||||
@@ -48,3 +50,11 @@
|
||||
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; }
|
||||
|
||||
@@ -39,6 +39,16 @@ export function normalizeWidth( value ) {
|
||||
? 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;
|
||||
|
||||
@@ -61,8 +61,6 @@ export default function Preview( { source, attributes, attempt, onRetry } ) {
|
||||
{ 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' ) } />
|
||||
{ [ 'height', 'both' ].includes( attributes.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> }
|
||||
<p className="asciiplayer-editor__hint">{ __( 'Use the player controls to play, pause, and seek. Autoplay is disabled only in the editor.', 'wp-asciiplayer' ) }</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
+63
-1
@@ -1,15 +1,77 @@
|
||||
.wp-block-lamgc-asciiplayer,
|
||||
.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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const blockName = 'lamgc/asciiplayer';
|
||||
const fixturePath = '/wp-content/uploads/asciiplayer-fixtures/hello.cast';
|
||||
|
||||
async function openEditor(page) {
|
||||
await page.goto('/wp-login.php');
|
||||
await page.locator('#user_login').fill(process.env.WP_USERNAME || 'admin');
|
||||
await page.locator('#user_pass').fill(process.env.WP_PASSWORD || 'password');
|
||||
await page.locator('#wp-submit').click();
|
||||
await expect(page).toHaveURL(/\/wp-admin\//);
|
||||
await page.goto('/wp-admin/post-new.php');
|
||||
await page.waitForFunction((name) => Boolean(
|
||||
window.wp?.blocks?.getBlockType(name) &&
|
||||
window.wp?.data?.select('core/editor')?.getCurrentPostId()
|
||||
), blockName);
|
||||
await page.evaluate(() => {
|
||||
for (const scope of ['core/edit-post', 'core/editor']) {
|
||||
window.wp.data.dispatch('core/preferences').set(scope, 'welcomeGuide', false);
|
||||
}
|
||||
});
|
||||
await expect(page.locator('iframe[name="editor-canvas"]')).toBeVisible();
|
||||
}
|
||||
|
||||
async function insertPlayer(page, attributes = {}) {
|
||||
const id = await page.evaluate(({ name, attrs }) => {
|
||||
const block = window.wp.blocks.createBlock(name, attrs);
|
||||
window.wp.data.dispatch('core/block-editor').insertBlocks(block);
|
||||
window.wp.data.dispatch('core/block-editor').selectBlock(block.clientId);
|
||||
return block.clientId;
|
||||
}, { name: blockName, attrs: attributes });
|
||||
return { id, block: page.frameLocator('iframe[name="editor-canvas"]').locator(`[data-block="${id}"]`) };
|
||||
}
|
||||
|
||||
async function attributes(page, id) {
|
||||
return page.evaluate((clientId) => window.wp.data.select('core/block-editor').getBlockAttributes(clientId), id);
|
||||
}
|
||||
|
||||
async function loadPreview(block) {
|
||||
await block.getByRole('button', { name: 'Load preview', exact: true }).click();
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready');
|
||||
await expect(block.locator('.ap-wrapper')).toHaveCount(1);
|
||||
}
|
||||
|
||||
async function openInspectorPanel(page, name, control) {
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
|
||||
if (!await control.isVisible()) {
|
||||
await page.getByRole('button', { name, exact: true }).click();
|
||||
}
|
||||
await expect(control).toBeVisible();
|
||||
}
|
||||
|
||||
async function publish(page, title) {
|
||||
return page.evaluate(async (postTitle) => {
|
||||
const editor = window.wp.data.dispatch('core/editor');
|
||||
editor.editPost({ title: postTitle, status: 'publish' });
|
||||
await editor.savePost();
|
||||
const state = window.wp.data.select('core/editor');
|
||||
if (state.didPostSaveRequestFail()) throw new Error('WordPress could not save the test post.');
|
||||
return { id: state.getCurrentPostId(), url: state.getPermalink() };
|
||||
}, title);
|
||||
}
|
||||
|
||||
async function grid(container) {
|
||||
// These are the live VT dimensions rendered by bundled asciinema-player,
|
||||
// not the WordPress attributes or an inferred CSS aspect ratio.
|
||||
return container.locator('.ap-term').evaluate((terminal) => ({
|
||||
cols: Number(terminal.style.getPropertyValue('--term-cols')),
|
||||
rows: Number(terminal.style.getPropertyValue('--term-rows')),
|
||||
}));
|
||||
}
|
||||
|
||||
async function expectGrid(container, cols, rows) {
|
||||
await expect(container.locator('.ap-term')).toBeVisible();
|
||||
await expect.poll(() => grid(container)).toEqual({ cols, rows });
|
||||
await expect(container.locator('.ap-term-text > .ap-line')).toHaveCount(rows);
|
||||
}
|
||||
|
||||
async function figureMetrics(figure) {
|
||||
return figure.evaluate((element) => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
const parent = element.parentElement;
|
||||
const outer = parent.getBoundingClientRect();
|
||||
const style = getComputedStyle(parent);
|
||||
const left = outer.left + parseFloat(style.borderLeftWidth) + parseFloat(style.paddingLeft);
|
||||
const right = outer.right - parseFloat(style.borderRightWidth) - parseFloat(style.paddingRight);
|
||||
return {
|
||||
width: rect.width,
|
||||
available: right - left,
|
||||
leftGap: rect.left - left,
|
||||
rightGap: right - rect.right,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function expectAlignment(figure, alignment, fraction = 0.5) {
|
||||
await expect.poll(async () => {
|
||||
const dimensions = await figureMetrics(figure);
|
||||
return Math.abs(dimensions.width - dimensions.available * fraction);
|
||||
}).toBeLessThan(3);
|
||||
await expect.poll(async () => {
|
||||
const { leftGap, rightGap } = await figureMetrics(figure);
|
||||
return alignment === 'center' ? Math.abs(leftGap - rightGap) : Math.abs(alignment === 'left' ? leftGap : rightGap);
|
||||
}).toBeLessThan(3);
|
||||
}
|
||||
|
||||
async function screenshot(page, testInfo, name) {
|
||||
const path = testInfo.outputPath(`${name}.png`);
|
||||
await page.screenshot({ path, fullPage: true });
|
||||
await testInfo.attach(name, { path, contentType: 'image/png' });
|
||||
}
|
||||
|
||||
test('display width, alignment and caption survive editor save/reload without changing the recording grid', async ({ page }, testInfo) => {
|
||||
await openEditor(page);
|
||||
const source = new URL(fixturePath, page.url()).href;
|
||||
const { id, block } = await insertPlayer(page, { source, controls: 'always' });
|
||||
await loadPreview(block);
|
||||
await expectGrid(block, 64, 12);
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
const figure = block.locator('.asciiplayer-figure');
|
||||
const width = page.getByRole('combobox', { name: 'Player width', exact: true });
|
||||
await openInspectorPanel(page, 'Display', width);
|
||||
// Keep a marker on the actual terminal: display-only changes must neither
|
||||
// reconstruct it nor alter rows/columns, so playback position is preserved.
|
||||
await block.locator('.ap-term').evaluate((element) => { element.dataset.layoutIdentity = 'unchanged'; });
|
||||
await width.selectOption('50%');
|
||||
const alignment = page.getByRole('combobox', { name: 'Display alignment', exact: true });
|
||||
for (const value of ['left', 'center', 'right']) {
|
||||
await alignment.selectOption(value);
|
||||
await expectAlignment(figure, value);
|
||||
await expectGrid(block, 64, 12);
|
||||
await expect(block.locator('.ap-term')).toHaveAttribute('data-layout-identity', 'unchanged');
|
||||
}
|
||||
await width.selectOption('custom');
|
||||
const customWidth = page.getByRole('textbox', { name: 'Custom width', exact: true });
|
||||
await customWidth.fill('240px');
|
||||
await customWidth.press('Tab');
|
||||
await expect.poll(async () => Math.abs((await figure.boundingBox()).width - 240)).toBeLessThan(2);
|
||||
await customWidth.fill('calc(100% - 20px)');
|
||||
await customWidth.press('Tab');
|
||||
await expect(customWidth).toHaveAttribute('aria-invalid', 'true');
|
||||
expect((await attributes(page, id)).width).toBe('240px');
|
||||
await width.selectOption('50%');
|
||||
const caption = figure.locator('figcaption[contenteditable="true"]');
|
||||
await caption.fill('Example terminal session');
|
||||
await caption.press('Tab');
|
||||
await expect.poll(async () => (await attributes(page, id)).caption).toContain('Example terminal session');
|
||||
const saved = await publish(page, 'Player display layout regression');
|
||||
await screenshot(page, testInfo, 'layout-editor-desktop');
|
||||
await page.reload();
|
||||
await page.waitForFunction((name) => window.wp?.data?.select('core/block-editor')?.getBlocks().some((block) => block.name === name), blockName);
|
||||
const reloaded = await page.evaluate((name) => window.wp.data.select('core/block-editor').getBlocks().find((block) => block.name === name), blockName);
|
||||
expect(reloaded.attributes).toMatchObject({ source, width: '50%', displayAlign: 'right', caption: 'Example terminal session' });
|
||||
expect(reloaded.attributes.cols).toBeUndefined();
|
||||
expect(reloaded.attributes.rows).toBeUndefined();
|
||||
const reloadedBlock = page.frameLocator('iframe[name="editor-canvas"]').locator(`[data-block="${reloaded.clientId}"]`);
|
||||
await loadPreview(reloadedBlock);
|
||||
await expectGrid(reloadedBlock, 64, 12);
|
||||
await expectAlignment(reloadedBlock.locator('.asciiplayer-figure'), 'right');
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await expectGrid(reloadedBlock, 64, 12);
|
||||
const editorCanvasWidth = await page.locator('iframe[name="editor-canvas"]').evaluate((element) => element.clientWidth);
|
||||
await expect.poll(async () => (await reloadedBlock.locator('.ap-wrapper').boundingBox()).width).toBeLessThanOrEqual(editorCanvasWidth);
|
||||
await screenshot(page, testInfo, 'layout-editor-mobile');
|
||||
await page.setViewportSize({ width: 1280, height: 720 });
|
||||
await page.goto(saved.url);
|
||||
const frontend = page.locator('.asciiplayer-container');
|
||||
const frontendFigure = page.locator('.asciiplayer-figure');
|
||||
await expectGrid(frontend, 64, 12);
|
||||
await expect(frontendFigure.locator('figcaption')).toHaveText('Example terminal session');
|
||||
await expectAlignment(frontendFigure, 'right');
|
||||
const options = JSON.parse(await frontend.getAttribute('data-ap-options'));
|
||||
expect(options).not.toHaveProperty('cols');
|
||||
expect(options).not.toHaveProperty('rows');
|
||||
expect(options).not.toHaveProperty('width');
|
||||
expect(options).not.toHaveProperty('caption');
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await expectGrid(frontend, 64, 12);
|
||||
await expectAlignment(frontendFigure, 'right');
|
||||
const bounds = await frontendFigure.boundingBox();
|
||||
expect(bounds.x).toBeGreaterThanOrEqual(0);
|
||||
expect(bounds.x + bounds.width).toBeLessThanOrEqual(391);
|
||||
await screenshot(page, testInfo, 'layout-frontend-mobile');
|
||||
});
|
||||
|
||||
test('optional columns and rows override the grid and clearing or resetting restores recording metadata', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
const source = new URL(fixturePath, page.url()).href;
|
||||
const { id, block } = await insertPlayer(page, { source });
|
||||
await loadPreview(block);
|
||||
const columns = page.getByRole('spinbutton', { name: 'Columns', exact: true });
|
||||
const rows = page.getByRole('spinbutton', { name: 'Rows', exact: true });
|
||||
await openInspectorPanel(page, 'Terminal size', columns);
|
||||
await expect(columns).toHaveValue('');
|
||||
await expect(rows).toHaveValue('');
|
||||
await columns.fill('88');
|
||||
await columns.press('Tab');
|
||||
await rows.fill('16');
|
||||
await rows.press('Tab');
|
||||
await expectGrid(block, 88, 16);
|
||||
await columns.fill('');
|
||||
await columns.press('Tab');
|
||||
await expectGrid(block, 64, 16);
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
await columns.fill('88');
|
||||
await columns.press('Tab');
|
||||
await expectGrid(block, 88, 16);
|
||||
await page.getByRole('button', { name: 'Use recording size', exact: true }).click();
|
||||
await expectGrid(block, 64, 12);
|
||||
await expect(columns).toHaveValue('');
|
||||
await expect(rows).toHaveValue('');
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
const saved = await publish(page, 'Reset terminal dimensions regression');
|
||||
await page.goto(saved.url);
|
||||
const frontend = page.locator('.asciiplayer-container');
|
||||
await expectGrid(frontend, 64, 12);
|
||||
const options = JSON.parse(await frontend.getAttribute('data-ap-options'));
|
||||
expect(options).not.toHaveProperty('cols');
|
||||
expect(options).not.toHaveProperty('rows');
|
||||
});
|
||||
|
||||
test('recorded resize events remain authoritative except on explicitly overridden axes', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
const source = new URL('/wp-content/uploads/asciiplayer-fixtures/resize.cast', page.url()).href;
|
||||
const cases = [
|
||||
{ overrides: {}, cols: 96, rows: 18 },
|
||||
{ overrides: { cols: 80 }, cols: 80, rows: 18 },
|
||||
{ overrides: { rows: 24 }, cols: 96, rows: 24 },
|
||||
{ overrides: { cols: 80, rows: 24 }, cols: 80, rows: 24 },
|
||||
];
|
||||
for (const entry of cases) {
|
||||
const { block } = await insertPlayer(page, { source, startAt: 2, ...entry.overrides });
|
||||
await loadPreview(block);
|
||||
await expectGrid(block, entry.overrides.cols ?? 64, entry.overrides.rows ?? 12);
|
||||
await block.locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expectGrid(block, entry.cols, entry.rows);
|
||||
}
|
||||
const saved = await publish(page, 'Recording resize and explicit axes regression');
|
||||
await page.goto(saved.url);
|
||||
const players = page.locator('.asciiplayer-container');
|
||||
await expect(players).toHaveCount(cases.length);
|
||||
for (const [index, entry] of cases.entries()) {
|
||||
await expectGrid(players.nth(index), entry.overrides.cols ?? 64, entry.overrides.rows ?? 12);
|
||||
await players.nth(index).locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expectGrid(players.nth(index), entry.cols, entry.rows);
|
||||
await expect(players.nth(index).locator('.ap-term-text')).toContainText('Resized recording grid');
|
||||
}
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
for (const [index, entry] of cases.entries()) await expectGrid(players.nth(index), entry.cols, entry.rows);
|
||||
});
|
||||
|
||||
test('published figures preserve all alignments, safe captions and terminal typography under theme CSS', async ({ page }, testInfo) => {
|
||||
await openEditor(page);
|
||||
const source = new URL(fixturePath, page.url()).href;
|
||||
const caption = 'Safe caption<br>with a second line & literal text';
|
||||
for (const displayAlign of ['left', 'center', 'right']) {
|
||||
await insertPlayer(page, { source, width: '50%', displayAlign, caption });
|
||||
}
|
||||
// Raw block attributes can come from REST/imported post content, bypassing
|
||||
// RichText's editor filtering. The server must sanitize them independently.
|
||||
await insertPlayer(page, {
|
||||
source,
|
||||
caption: '<script>window.__captionXss = true</script><img src="x" onerror="window.__captionXss = true"><a href="javascript:window.__captionXss=true">unsafe link</a><strong>Still safe</strong>',
|
||||
});
|
||||
const saved = await publish(page, 'Frontend figure and caption sanitization regression');
|
||||
await page.addInitScript((content) => {
|
||||
const install = () => {
|
||||
if (!document.documentElement) return false;
|
||||
const stylesheet = document.createElement('style');
|
||||
stylesheet.textContent = content;
|
||||
document.documentElement.appendChild(stylesheet);
|
||||
return true;
|
||||
};
|
||||
if (!install()) {
|
||||
const observer = new MutationObserver(() => { if (install()) observer.disconnect(); });
|
||||
observer.observe(document, { childList: true, subtree: true });
|
||||
}
|
||||
}, `
|
||||
body { letter-spacing: 1.5px; line-height: 2; text-align: center; }
|
||||
figure { margin: 2em 40px; }
|
||||
pre { padding: 24px !important; margin: 24px !important; font-family: serif !important; font-size: 24px !important; line-height: 2 !important; white-space: pre-wrap !important; border: 2px solid red !important; box-shadow: 0 0 0 3px red !important; }
|
||||
pre span { font-family: serif !important; font-size: 24px !important; line-height: 2 !important; letter-spacing: 2px !important; }
|
||||
button { border: 2px solid red !important; box-shadow: 0 0 0 3px red !important; }
|
||||
`);
|
||||
await page.goto(saved.url);
|
||||
const figures = page.locator('.asciiplayer-figure');
|
||||
const desktopFontSizes = [];
|
||||
await expect(figures).toHaveCount(4);
|
||||
for (const [index, displayAlign] of ['left', 'center', 'right'].entries()) {
|
||||
const figure = figures.nth(index);
|
||||
await expectAlignment(figure, displayAlign);
|
||||
await expectGrid(figure, 64, 12);
|
||||
await figure.locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expect(figure.locator('.ap-term-text')).toContainText('Hello from wp-asciiplayer');
|
||||
await expect(figure.locator('figcaption')).toHaveText('Safe captionwith a second line & literal text');
|
||||
await expect(figure.locator('figcaption br')).toHaveCount(1);
|
||||
const typography = await figure.locator('.ap-term-text').evaluate((element) => {
|
||||
const style = getComputedStyle(element);
|
||||
const parent = getComputedStyle(element.parentElement);
|
||||
return {
|
||||
padding: style.padding,
|
||||
margin: style.margin,
|
||||
whiteSpace: style.whiteSpace,
|
||||
borderWidth: style.borderWidth,
|
||||
boxShadow: style.boxShadow,
|
||||
familyMatches: style.fontFamily === parent.fontFamily,
|
||||
fontSizeMatches: style.fontSize === parent.fontSize,
|
||||
textAlign: style.textAlign,
|
||||
};
|
||||
});
|
||||
expect(typography).toEqual({ padding: '0px', margin: '0px', whiteSpace: 'pre', borderWidth: '0px', boxShadow: 'none', familyMatches: true, fontSizeMatches: true, textAlign: 'left' });
|
||||
desktopFontSizes.push(await figure.locator('.ap-term').evaluate((element) => parseFloat(getComputedStyle(element).fontSize)));
|
||||
const rowTypography = await figure.locator('.ap-term-text .ap-line').first().evaluate((element) => {
|
||||
const style = getComputedStyle(element);
|
||||
const terminal = getComputedStyle(element.closest('.ap-term'));
|
||||
return { fontSizeMatches: style.fontSize === terminal.fontSize, familyMatches: style.fontFamily === terminal.fontFamily };
|
||||
});
|
||||
expect(rowTypography).toEqual({ fontSizeMatches: true, familyMatches: true });
|
||||
const spanTypography = await figure.locator('.ap-term-text .ap-line span').first().evaluate((element) => {
|
||||
const style = getComputedStyle(element);
|
||||
const terminal = getComputedStyle(element.closest('.ap-term'));
|
||||
return { fontSizeMatches: style.fontSize === terminal.fontSize, familyMatches: style.fontFamily === terminal.fontFamily, letterSpacing: style.letterSpacing };
|
||||
});
|
||||
expect(spanTypography).toEqual({ fontSizeMatches: true, familyMatches: true, letterSpacing: 'normal' });
|
||||
const controls = await figure.locator('.ap-control-bar button.ap-button').first().evaluate((element) => {
|
||||
const style = getComputedStyle(element);
|
||||
return { borderWidth: style.borderWidth, boxShadow: style.boxShadow };
|
||||
});
|
||||
expect(controls).toEqual({ borderWidth: '0px', boxShadow: 'none' });
|
||||
}
|
||||
const unsafeCaption = figures.nth(3).locator('figcaption');
|
||||
await expect(unsafeCaption).toContainText('Still safe');
|
||||
await expect(unsafeCaption.locator('script, img, iframe, a, strong, [onerror], [onclick]')).toHaveCount(0);
|
||||
expect(await page.evaluate(() => window.__captionXss)).toBeUndefined();
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
for (const [index, displayAlign] of ['left', 'center', 'right'].entries()) {
|
||||
await expectAlignment(figures.nth(index), displayAlign);
|
||||
await expectGrid(figures.nth(index), 64, 12);
|
||||
await expect.poll(() => figures.nth(index).locator('.ap-term').evaluate((element) => parseFloat(getComputedStyle(element).fontSize))).toBeLessThan(desktopFontSizes[index]);
|
||||
const scaledTypography = await figures.nth(index).locator('.ap-term').evaluate((terminal) => {
|
||||
const expected = getComputedStyle(terminal);
|
||||
return [...terminal.querySelectorAll('.ap-term-text, .ap-line, .ap-line span')].every((element) => {
|
||||
const style = getComputedStyle(element);
|
||||
return style.fontSize === expected.fontSize && style.fontFamily === expected.fontFamily;
|
||||
});
|
||||
});
|
||||
expect(scaledTypography).toBe(true);
|
||||
}
|
||||
await screenshot(page, testInfo, 'layout-theme-css-mobile');
|
||||
// Physical left/right placement must remain the same inside RTL content.
|
||||
// This covers direction inheritance at runtime; generated RTL stylesheets
|
||||
// are independently protected by the source's rtlcss ignore directive.
|
||||
await page.evaluate(() => {
|
||||
document.documentElement.dir = 'rtl';
|
||||
for (const figure of document.querySelectorAll('.asciiplayer-figure')) {
|
||||
figure.parentElement.dir = 'rtl';
|
||||
}
|
||||
});
|
||||
for (const [index, displayAlign] of ['left', 'center', 'right'].entries()) {
|
||||
await expectAlignment(figures.nth(index), displayAlign);
|
||||
await expectGrid(figures.nth(index), 64, 12);
|
||||
}
|
||||
await screenshot(page, testInfo, 'layout-theme-css-mobile-rtl');
|
||||
});
|
||||
|
||||
test('the inserter example is a local static preview and makes no recording request', async ({ page }, testInfo) => {
|
||||
await openEditor(page);
|
||||
const example = await page.evaluate((name) => window.wp.blocks.getBlockType(name).example, blockName);
|
||||
expect(example).toMatchObject({ attributes: { isExample: true } });
|
||||
const recordingRequests = [];
|
||||
page.on('request', (request) => {
|
||||
if (/\.cast(?:[?#]|$)|asciinema\.org|jsdelivr\.net/.test(request.url())) recordingRequests.push(request.url());
|
||||
});
|
||||
const { block } = await insertPlayer(page, example.attributes);
|
||||
await expect(block.locator('.asciiplayer-example')).toContainText('Hello, terminal!');
|
||||
await expect(block.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveCount(0);
|
||||
await expect(block.locator('.ap-wrapper')).toHaveCount(0);
|
||||
await screenshot(page, testInfo, 'static-inserter-example');
|
||||
expect(recordingRequests).toEqual([]);
|
||||
});
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
{"version":2,"width":64,"height":12,"timestamp":1700000000,"env":{"TERM":"xterm-256color","SHELL":"/bin/sh"},"title":"Recording-controlled terminal resize"}
|
||||
[0.0,"o","$ printf 'Original 64 x 12 grid'\r\n"]
|
||||
[0.1,"o","Original 64 x 12 grid\r\n"]
|
||||
[1.0,"r","96x18"]
|
||||
[1.1,"o","\u001b[2J\u001b[HResized recording grid: 96 x 18\r\n"]
|
||||
[30.0,"o","$ "]
|
||||
@@ -0,0 +1,24 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { normalizeDisplayAlign, normalizePlayerOptions, terminalDimension, normalizeWidth } from '../../src/options.js';
|
||||
test('display placement and scaling never create terminal grid overrides', () => {
|
||||
for (const width of ['25%', '480px', '100%']) {
|
||||
const options = normalizePlayerOptions({ width, displayAlign: 'right', caption: 'Demo' });
|
||||
assert.equal(options.cols, undefined);
|
||||
assert.equal(options.rows, undefined);
|
||||
assert.equal(options.width, undefined);
|
||||
assert.equal(options.caption, undefined);
|
||||
}
|
||||
assert.equal(normalizeDisplayAlign('right'), 'right');
|
||||
assert.equal(normalizeDisplayAlign('unsafe'), 'center');
|
||||
assert.equal(normalizeWidth('480px'), '480px');
|
||||
assert.equal(normalizeWidth('480px;display:none'), '100%');
|
||||
});
|
||||
test('terminal overrides are optional bounded integers', () => {
|
||||
for (const value of ['', '0', '-1', '2.5', '1001', 'Infinity', null]) assert.equal(terminalDimension(value), undefined);
|
||||
assert.equal(terminalDimension('120'), 120);
|
||||
assert.equal(terminalDimension(1), 1);
|
||||
const options = normalizePlayerOptions({ cols: terminalDimension('120'), rows: terminalDimension('') });
|
||||
assert.equal(options.cols, 120);
|
||||
assert.equal(options.rows, undefined);
|
||||
});
|
||||
@@ -54,6 +54,10 @@ function get_block_wrapper_attributes( $attributes ) {
|
||||
}
|
||||
return implode( ' ', $output );
|
||||
}
|
||||
function wp_kses( $value, $allowed ) {
|
||||
// Contract-only double. Actual sanitizer coverage belongs to WP browser tests.
|
||||
return strip_tags( $value, '<br>' );
|
||||
}
|
||||
function wp_json_encode( $value, $flags = 0 ) {
|
||||
return json_encode( $value, $flags );
|
||||
}
|
||||
|
||||
+22
-5
@@ -60,8 +60,8 @@ try {
|
||||
same( array( 'lamgc-asciiplayer-player-style' ), $GLOBALS['ap_test']['styles']['lamgc-asciiplayer-style']['deps'], 'Frontend style depends on player stylesheet.' );
|
||||
contains( 'window.wpAsciiplayerSettings = ', $GLOBALS['ap_test']['inline_scripts'][0]['source'], 'Editor iframe receives trusted runtime URLs.' );
|
||||
same( 'before', $GLOBALS['ap_test']['inline_scripts'][0]['position'], 'Settings are available before editor boot.' );
|
||||
contains( 'player.js?ver=1.1.0', $GLOBALS['ap_test']['inline_scripts'][0]['source'], 'Bridge JavaScript cache-buster matches registered asset version.' );
|
||||
contains( 'player.css?ver=1.1.0', $GLOBALS['ap_test']['inline_scripts'][0]['source'], 'Bridge CSS cache-buster matches registered asset version.' );
|
||||
contains( 'player.js?ver=1.2.0', $GLOBALS['ap_test']['inline_scripts'][0]['source'], 'Bridge JavaScript cache-buster matches registered asset version.' );
|
||||
contains( 'player.css?ver=1.2.0', $GLOBALS['ap_test']['inline_scripts'][0]['source'], 'Bridge CSS cache-buster matches registered asset version.' );
|
||||
|
||||
// Source validation covers script, HTML, credential and relative-URL attacks.
|
||||
foreach ( array( '', 'javascript:alert(1)', 'data:text/html,test', 'file:///tmp/a.cast', '//evil.test/a.cast', '/\\evil.test/a.cast', "https://example.test/a\n.cast", 'https://x.test/" onmouseover="alert(1)', 'https://user:[email protected]/a.cast', 'https:///a.cast', 'a.cast', array( 'bad' ) ) as $source ) {
|
||||
@@ -128,13 +128,30 @@ try {
|
||||
same( true, isset( $GLOBALS['ap_test']['enqueued_styles']['lamgc-asciiplayer-style'] ), 'Every valid render requests CSS.' );
|
||||
$html = render_block( array( 'source' => '/demo.cast', 'poster' => 'data:text/plain,"><script>alert(1)</script>', 'legacyStyle' => 'width:80%;color:red;background:url(javascript:alert(1))' ) );
|
||||
same( false, false !== strpos( $html, '<script>' ), 'Poster cannot escape JSON/HTML attribute.' );
|
||||
contains( 'style="width:80%;color:red"', $html, 'Legacy style passes through WordPress safe CSS filtering.' );
|
||||
contains( 'style="color:red"', $html, 'Legacy player styles stay on the player mount point.' );
|
||||
contains( 'style="width:80%;"', $html, 'Legacy width moves to the figure.' );
|
||||
contains( 'background:url(javascript:alert(1))', end( $GLOBALS['ap_test']['filtered_css'] ), 'The original style is supplied to the WordPress sanitizer.' );
|
||||
same( 'width:80%;height:200px;width:50%;', player_style( array( 'legacyStyle' => 'width:80%;height:200px', 'width' => '50%' ) ), 'Dedicated width control overrides legacy width.' );
|
||||
same( '', player_style( array( 'width' => '100%;background:red' ) ), 'Width cannot inject extra declarations.' );
|
||||
same( render_player( array( 'source' => '/demo.cast', 'speed' => 2 ) ), render_block( array( 'source' => '/demo.cast', 'speed' => 2 ) ), 'Block uses shared renderer.' );
|
||||
same( 'asciiplayer-container', end( $GLOBALS['ap_test']['block_wrappers'] )['class'], 'Block wrapper classes/layout pass through WordPress block supports.' );
|
||||
same( options_from( render_player( array( 'source' => '/demo.cast', 'speed' => 2 ) ) ), options_from( render_block( array( 'source' => '/demo.cast', 'speed' => 2 ) ) ), 'Block uses shared player options.' );
|
||||
same( 'asciiplayer-block', end( $GLOBALS['ap_test']['block_wrappers'] )['class'], 'Block wrapper classes/layout pass through WordPress block supports.' );
|
||||
|
||||
$html = render_block( array( 'source' => '/demo.cast', 'width' => '480px', 'displayAlign' => 'right', 'caption' => 'Caption & detail<br>second line' ) );
|
||||
contains( '<figure ', $html, 'Block has semantic figure wrapper.' );
|
||||
contains( 'asciiplayer-align-right', $html, 'Validated display alignment.' );
|
||||
contains( 'width:480px;', $html, 'Display width belongs to figure.' );
|
||||
contains( '<figcaption class="wp-element-caption">Caption & detail<br>second line</figcaption>', $html, 'Caption is outside player mount point.' );
|
||||
contains( '</div><figcaption', $html, 'Player cannot dispose caption.' );
|
||||
$html = render_block( array( 'source' => '/demo.cast', 'displayAlign' => '\" onclick=alert(1)', 'caption' => '<img src=x onerror=alert(1)>Safe' ) );
|
||||
contains( 'asciiplayer-align-center', $html, 'Invalid alignment falls back safely.' );
|
||||
same( false, false !== strpos( $html, '<img' ), 'Caption does not allow image markup.' );
|
||||
same( false, isset( player_options( array() )['cols'] ), 'Default columns come from recording.' );
|
||||
same( false, isset( player_options( array() )['rows'] ), 'Default rows come from recording.' );
|
||||
same( 120, player_options( array( 'cols' => 120 ) )['cols'], 'Explicit column override is retained.' );
|
||||
same( false, isset( player_options( array( 'cols' => 120 ) )['rows'] ), 'One-axis override leaves other axis native.' );
|
||||
|
||||
$html = render_block( array( 'source' => '/demo.cast', 'legacyStyle' => 'height:200px;width:80%', 'caption' => 'Under player' ) );
|
||||
contains( 'class="asciiplayer-container" style="height:200px"', $html, 'Legacy height remains on the player, so caption contributes to figure height.' );
|
||||
// No is_single gate: query lookahead supports Pages and archive results.
|
||||
reset_enqueues();
|
||||
$GLOBALS['wp_query'] = (object) array( 'posts' => array( (object) array( 'post_content' => 'Ordinary content' ), (object) array( 'post_content' => '[asciiplayer]/demo.cast[/asciiplayer]' ) ) );
|
||||
|
||||
Reference in New Issue
Block a user