Compare commits

..
Author SHA1 Message Date
LamGC 9f026221f2 Use native RichText labels and supported Chinese HTML language tags in locale tests
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
2026-10-14 10:39:15 +08:00
LamGC 3b2b213b6f Add bundled English and Simplified Chinese UI translations (1.1.0-dev) 2026-10-14 10:28:49 +08:00
LamGC 41395f4102 Move block explanations into collapsed sidebar help (1.2.3) 2026-10-14 09:59:55 +08:00
LamGC 85474494b1 Document bounded temporary-upload stream exceptions
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
2026-10-13 18:06:18 +08:00
LamGC 04f19543d3 Fix Media Library test storage and scope sidebar selectors 2026-10-13 17:57:41 +08:00
LamGC af866bc20e Show native cast dimensions and add Media Library recordings (1.2.2) 2026-10-13 17:50:18 +08:00
LamGC 27fe6e0d19 Improve automatic previews and toolbar terminal sizing (1.2.1) 2026-10-13 17:19:54 +08:00
LamGC 26742f3699 Respect WordPress editor gutters with border-box sizing 2026-10-13 16:48:28 +08:00
LamGC 90ef836730 Keep editor caption geometry stable during block selection 2026-10-13 16:41:36 +08:00
LamGC 2041124178 Add responsive player layout, captions and native terminal sizing 2026-10-13 16:31:55 +08:00
46 changed files with 3902 additions and 94 deletions
+11 -1
View File
@@ -67,15 +67,25 @@ jobs:
JS JS
- name: Start real WordPress and install only the packaged plugin - name: Start real WordPress and install only the packaged plugin
run: | run: |
mkdir -p .wp-env-uploads
npx --no-install wp-env start npx --no-install wp-env start
npx --no-install wp-env run cli wp plugin install /var/www/html/wp-content/asciiplayer-packages/wp-asciiplayer.zip --activate --force npx --no-install wp-env run cli wp plugin install /var/www/html/wp-content/asciiplayer-packages/wp-asciiplayer.zip --activate --force
npx --no-install wp-env run cli wp plugin is-active wp-asciiplayer npx --no-install wp-env run cli wp plugin is-active wp-asciiplayer
npx --no-install wp-env run cli wp core version | tee wordpress-version.txt npx --no-install wp-env run cli wp core version | tee wordpress-version.txt
npx --no-install wp-env run cli wp plugin list npx --no-install wp-env run cli wp plugin list
npx --no-install wp-env run cli wp language core install zh_CN
npx --no-install wp-env run cli wp site switch-language en_US
npx --no-install wp-env run cli wp user meta update admin locale en_US
- name: Install Chromium - name: Install Chromium
run: npx --no-install playwright install --with-deps chromium run: npx --no-install playwright install --with-deps chromium
- name: Exercise editor iframe, saved blocks, Pages, posts and legacy shortcodes - name: Exercise editor iframe, saved blocks, Pages, posts and legacy shortcodes
run: npm run test:e2e env:
PLAYWRIGHT_HTML_OUTPUT_DIR: playwright-report/en-US
run: npm run test:e2e -- --grep-invert @i18n --output=test-results/en-US
- name: Exercise real en_US and zh_CN site and user locale combinations
env:
PLAYWRIGHT_HTML_OUTPUT_DIR: playwright-report/i18n
run: npm run test:e2e -- --grep @i18n --output=test-results/i18n
- name: Run Plugin Check (advisory until directory review) - name: Run Plugin Check (advisory until directory review)
if: always() && matrix.wordpress == 'latest' if: always() && matrix.wordpress == 'latest'
continue-on-error: true continue-on-error: true
+1
View File
@@ -54,3 +54,4 @@ dist/
/playwright-report/ /playwright-report/
/test-results/ /test-results/
/.wp-env/ /.wp-env/
/.wp-env-uploads/
+1
View File
@@ -11,6 +11,7 @@
"SCRIPT_DEBUG": true "SCRIPT_DEBUG": true
}, },
"mappings": { "mappings": {
"wp-content/uploads": "./.wp-env-uploads",
"wp-content/uploads/asciiplayer-fixtures": "./tests/fixtures", "wp-content/uploads/asciiplayer-fixtures": "./tests/fixtures",
"wp-content/asciiplayer-packages": "./dist" "wp-content/asciiplayer-packages": "./dist"
}, },
+36 -6
View File
@@ -3,20 +3,40 @@
为 WordPress 提供原生 Asciicast Player 区块,可在编辑器内真实播放终端录屏, 为 WordPress 提供原生 Asciicast Player 区块,可在编辑器内真实播放终端录屏,
同时兼容原有 `[asciiplayer]` shortcode。 同时兼容原有 `[asciiplayer]` shortcode。
## 开发预览:1.1.0-dev
当前 PR 为尚未发布的开发预览。此前安装包的 1.1.0、1.2.0–1.2.3 仅为迭代标记,不代表正式发布。
供测试的安装包使用 `wp-asciiplayer-1.1.0-dev-<提交号>.zip` 命名;不会自动创建发布标签或部署。
## 界面语言
插件自己的界面支持英文和简体中文(`zh_CN`)。编辑器跟随「用户 → 个人资料 → 语言」
(未单独设置时跟随站点),前台跟随「设置 → 常规 → 站点语言」。翻译文件随安装包附带,可离线使用。
英文为默认回退语言。不会把 `zh_TW` 等其他中文地区设置自动映射为简体中文。
录屏中的终端内容和作者填写的说明文字不会被翻译。上游播放器自身的播放控件和帮助仍为英文,播放器文件保持原样。
## 安装与使用 ## 安装与使用
将构建得到的 `wp-asciiplayer.zip` 上传到「插件 → 安装插件 → 上传插件」并启用。 将构建得到的 `wp-asciiplayer.zip` 上传到「插件 → 安装插件 → 上传插件」并启用。
GitHub 源码 ZIP 需要先构建,不能直接当发行包安装。构建方法见 [SOURCE.md](SOURCE.md)。 GitHub 源码 ZIP 需要先构建,不能直接当发行包安装。构建方法见 [SOURCE.md](SOURCE.md)。
要求 WordPress 6.3+、PHP 7.4+;具体测试版本见仓库 CI。 要求 WordPress 6.3+、PHP 7.4+;具体测试版本见仓库 CI。
插入「Asciicast Player」区块,粘贴录制文件的 HTTP(S) URL,应用后即可在编辑器内播放、 插入「Asciicast Player」区块,粘贴录制文件的 HTTP(S) URL,停止输入约半秒后会自动加载预览;也可以点击「Apply URL」立即加载。之后即可在编辑器内播放、
暂停和拖动。主题、速度、循环、控制栏、尺寸、起始时间和空闲压缩等选项在区块设置中调整。 暂停和拖动。「Display」面板提供展示宽度预设、自定义宽度(例如 `480px`、`65%`)以及左、中、右对齐;
保存文章或页面后,前台使用同一播放器。重新打开已有区块时点击「Load preview」加载预览; 展示宽度会限制在当前页面可用空间内。点击播放器下方即可添加描述文字。
编辑预览不会自动播放,前台自动播放设置仍会保留。
在区块上方浮动工具栏点击「Terminal size」可快速调整终端行列数;侧边栏的同名折叠面板也保留,两处设置实时同步。
终端尺寸与展示大小分别控制:Columns / Rows 留空时,使用 cast 文件记录的终端尺寸,
并跟随录制中的 resize 事件。只有需要改变终端网格时才覆盖行列数,点击「Use recording size」可恢复。
展示宽度与 `fit: width` 只缩放画面,不会修改终端行列数;覆盖网格可能影响录屏排版或裁切内容。
主题、速度、循环、控制栏、起始时间和空闲压缩等选项仍在区块设置中调整。
保存文章或页面后,前台使用同一播放器。重新打开已有区块时,只要已有有效 URL 就自动加载预览;
编辑预览不会自动播放,前台自动播放设置仍会保留。区块插入器使用本地静态示例,不请求录制文件。
播放器增加了局部样式隔离,避免常见主题的代码块边框、阴影和字体设置干扰终端;键盘焦点提示仍保留。
URL 必须指向录制文件(例如 `.cast`),不能直接使用分享页面地址。跨域文件需要允许 URL 必须指向录制文件(例如 `.cast`),不能直接使用分享页面地址。跨域文件需要允许
来自你站点的 CORS 请求;HTTPS 页面上的 HTTP 文件可能被浏览器阻止。优先使用同源 HTTPS。 来自你站点的 CORS 请求;HTTPS 页面上的 HTTP 文件可能被浏览器阻止。优先使用同源 HTTPS。
本插件不提供远程文件代理、不扩展上传类型,也不创建额外的录屏管理文章类型。 本插件不提供远程文件代理、不扩大用户的上传权限,也不创建额外的录屏管理文章类型。
## 旧文章兼容 ## 旧文章兼容
@@ -36,7 +56,7 @@ URL 必须指向录制文件(例如 `.cast`),不能直接使用分享页
旧 `ap_use_local_resources` 开关不再使用。没有统计追踪或后台远程 API 请求。 旧 `ap_use_local_resources` 开关不再使用。没有统计追踪或后台远程 API 请求。
你选择的录制文件会由读者浏览器直接请求;外部文件主机可能收到 IP、浏览器请求信息和 你选择的录制文件会由读者浏览器直接请求;外部文件主机可能收到 IP、浏览器请求信息和
依浏览器/站点策略发送的来源信息。应用 URL 或点击加载预览时,编辑器也会发起这类请求。 依浏览器/站点策略发送的来源信息。编辑器存在有效 URL 时也会自动发起这类请求,包括重新打开已保存的区块。
请使用可信主机,发布前检查录屏是否包含终端里的敏感信息。外部主机适用其自身隐私政策。 请使用可信主机,发布前检查录屏是否包含终端里的敏感信息。外部主机适用其自身隐私政策。
## 开发与许可 ## 开发与许可
@@ -44,3 +64,13 @@ URL 必须指向录制文件(例如 `.cast`),不能直接使用分享页
[构建与测试说明](SOURCE.md) · [第三方许可证](THIRD-PARTY-NOTICES.md) [构建与测试说明](SOURCE.md) · [第三方许可证](THIRD-PARTY-NOTICES.md)
本插件保持 GPL-3.0-only,播放器及依赖保留各自的兼容许可证。 本插件保持 GPL-3.0-only,播放器及依赖保留各自的兼容许可证。
### 媒体库与原始终端尺寸
点击区块中的 **选择录制文件(Choose recording)** 可通过 WordPress 媒体库选择或上传 `.cast` 录制文件。上传权限沿用 WordPress 的 `upload_files` 能力,不会为低权限用户开放上传。插件仅为经过格式校验的 `.cast` 文件添加支持,不放开任意 JSON、HTML 或 SVG。
浮动工具栏和折叠侧栏中的 Columns / Rows 留空时,会在录制加载后显示原始终端尺寸作为占位提示。更换 URL 会刷新提示,但保留你明确填写的覆盖值;恢复录制尺寸会清空覆盖值,继续尊重录制中的尺寸变化。未知或加载失败时不猜测尺寸。
上传文件会完整校验:最多 32 MiB、100,000 个事件或流内行、每条 JSONL 行 256 KiB、终端任一方向不超过 1,000。旧版 v1 最多 2 MiB,需使用起始 `{` 单独一行的格式化 JSON;内置播放器不支持压成一行的 v1。v2/v3 使用标准 JSONL。站点和服务器更低的上传限制仍生效,多站点还需网络允许 `cast` 扩展名。原始尺寸提示只检查同一次预览响应的前 64 KiB,无法读取时保留通用提示。
区块内常驻的录制/隐私说明和播放操作说明位于侧栏默认折叠的 **帮助(Help)** 面板,保留标题、错误提示和必要控件标签。
+61 -8
View File
@@ -3,6 +3,23 @@
An Asciicast Player block for WordPress, with real playback in the editor and An Asciicast Player block for WordPress, with real playback in the editor and
backwards-compatible `[asciiplayer]` shortcodes. [中文说明](README-zh.md) backwards-compatible `[asciiplayer]` shortcodes. [中文说明](README-zh.md)
## Development preview: 1.1.0-dev
This PR is an unreleased development preview. Earlier draft ZIP labels 1.1.0 and
1.2.0–1.2.3 were iteration labels, not published releases. Review packages use
`wp-asciiplayer-1.1.0-dev-<commit>.zip`; no release tag or deployment is implied.
## Languages
Plugin-owned UI includes English and Simplified Chinese (`zh_CN`). The editor
follows **Users → Profile → Language** (or the site default); public pages follow
**Settings → General → Site Language**. Catalogs ship inside the ZIP and need no
translation server at runtime. English is the source/fallback language, so a
separate `en_US` catalog is unnecessary. `zh_TW` and other locales are not silently
mapped to Simplified Chinese. Recorded terminal output and author captions stay
unchanged. The bundled upstream player's own playback controls and help remain
English; its vendor files are not modified.
## Install ## Install
Install the built `wp-asciiplayer.zip` through **Plugins → Add New → Upload Install the built `wp-asciiplayer.zip` through **Plugins → Add New → Upload
@@ -15,20 +32,41 @@ site and theme; CI tests the versions listed in `.github/workflows/ci.yml`.
## Block editor ## Block editor
1. Insert **Asciicast Player**. 1. Insert **Asciicast Player**.
2. Paste an HTTP(S) recording-file URL (for example a `.cast` file), then apply it. 2. Paste an HTTP(S) recording-file URL (for example a `.cast` file), or use **Choose recording** to select/upload a `.cast` file in the WordPress Media Library. The preview loads after a short pause; **Apply URL** loads it immediately.
3. Play, pause and seek in the editor. Change theme, speed, looping, controls, 3. Play, pause and seek in the editor. **Display** offers width presets or a custom
width/fit, start time and idle-time limit from the block settings. CSS length (for example `480px` or `65%`), plus left/center/right alignment.
4. Save the post or page; the same locally bundled player is used on the front end. The width stays within the available space. Add a caption below the player.
4. Use **Terminal size** in the floating block toolbar for quick Columns/Rows
edits, or expand the **Terminal size** sidebar panel. Both edit the same values.
Empty fields show the recording’s original columns/rows as placeholders after
loading. Changing the URL refreshes these hints without clearing your explicit
overrides; reset clears overrides, so recorded resize events remain active.
Terminal size is separate from display width: 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. Existing saved blocks load their valid recording URL automatically on reopening
This keeps external recordings from loading until you choose to preview them. the editor. Typed URL changes are debounced for 500ms; empty or invalid URLs do
not start a recording request.
Preview does not autoplay even when front-end autoplay is enabled. Preview does not autoplay even when front-end autoplay is enabled.
Recording/privacy and playback explanations are available in the collapsed
**Help** sidebar panel, keeping the block canvas focused on editing.
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. 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. A recording on another origin must allow CORS requests from your WordPress site.
HTTP recordings on an HTTPS site may be blocked as mixed content. Use a same-site HTTP recordings on an HTTPS site may be blocked as mixed content. Use a same-site
HTTPS URL when possible. The plugin does not proxy or copy remote files, grant HTTPS URL when possible. The plugin does not proxy or copy remote files, grant
new upload types, or add a recording-management post type. new upload capabilities, or add a recording-management post type.
## Existing shortcodes ## Existing shortcodes
@@ -55,7 +93,7 @@ No analytics or background remote API calls are added.
A recording URL you choose is fetched directly by the visitor's browser. Its host A recording URL you choose is fetched directly by the visitor's browser. Its host
can receive the visitor's IP address, browser request metadata and possibly a can receive the visitor's IP address, browser request metadata and possibly a
referrer, according to browser/site policy. Editor previews have the same effect referrer, according to browser/site policy. Editor previews have the same effect
when you apply a URL or click **Load preview**. Choose a trusted host and review automatically when a valid URL is present, including when reopening saved blocks. Choose a trusted host and review
recordings for sensitive terminal output before publishing them. The host's own recordings for sensitive terminal output before publishing them. The host's own
privacy policy applies; the plugin cannot make an external recording private. privacy policy applies; the plugin cannot make an external recording private.
@@ -64,3 +102,18 @@ privacy policy applies; the plugin cannot make an external recording private.
See [SOURCE.md](SOURCE.md) for locked build and ZIP packaging commands. Source See [SOURCE.md](SOURCE.md) for locked build and ZIP packaging commands. Source
code is GPL-3.0-only. The player and its dependencies retain their own compatible code is GPL-3.0-only. The player and its dependencies retain their own compatible
licenses; see [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md). licenses; see [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md).
### Media Library upload limits
The plugin adds only `.cast` uploads for users who already have WordPress
`upload_files` permission. On multisite, the network must also allow the `cast`
extension. Existing site/server upload limits still apply. Each upload is fully
validated: at most 32 MiB, 100,000 events/stream lines, 256 KiB per JSONL line, and dimensions
up to 1,000 columns/rows. Legacy v1 is limited to 2 MiB and must be pretty-printed
with its opening JSON object on a separate line because the bundled player cannot
read compact single-line v1. v2/v3 use their standard JSONL format. Invalid files
are rejected; generic JSON, HTML and SVG uploads are not enabled.
Original-size hints inspect at most the first 64 KiB of the same preview response.
If metadata is unavailable, the fields keep a generic placeholder rather than
guessing dimensions. Recorded resize events do not replace the initial-size hint.
+25
View File
@@ -33,3 +33,28 @@ Chromium; the repository CI records the exact WordPress version under test and
installs the release ZIP into the test site before checking it. Refer to the installs the release ZIP into the test site before checking it. Refer to the
workflow for setup details. Running a unit test is not a substitute for the workflow for setup details. Running a unit test is not a substitute for the
WordPress browser integration suite. WordPress browser integration suite.
## Translation maintenance
The English gettext strings are the fallback. Edit `languages/wp-asciiplayer-zh_CN.po`
to maintain Simplified Chinese; `npm run i18n` extracts the current static PHP/JS
and block-metadata strings into the POT and compiles the MO and WordPress Jed JSON.
`npm run i18n:check` fails for missing/fuzzy translations, stale generated files,
unsupported plural extraction, and mismatched printf placeholders. Build runs
compilation and tests check it reproducibly, without a network service or timestamps.
For new strings, run `node scripts/i18n.mjs --pot-only`, merge into the maintained
PO with a gettext editor, translate, and run `npm run i18n` again.
JSON files use WordPress's supported domain-locale-script-handle names for the
actual `lamgc-asciiplayer-editor` and `lamgc-asciiplayer-view` handles. The editor
bundle has no lazy translated chunks. `wp_set_script_translations` registers both
paths after scripts; PHP registers `load_plugin_textdomain` during `init`, before
block metadata is translated. The generated assets and all catalogs are packaged.
The upstream vendor bundle is byte-for-byte unchanged and its own controls remain
English. Runtime JS/CSS versions use build content hashes even though the preview
package version stays `1.1.0-dev`.
References:
- https://developer.wordpress.org/reference/functions/wp_set_script_translations/
- https://developer.wordpress.org/reference/functions/load_script_textdomain/
- https://developer.wordpress.org/reference/functions/load_plugin_textdomain/
+9 -2
View File
@@ -3,13 +3,14 @@
* Plugin Name: Asciicast Player * Plugin Name: Asciicast Player
* Plugin URI: https://github.com/LamGC/wp-asciiplayer * Plugin URI: https://github.com/LamGC/wp-asciiplayer
* Description: Add interactive terminal recordings to posts and pages with a block or shortcode. * Description: Add interactive terminal recordings to posts and pages with a block or shortcode.
* Version: 1.1.0 * Version: 1.1.0-dev
* Requires at least: 6.3 * Requires at least: 6.3
* Requires PHP: 7.4 * Requires PHP: 7.4
* Author: LamGC * Author: LamGC
* Author URI: https://blog.lamgc.moe * Author URI: https://blog.lamgc.moe
* License: GPL-3.0-only * License: GPL-3.0-only
* License URI: https://www.gnu.org/licenses/gpl-3.0.html * License URI: https://www.gnu.org/licenses/gpl-3.0.html
* Domain Path: /languages
* Text Domain: wp-asciiplayer * Text Domain: wp-asciiplayer
* *
* @package LamGC\Asciiplayer * @package LamGC\Asciiplayer
@@ -21,14 +22,20 @@ if ( ! defined( 'ABSPATH' ) ) {
exit; exit;
} }
const VERSION = '1.1.0'; const VERSION = '1.1.0-dev';
const PLUGIN_FILE = __FILE__; const PLUGIN_FILE = __FILE__;
const SHORTCODE = 'asciiplayer'; const SHORTCODE = 'asciiplayer';
require_once __DIR__ . '/includes/options.php'; require_once __DIR__ . '/includes/options.php';
require_once __DIR__ . '/includes/render.php'; require_once __DIR__ . '/includes/render.php';
require_once __DIR__ . '/includes/assets.php'; require_once __DIR__ . '/includes/assets.php';
require_once __DIR__ . '/includes/uploads.php';
add_action( 'init', __NAMESPACE__ . '\\register_plugin' ); add_action( 'init', __NAMESPACE__ . '\\register_plugin' );
add_action( 'wp_enqueue_scripts', __NAMESPACE__ . '\\enqueue_content_assets' ); add_action( 'wp_enqueue_scripts', __NAMESPACE__ . '\\enqueue_content_assets' );
add_action( 'wp_footer', __NAMESPACE__ . '\\print_late_styles', 5 ); add_action( 'wp_footer', __NAMESPACE__ . '\\print_late_styles', 5 );
add_filter( 'upload_mimes', __NAMESPACE__ . '\\allow_cast_upload_mime', 10, 2 );
add_filter( 'wp_check_filetype_and_ext', __NAMESPACE__ . '\\check_cast_filetype', 10, 5 );
add_filter( 'wp_handle_upload_prefilter', __NAMESPACE__ . '\\validate_cast_upload' );
add_filter( 'wp_handle_sideload_prefilter', __NAMESPACE__ . '\\validate_cast_upload' );
+5 -1
View File
@@ -2,7 +2,7 @@
"$schema": "https://schemas.wp.org/trunk/block.json", "$schema": "https://schemas.wp.org/trunk/block.json",
"apiVersion": 3, "apiVersion": 3,
"name": "lamgc/asciiplayer", "name": "lamgc/asciiplayer",
"version": "1.1.0", "version": "1.1.0-dev",
"title": "Asciicast Player", "title": "Asciicast Player",
"category": "media", "category": "media",
"icon": "editor-code", "icon": "editor-code",
@@ -21,6 +21,9 @@
"autoPlay": { "type": "boolean", "default": false }, "autoPlay": { "type": "boolean", "default": false },
"preload": { "type": "boolean", "default": true }, "preload": { "type": "boolean", "default": true },
"width": { "type": "string", "default": "100%" }, "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": "" }, "legacyStyle": { "type": "string", "default": "" },
"cols": { "type": "number" }, "cols": { "type": "number" },
"rows": { "type": "number" }, "rows": { "type": "number" },
@@ -29,6 +32,7 @@
"terminalLineHeight": { "type": "number" }, "terminalLineHeight": { "type": "number" },
"poster": { "type": "string" } "poster": { "type": "string" }
}, },
"example": { "attributes": { "isExample": true } },
"supports": { "html": false, "align": ["wide", "full"] }, "supports": { "html": false, "align": ["wide", "full"] },
"editorScript": "lamgc-asciiplayer-editor", "editorScript": "lamgc-asciiplayer-editor",
"viewScript": "lamgc-asciiplayer-view", "viewScript": "lamgc-asciiplayer-view",
+9 -6
View File
@@ -17,6 +17,7 @@ if ( ! defined( 'ABSPATH' ) ) {
* @return void * @return void
*/ */
function register_plugin() { function register_plugin() {
load_plugin_textdomain( 'wp-asciiplayer', false, dirname( plugin_basename( PLUGIN_FILE ) ) . '/languages' );
$base = plugin_dir_url( PLUGIN_FILE ) . 'build/'; $base = plugin_dir_url( PLUGIN_FILE ) . 'build/';
$asset = array( $asset = array(
'dependencies' => array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n' ), 'dependencies' => array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n' ),
@@ -31,7 +32,9 @@ function register_plugin() {
$view_asset = require dirname( PLUGIN_FILE ) . '/build/view.asset.php'; $view_asset = require dirname( PLUGIN_FILE ) . '/build/view.asset.php';
} }
wp_register_script( 'lamgc-asciiplayer-player', $base . 'player.js', array(), VERSION, true ); $versions = file_exists( dirname( PLUGIN_FILE ) . '/build/runtime.asset.php' ) ? require dirname( PLUGIN_FILE ) . '/build/runtime.asset.php' : array();
$player_version = $versions['player.js'] ?? VERSION;
wp_register_script( 'lamgc-asciiplayer-player', $base . 'player.js', array(), $player_version, true );
wp_register_script( wp_register_script(
'lamgc-asciiplayer-view', 'lamgc-asciiplayer-view',
$base . 'view.js', $base . 'view.js',
@@ -46,16 +49,16 @@ function register_plugin() {
$asset['version'], $asset['version'],
true true
); );
wp_register_style( 'lamgc-asciiplayer-player-style', $base . 'player.css', array(), VERSION ); wp_register_style( 'lamgc-asciiplayer-player-style', $base . 'player.css', array(), $versions['player.css'] ?? VERSION );
wp_register_style( 'lamgc-asciiplayer-style', $base . 'style-index.css', array( 'lamgc-asciiplayer-player-style' ), VERSION ); wp_register_style( 'lamgc-asciiplayer-style', $base . 'style-index.css', array( 'lamgc-asciiplayer-player-style' ), $versions['style-index.css'] ?? VERSION );
wp_register_style( 'lamgc-asciiplayer-editor-style', $base . 'index.css', array( 'lamgc-asciiplayer-player-style' ), VERSION ); wp_register_style( 'lamgc-asciiplayer-editor-style', $base . 'index.css', array( 'lamgc-asciiplayer-player-style' ), $versions['index.css'] ?? VERSION );
wp_add_inline_script( wp_add_inline_script(
'lamgc-asciiplayer-editor', 'lamgc-asciiplayer-editor',
'window.wpAsciiplayerSettings = ' . wp_json_encode( 'window.wpAsciiplayerSettings = ' . wp_json_encode(
array( array(
'playerScriptUrl' => add_query_arg( 'ver', VERSION, $base . 'player.js' ), 'playerScriptUrl' => add_query_arg( 'ver', $player_version, $base . 'player.js' ),
'playerStyleUrl' => add_query_arg( 'ver', VERSION, $base . 'player.css' ), 'playerStyleUrl' => add_query_arg( 'ver', $versions['player.css'] ?? VERSION, $base . 'player.css' ),
), ),
JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
) . ';', ) . ';',
+2
View File
@@ -45,6 +45,8 @@ function normalize_attributes( $attributes ) {
'terminallineheight' => 'terminalLineHeight', 'terminallineheight' => 'terminalLineHeight',
'poster' => 'poster', 'poster' => 'poster',
'width' => 'width', 'width' => 'width',
'displayalign' => 'displayAlign',
'caption' => 'caption',
'style' => 'legacyStyle', 'style' => 'legacyStyle',
'legacystyle' => 'legacyStyle', 'legacystyle' => 'legacyStyle',
); );
+24 -6
View File
@@ -33,15 +33,33 @@ function render_player( $attributes = array(), $content = null, $block = false )
enqueue_player_assets(); enqueue_player_assets();
$style = player_style( $attributes ); $style = player_style( $attributes );
$wrapper = $block // The mount point owns only the player. Captions must stay outside it so
? get_block_wrapper_attributes( array( 'class' => 'asciiplayer-container', 'style' => $style ) ) // upstream disposal/reinitialization cannot remove author-written content.
: 'class="asciiplayer-container"' . ( '' === $style ? '' : ' style="' . esc_attr( $style ) . '"' ); $mount_style = $style;
return sprintf( $figure_style = '';
'<div %1$s data-ap-src="%2$s" data-ap-options="%3$s"></div>', if ( $block ) {
$wrapper, // 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_url( $source, array( 'http', 'https' ) ),
esc_attr( $options ) 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>';
} }
/** /**
+222
View File
@@ -0,0 +1,222 @@
<?php
/**
* Extension-scoped, content-validated Media Library support for asciicast files.
*
* @package LamGC\Asciiplayer
*/
namespace LamGC\Asciiplayer;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
const CAST_MIME = 'application/x-asciicast';
const CAST_MAX_BYTES = 33554432; // 32 MiB; WordPress/server upload limits still apply.
const CAST_MAX_LINE_BYTES = 262144; // Bound individual JSON decodes to 256 KiB.
const CAST_MAX_V1_BYTES = 2097152; // Legacy v1 is a single JSON document, not a stream.
const CAST_MAX_EVENTS = 100000;
const CAST_MAX_DIMENSION = 1000;
/** Whether this user and, on multisite, the network permit .cast uploads. */
function can_upload_cast( $user = null ) {
$allowed = null === $user ? current_user_can( 'upload_files' ) : user_can( $user, 'upload_files' );
if ( ! $allowed ) {
return false;
}
if ( is_multisite() ) {
$extensions = preg_split( '/\s+/', strtolower( (string) get_site_option( 'upload_filetypes', '' ) ) );
return in_array( 'cast', $extensions, true );
}
return true;
}
/** Add only the .cast extension; never enable generic JSON, text, HTML or SVG. */
function allow_cast_upload_mime( $mimes, $user = null ) {
if ( can_upload_cast( $user ) ) {
$mimes['cast'] = CAST_MIME;
}
return $mimes;
}
/** A filename must actually end in .cast, including before WordPress sanitizes it. */
function is_cast_filename( $filename ) {
return is_string( $filename ) && 1 === preg_match( '/\.cast\z/i', $filename );
}
/** Finite, nonnegative seconds that remain finite in the player's milliseconds. */
function is_cast_time( $value ) {
return ( is_int( $value ) || is_float( $value ) ) && $value >= 0 && is_finite( $value * 1000 );
}
/** Bound both initial and resize dimensions before they reach the terminal. */
function is_cast_dimension( $value ) {
return is_int( $value ) && $value > 0 && $value <= CAST_MAX_DIMENSION;
}
/** Validate metadata used by asciinema-player; unknown fields remain compatible. */
function is_cast_header( $header ) {
if ( ! is_object( $header ) || ! isset( $header->version ) || ! in_array( $header->version, array( 1, 2, 3 ), true ) ) {
return false;
}
$terminal = 3 === $header->version ? ( $header->term ?? null ) : $header;
if ( ! is_object( $terminal ) ) {
return false;
}
$cols = 3 === $header->version ? ( $terminal->cols ?? null ) : ( $terminal->width ?? null );
$rows = 3 === $header->version ? ( $terminal->rows ?? null ) : ( $terminal->height ?? null );
if ( ! is_cast_dimension( $cols ) || ! is_cast_dimension( $rows ) ) {
return false;
}
foreach ( array( 'duration', 'idle_time_limit' ) as $key ) {
if ( property_exists( $header, $key ) && ! is_cast_time( $header->$key ) ) {
return false;
}
}
return true;
}
/** Validate a whole bounded legacy v1 document, including every stdout frame. */
function is_cast_v1( $text ) {
$recording = json_decode( $text, false, 16 );
if ( JSON_ERROR_NONE !== json_last_error() || ! is_cast_header( $recording ) || 1 !== $recording->version || ! isset( $recording->stdout ) || ! is_array( $recording->stdout ) || count( $recording->stdout ) > CAST_MAX_EVENTS ) {
return false;
}
$time = 0;
foreach ( $recording->stdout as $frame ) {
if ( ! is_array( $frame ) || 2 !== count( $frame ) || ! is_cast_time( $frame[0] ) || ! is_string( $frame[1] ) ) {
return false;
}
$time += $frame[0];
if ( ! is_cast_time( $time ) ) {
return false;
}
}
return true;
}
/** Validate one JSONL event, with absolute v2 time or relative v3 intervals. */
function is_cast_event( $event, $version, &$time ) {
if ( ! is_array( $event ) || 3 !== count( $event ) || ! is_cast_time( $event[0] ) || ! is_string( $event[1] ) || '' === $event[1] || ! is_string( $event[2] ) ) {
return false;
}
if ( 2 === $version && $event[0] < $time ) {
return false;
}
$time = 2 === $version ? $event[0] : $time + $event[0];
if ( ! is_cast_time( $time ) ) {
return false;
}
if ( 'r' === $event[1] ) {
if ( 1 !== preg_match( '/^([1-9][0-9]{0,3})x([1-9][0-9]{0,3})$/D', $event[2], $matches ) || ! is_cast_dimension( (int) $matches[1] ) || ! is_cast_dimension( (int) $matches[2] ) ) {
return false;
}
}
// Unknown event codes are intentionally accepted, as required by the format.
return true;
}
/**
* Inspect the entire file, not just a plausible header or a MIME guess.
*
* v2/v3 are read line by line. v1 needs a bounded complete JSON decode. Limits
* bound bytes, per-line memory, nesting and event count, including malformed input.
* Formats: https://docs.asciinema.org/manual/asciicast/ (v1, v2 and v3).
*
* @param string $path Local temporary upload path; stream wrappers are forbidden.
* @return bool
*/
function is_valid_cast_file( $path ) {
if ( ! is_string( $path ) || '' === $path || false !== strpos( $path, '://' ) || ! is_file( $path ) || ! is_readable( $path ) ) {
return false;
}
// Read-only local upload validation needs bounded streaming; WP_Filesystem reads whole files.
$handle = fopen( $path, 'rb' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- Local temporary upload only; wrappers rejected above.
if ( false === $handle ) {
return false;
}
try {
$stat = fstat( $handle );
if ( false === $stat || $stat['size'] < 1 || $stat['size'] > CAST_MAX_BYTES ) {
return false;
}
$line = fgets( $handle, CAST_MAX_LINE_BYTES + 2 );
if ( false === $line || strlen( $line ) > CAST_MAX_LINE_BYTES ) {
return false;
}
$header = json_decode( $line, false, 16 );
// Player 3.17 interprets a complete first-line object as JSONL and rejects
// version 1 there. Keep uploads playable: legacy v1 must be pretty-printed.
if ( is_object( $header ) && isset( $header->version ) && 1 === $header->version ) {
return false;
}
if ( ! is_cast_header( $header ) ) {
if ( $stat['size'] > CAST_MAX_V1_BYTES || 0 !== fseek( $handle, 0 ) ) {
return false;
}
$text = stream_get_contents( $handle, CAST_MAX_V1_BYTES + 1 );
return false !== $text && strlen( $text ) <= CAST_MAX_V1_BYTES && feof( $handle ) && is_cast_v1( $text );
}
$bytes = strlen( $line );
$count = 0;
$time = 0;
while ( false !== ( $line = fgets( $handle, CAST_MAX_LINE_BYTES + 2 ) ) ) {
$bytes += strlen( $line );
if ( $bytes > CAST_MAX_BYTES || strlen( $line ) > CAST_MAX_LINE_BYTES || ++$count > CAST_MAX_EVENTS ) {
return false;
}
if ( 3 === $header->version && '#' === $line[0] ) {
continue;
}
// The bundled player's JSONL parser only consumes lines starting with
// '['; reject indented events rather than silently losing their output.
if ( '[' !== $line[0] ) {
return false;
}
// Empty extra lines and non-event trailing content are not valid JSONL.
$event = json_decode( $line, false, 16 );
if ( JSON_ERROR_NONE !== json_last_error() || ! is_cast_event( $event, $header->version, $time ) ) {
return false;
}
}
return feof( $handle );
} finally {
fclose( $handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- Always close the bounded read-only upload stream.
}
}
/** Reject invalid .cast uploads even for users with unfiltered_upload permission. */
function validate_cast_upload( $file ) {
if ( ! isset( $file['name'] ) || ! is_cast_filename( $file['name'] ) || ! empty( $file['error'] ) ) {
return $file;
}
$allowed = get_allowed_mime_types();
if ( ! can_upload_cast() || ! isset( $allowed['cast'] ) || CAST_MIME !== $allowed['cast'] ) {
$file['error'] = __( 'You are not allowed to upload Asciicast files.', 'wp-asciiplayer' );
} elseif ( ! is_valid_cast_file( $file['tmp_name'] ?? null ) ) {
$file['error'] = __( 'Upload a valid Asciicast v2/v3 JSONL or pretty-printed v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, and 1,000 columns or rows).', 'wp-asciiplayer' );
}
return $file;
}
/** Override generic fileinfo MIME guesses only for an allowed, validated .cast. */
function check_cast_filetype( $data, $file, $filename, $mimes = null, $real_mime = false ) {
if ( ! is_cast_filename( $filename ) ) {
return $data;
}
$global_allowed = get_allowed_mime_types();
$allowed = null === $mimes ? $global_allowed : $mimes;
// wp_check_filetype() treats an empty map as its default map. Do not let an
// explicitly empty allow-list silently re-enable this extension.
$checked = is_array( $allowed ) && ! empty( $allowed ) ? wp_check_filetype( $filename, $allowed ) : array( 'ext' => false, 'type' => false );
if ( can_upload_cast() && isset( $global_allowed['cast'] ) && CAST_MIME === $global_allowed['cast'] && 'cast' === strtolower( (string) $checked['ext'] ) && CAST_MIME === $checked['type'] && is_valid_cast_file( $file ) ) {
$data['ext'] = 'cast';
$data['type'] = CAST_MIME;
$data['proper_filename'] = false;
} else {
$data['ext'] = false;
$data['type'] = false;
$data['proper_filename'] = false;
}
return $data;
}
@@ -0,0 +1,237 @@
{
"domain": "wp-asciiplayer",
"locale_data": {
"messages": {
"": {
"domain": "wp-asciiplayer",
"lang": "zh_CN",
"plural-forms": "nplurals=1; plural=0;"
},
"Columns": [
"列数"
],
"From recording": [
"使用录制尺寸"
],
"Rows": [
"行数"
],
"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.": [
"加载后,占位提示会显示录制文件的原始行列数。留空可使用录制尺寸,并跟随录制中的尺寸变化。手动设置会改变字符网格,而非显示宽度,可能影响排版或裁切内容。"
],
"Use recording size": [
"使用录制尺寸"
],
"Asciinema": [
"Asciinema"
],
"Recording theme (automatic)": [
"录制文件主题(自动)"
],
"Custom": [
"自定义"
],
"Width": [
"按宽度缩放"
],
"Original size": [
"原始大小"
],
"Height (legacy)": [
"按高度缩放(旧版)"
],
"Width and height (legacy)": [
"按宽高缩放(旧版)"
],
"Example terminal recording": [
"终端录屏示例"
],
"A terminal recording, right in your post.": [
"在文章中直接播放终端录屏。"
],
"Terminal size": [
"终端尺寸"
],
"Terminal size (columns × rows)": [
"终端尺寸(列数 × 行数)"
],
"Close": [
"关闭"
],
"Display": [
"显示"
],
"Player width": [
"播放器宽度"
],
"Custom width": [
"自定义宽度"
],
"Use a CSS length, such as 480px or 65%. The player stays within its available space.": [
"使用 CSS 长度,例如 480px 或 65%。播放器不会超出可用空间。"
],
"Enter a positive width with a unit, such as 480px or 65%. The last valid width is kept.": [
"请输入带单位的正数宽度,例如 480px 或 65%。将保留上一次有效的宽度。"
],
"Display alignment": [
"对齐方式"
],
"Left": [
"左对齐"
],
"Center": [
"居中"
],
"Right": [
"右对齐"
],
"Display width scales the recording without changing its terminal columns or rows. Add a caption directly below the player.": [
"显示宽度只缩放画面,不改变终端行列数。可在播放器下方直接添加说明文字。"
],
"Playback": [
"播放"
],
"Playback speed": [
"播放速度"
],
"Loop playback": [
"循环播放"
],
"Autoplay on published page": [
"在发布后的页面自动播放"
],
"The editor preview always waits for you to press play.": [
"编辑器预览始终需要点击播放后才会开始。"
],
"Preload on published page": [
"在发布后的页面预加载"
],
"Loads the recording before the visitor presses play. The editor preview always preloads a valid recording URL.": [
"在访客点击播放前加载录制文件。编辑器预览始终会预加载有效的录制文件 URL。"
],
"Start at (seconds)": [
"起始时间(秒)"
],
"Idle time limit (seconds)": [
"最长空闲时间(秒)"
],
"Shorten long pauses. Use 0 to keep the recording’s default.": [
"缩短过长的停顿。设为 0 可保留录制文件的默认设置。"
],
"Appearance": [
"外观"
],
"Theme": [
"主题"
],
"Player controls": [
"播放控制栏"
],
"Show on interaction": [
"交互时显示"
],
"Always show": [
"始终显示"
],
"Hide": [
"隐藏"
],
"Fit": [
"缩放方式"
],
"Height-based fitting requires a fixed container height in your site CSS.": [
"按高度缩放需要在站点 CSS 中设置固定的容器高度。"
],
"The custom container style from your shortcode is preserved on the published page.": [
"发布后的页面会保留简码中的自定义容器样式。"
],
"Help": [
"帮助"
],
"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.": [
"有效的录制文件 URL 会自动加载预览,重新打开编辑器时也一样。文件所在服务器会收到浏览器请求,发布后的播放器也会访问该服务器。请使用 .cast 文件直链;外部服务器需允许跨域请求(CORS)。"
],
"Use the player controls to play, pause, and seek. Autoplay is disabled only in the editor.": [
"使用播放器控件播放、暂停和跳转。仅编辑器预览禁用自动播放。"
],
"Recording URL": [
"录制文件 URL"
],
"Apply URL": [
"应用 URL"
],
"Choose an Asciicast recording": [
"选择 Asciicast 录制文件"
],
"Choose recording": [
"选择录制文件"
],
"Choose an Asciicast (.cast) file from the Media Library.": [
"请从媒体库选择 Asciicast(.cast)文件。"
],
"Enter an HTTP(S) recording URL or a path starting with a single /.": [
"请输入 HTTP(S) 录制文件 URL,或以单个 / 开头的路径。"
],
"Asciicast Player": [
"Asciicast 播放器"
],
"Enter a recording URL to load its preview automatically. Playback starts only when you press play.": [
"输入录制文件 URL 后会自动加载预览,点击播放才会开始播放。"
],
"Add a caption…": [
"添加说明文字…"
],
"Recording caption": [
"录屏说明文字"
],
"Height-based previews use the shortcode’s fixed height when available, or a 320px editor frame. Published height still comes from your container style.": [
"按高度缩放的预览会使用简码中的固定高度;未设置时使用 320px 的编辑器预览高度。发布后的高度仍由容器样式决定。"
],
"block title\u0004Asciicast Player": [
"Asciicast 播放器"
],
"block description\u0004Embed and preview a terminal recording with the locally bundled asciinema player.": [
"使用本地附带的 asciinema 播放器嵌入和预览终端录屏。"
],
"block keyword\u0004asciinema": [
"asciinema"
],
"block keyword\u0004terminal": [
"终端"
],
"block keyword\u0004recording": [
"录屏"
],
"Unable to load the recording. Check the URL, file format, and the source server’s CORS permissions.": [
"无法加载录制文件。请检查 URL、文件格式及来源服务器的跨域请求(CORS)权限。"
],
"The recording is taking too long to load. Check your connection and try again.": [
"录制文件加载超时。请检查网络连接后重试。"
],
"The local player could not start. Try again, or check that the plugin’s built assets are installed.": [
"本地播放器无法启动。请重试,或检查插件的构建资源是否已安装。"
],
"Loading recording…": [
"正在加载录制文件…"
],
"Retry preview": [
"重试预览"
],
"Interactive terminal recording preview": [
"可交互的终端录屏预览"
],
"Unable to load this terminal recording. The file may be unavailable, invalid, or blocked by the source server’s CORS policy.": [
"无法加载此终端录屏。文件可能无法访问、格式无效,或被来源服务器的跨域请求(CORS)策略阻止。"
],
"You are not allowed to upload Asciicast files.": [
"你没有上传 Asciicast 文件的权限。"
],
"Upload a valid Asciicast v2/v3 JSONL or pretty-printed v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, and 1,000 columns or rows).": [
"请上传有效的 Asciicast v2/v3 JSONL 或格式化的 v1 .cast 录制文件(最大 32 MiB;v1 最大 2 MiB;最多 100,000 个事件;每行 JSONL最大 256 KiB;列数和行数均不超过 1,000)。"
],
"Add interactive terminal recordings to posts and pages with a block or shortcode.": [
"通过区块或简码在文章和页面中添加可交互的终端录屏。"
]
}
}
}
@@ -0,0 +1,237 @@
{
"domain": "wp-asciiplayer",
"locale_data": {
"messages": {
"": {
"domain": "wp-asciiplayer",
"lang": "zh_CN",
"plural-forms": "nplurals=1; plural=0;"
},
"Columns": [
"列数"
],
"From recording": [
"使用录制尺寸"
],
"Rows": [
"行数"
],
"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.": [
"加载后,占位提示会显示录制文件的原始行列数。留空可使用录制尺寸,并跟随录制中的尺寸变化。手动设置会改变字符网格,而非显示宽度,可能影响排版或裁切内容。"
],
"Use recording size": [
"使用录制尺寸"
],
"Asciinema": [
"Asciinema"
],
"Recording theme (automatic)": [
"录制文件主题(自动)"
],
"Custom": [
"自定义"
],
"Width": [
"按宽度缩放"
],
"Original size": [
"原始大小"
],
"Height (legacy)": [
"按高度缩放(旧版)"
],
"Width and height (legacy)": [
"按宽高缩放(旧版)"
],
"Example terminal recording": [
"终端录屏示例"
],
"A terminal recording, right in your post.": [
"在文章中直接播放终端录屏。"
],
"Terminal size": [
"终端尺寸"
],
"Terminal size (columns × rows)": [
"终端尺寸(列数 × 行数)"
],
"Close": [
"关闭"
],
"Display": [
"显示"
],
"Player width": [
"播放器宽度"
],
"Custom width": [
"自定义宽度"
],
"Use a CSS length, such as 480px or 65%. The player stays within its available space.": [
"使用 CSS 长度,例如 480px 或 65%。播放器不会超出可用空间。"
],
"Enter a positive width with a unit, such as 480px or 65%. The last valid width is kept.": [
"请输入带单位的正数宽度,例如 480px 或 65%。将保留上一次有效的宽度。"
],
"Display alignment": [
"对齐方式"
],
"Left": [
"左对齐"
],
"Center": [
"居中"
],
"Right": [
"右对齐"
],
"Display width scales the recording without changing its terminal columns or rows. Add a caption directly below the player.": [
"显示宽度只缩放画面,不改变终端行列数。可在播放器下方直接添加说明文字。"
],
"Playback": [
"播放"
],
"Playback speed": [
"播放速度"
],
"Loop playback": [
"循环播放"
],
"Autoplay on published page": [
"在发布后的页面自动播放"
],
"The editor preview always waits for you to press play.": [
"编辑器预览始终需要点击播放后才会开始。"
],
"Preload on published page": [
"在发布后的页面预加载"
],
"Loads the recording before the visitor presses play. The editor preview always preloads a valid recording URL.": [
"在访客点击播放前加载录制文件。编辑器预览始终会预加载有效的录制文件 URL。"
],
"Start at (seconds)": [
"起始时间(秒)"
],
"Idle time limit (seconds)": [
"最长空闲时间(秒)"
],
"Shorten long pauses. Use 0 to keep the recording’s default.": [
"缩短过长的停顿。设为 0 可保留录制文件的默认设置。"
],
"Appearance": [
"外观"
],
"Theme": [
"主题"
],
"Player controls": [
"播放控制栏"
],
"Show on interaction": [
"交互时显示"
],
"Always show": [
"始终显示"
],
"Hide": [
"隐藏"
],
"Fit": [
"缩放方式"
],
"Height-based fitting requires a fixed container height in your site CSS.": [
"按高度缩放需要在站点 CSS 中设置固定的容器高度。"
],
"The custom container style from your shortcode is preserved on the published page.": [
"发布后的页面会保留简码中的自定义容器样式。"
],
"Help": [
"帮助"
],
"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.": [
"有效的录制文件 URL 会自动加载预览,重新打开编辑器时也一样。文件所在服务器会收到浏览器请求,发布后的播放器也会访问该服务器。请使用 .cast 文件直链;外部服务器需允许跨域请求(CORS)。"
],
"Use the player controls to play, pause, and seek. Autoplay is disabled only in the editor.": [
"使用播放器控件播放、暂停和跳转。仅编辑器预览禁用自动播放。"
],
"Recording URL": [
"录制文件 URL"
],
"Apply URL": [
"应用 URL"
],
"Choose an Asciicast recording": [
"选择 Asciicast 录制文件"
],
"Choose recording": [
"选择录制文件"
],
"Choose an Asciicast (.cast) file from the Media Library.": [
"请从媒体库选择 Asciicast(.cast)文件。"
],
"Enter an HTTP(S) recording URL or a path starting with a single /.": [
"请输入 HTTP(S) 录制文件 URL,或以单个 / 开头的路径。"
],
"Asciicast Player": [
"Asciicast 播放器"
],
"Enter a recording URL to load its preview automatically. Playback starts only when you press play.": [
"输入录制文件 URL 后会自动加载预览,点击播放才会开始播放。"
],
"Add a caption…": [
"添加说明文字…"
],
"Recording caption": [
"录屏说明文字"
],
"Height-based previews use the shortcode’s fixed height when available, or a 320px editor frame. Published height still comes from your container style.": [
"按高度缩放的预览会使用简码中的固定高度;未设置时使用 320px 的编辑器预览高度。发布后的高度仍由容器样式决定。"
],
"block title\u0004Asciicast Player": [
"Asciicast 播放器"
],
"block description\u0004Embed and preview a terminal recording with the locally bundled asciinema player.": [
"使用本地附带的 asciinema 播放器嵌入和预览终端录屏。"
],
"block keyword\u0004asciinema": [
"asciinema"
],
"block keyword\u0004terminal": [
"终端"
],
"block keyword\u0004recording": [
"录屏"
],
"Unable to load the recording. Check the URL, file format, and the source server’s CORS permissions.": [
"无法加载录制文件。请检查 URL、文件格式及来源服务器的跨域请求(CORS)权限。"
],
"The recording is taking too long to load. Check your connection and try again.": [
"录制文件加载超时。请检查网络连接后重试。"
],
"The local player could not start. Try again, or check that the plugin’s built assets are installed.": [
"本地播放器无法启动。请重试,或检查插件的构建资源是否已安装。"
],
"Loading recording…": [
"正在加载录制文件…"
],
"Retry preview": [
"重试预览"
],
"Interactive terminal recording preview": [
"可交互的终端录屏预览"
],
"Unable to load this terminal recording. The file may be unavailable, invalid, or blocked by the source server’s CORS policy.": [
"无法加载此终端录屏。文件可能无法访问、格式无效,或被来源服务器的跨域请求(CORS)策略阻止。"
],
"You are not allowed to upload Asciicast files.": [
"你没有上传 Asciicast 文件的权限。"
],
"Upload a valid Asciicast v2/v3 JSONL or pretty-printed v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, and 1,000 columns or rows).": [
"请上传有效的 Asciicast v2/v3 JSONL 或格式化的 v1 .cast 录制文件(最大 32 MiB;v1 最大 2 MiB;最多 100,000 个事件;每行 JSONL最大 256 KiB;列数和行数均不超过 1,000)。"
],
"Add interactive terminal recordings to posts and pages with a block or shortcode.": [
"通过区块或简码在文章和页面中添加可交互的终端录屏。"
]
}
}
}
Binary file not shown.
+367
View File
@@ -0,0 +1,367 @@
msgid ""
msgstr ""
"Project-Id-Version: wp-asciiplayer 1.1.0-dev\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Domain: wp-asciiplayer\n"
"Language: zh_CN\n"
"Plural-Forms: nplurals=1; plural=0;\n"
"Language-Team: Simplified Chinese\n"
#: src/edit.js:91
msgid "A terminal recording, right in your post."
msgstr "在文章中直接播放终端录屏。"
#: src/edit.js:139
msgid ""
"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."
msgstr ""
"有效的录制文件 URL 会自动加载预览,重新打开编辑器时也一样。文件所在服务器会收到浏览器请求,发布后的播放器也会访问该服务器。请使用 .cast "
"文件直链;外部服务器需允许跨域请求(CORS)。"
#: src/edit.js:165
msgid "Add a caption…"
msgstr "添加说明文字…"
#: asciicast-player.php:1
msgid ""
"Add interactive terminal recordings to posts and pages with a block or "
"shortcode."
msgstr "通过区块或简码在文章和页面中添加可交互的终端录屏。"
#: src/edit.js:132
msgid "Always show"
msgstr "始终显示"
#: src/edit.js:128
msgid "Appearance"
msgstr "外观"
#: src/edit.js:147
msgid "Apply URL"
msgstr "应用 URL"
#: src/edit.js:163
#: asciicast-player.php:1
msgid "Asciicast Player"
msgstr "Asciicast 播放器"
#: src/edit.js:73
msgid "Asciinema"
msgstr "Asciinema"
#: src/edit.js:123
msgid "Autoplay on published page"
msgstr "在发布后的页面自动播放"
#: src/edit.js:116
msgid "Center"
msgstr "居中"
#: src/edit.js:154
msgid "Choose an Asciicast (.cast) file from the Media Library."
msgstr "请从媒体库选择 Asciicast(.cast)文件。"
#: src/edit.js:150
msgid "Choose an Asciicast recording"
msgstr "选择 Asciicast 录制文件"
#: src/edit.js:151
msgid "Choose recording"
msgstr "选择录制文件"
#: src/edit.js:104
msgid "Close"
msgstr "关闭"
#: src/edit.js:12
msgid "Columns"
msgstr "列数"
#: src/edit.js:81
msgid "Custom"
msgstr "自定义"
#: src/edit.js:115
msgid "Custom width"
msgstr "自定义宽度"
#: src/edit.js:113
msgid "Display"
msgstr "显示"
#: src/edit.js:116
msgid "Display alignment"
msgstr "对齐方式"
#: src/edit.js:117
msgid ""
"Display width scales the recording without changing its terminal columns or "
"rows. Add a caption directly below the player."
msgstr "显示宽度只缩放画面,不改变终端行列数。可在播放器下方直接添加说明文字。"
#: src/edit.js:115
msgid ""
"Enter a positive width with a unit, such as 480px or 65%. The last valid "
"width is kept."
msgstr "请输入带单位的正数宽度,例如 480px 或 65%。将保留上一次有效的宽度。"
#: src/edit.js:163
msgid ""
"Enter a recording URL to load its preview automatically. Playback starts "
"only when you press play."
msgstr "输入录制文件 URL 后会自动加载预览,点击播放才会开始播放。"
#: src/edit.js:155
msgid "Enter an HTTP(S) recording URL or a path starting with a single /."
msgstr "请输入 HTTP(S) 录制文件 URL,或以单个 / 开头的路径。"
#: src/edit.js:91
msgid "Example terminal recording"
msgstr "终端录屏示例"
#: src/edit.js:135
msgid "Fit"
msgstr "缩放方式"
#: src/edit.js:12
#: src/edit.js:13
msgid "From recording"
msgstr "使用录制尺寸"
#: src/edit.js:89
msgid "Height (legacy)"
msgstr "按高度缩放(旧版)"
#: src/edit.js:135
msgid "Height-based fitting requires a fixed container height in your site CSS."
msgstr "按高度缩放需要在站点 CSS 中设置固定的容器高度。"
#: src/edit.js:167
msgid ""
"Height-based previews use the shortcode’s fixed height when available, or a "
"320px editor frame. Published height still comes from your container style."
msgstr "按高度缩放的预览会使用简码中的固定高度;未设置时使用 320px 的编辑器预览高度。发布后的高度仍由容器样式决定。"
#: src/edit.js:138
msgid "Help"
msgstr "帮助"
#: src/edit.js:133
msgid "Hide"
msgstr "隐藏"
#: src/edit.js:126
msgid "Idle time limit (seconds)"
msgstr "最长空闲时间(秒)"
#: src/preview.js:85
msgid "Interactive terminal recording preview"
msgstr "可交互的终端录屏预览"
#: src/edit.js:116
msgid "Left"
msgstr "左对齐"
#: src/preview.js:83
msgid "Loading recording…"
msgstr "正在加载录制文件…"
#: src/edit.js:124
msgid ""
"Loads the recording before the visitor presses play. The editor preview "
"always preloads a valid recording URL."
msgstr "在访客点击播放前加载录制文件。编辑器预览始终会预加载有效的录制文件 URL。"
#: src/edit.js:122
msgid "Loop playback"
msgstr "循环播放"
#: src/edit.js:87
msgid "Original size"
msgstr "原始大小"
#: src/edit.js:15
msgid ""
"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."
msgstr "加载后,占位提示会显示录制文件的原始行列数。留空可使用录制尺寸,并跟随录制中的尺寸变化。手动设置会改变字符网格,而非显示宽度,可能影响排版或裁切内容。"
#: src/edit.js:120
msgid "Playback"
msgstr "播放"
#: src/edit.js:121
msgid "Playback speed"
msgstr "播放速度"
#: src/edit.js:130
msgid "Player controls"
msgstr "播放控制栏"
#: src/edit.js:114
msgid "Player width"
msgstr "播放器宽度"
#: src/edit.js:124
msgid "Preload on published page"
msgstr "在发布后的页面预加载"
#: src/edit.js:165
msgid "Recording caption"
msgstr "录屏说明文字"
#: src/edit.js:74
msgid "Recording theme (automatic)"
msgstr "录制文件主题(自动)"
#: src/edit.js:146
msgid "Recording URL"
msgstr "录制文件 URL"
#: src/preview.js:84
msgid "Retry preview"
msgstr "重试预览"
#: src/edit.js:116
msgid "Right"
msgstr "右对齐"
#: src/edit.js:13
msgid "Rows"
msgstr "行数"
#: src/edit.js:126
msgid "Shorten long pauses. Use 0 to keep the recording’s default."
msgstr "缩短过长的停顿。设为 0 可保留录制文件的默认设置。"
#: src/edit.js:131
msgid "Show on interaction"
msgstr "交互时显示"
#: src/edit.js:125
msgid "Start at (seconds)"
msgstr "起始时间(秒)"
#: src/edit.js:99
#: src/edit.js:101
#: src/edit.js:110
msgid "Terminal size"
msgstr "终端尺寸"
#: src/edit.js:102
msgid "Terminal size (columns × rows)"
msgstr "终端尺寸(列数 × 行数)"
#: src/edit.js:136
msgid ""
"The custom container style from your shortcode is preserved on the "
"published page."
msgstr "发布后的页面会保留简码中的自定义容器样式。"
#: src/edit.js:123
msgid "The editor preview always waits for you to press play."
msgstr "编辑器预览始终需要点击播放后才会开始。"
#: src/preview.js:70
msgid ""
"The local player could not start. Try again, or check that the plugin’s "
"built assets are installed."
msgstr "本地播放器无法启动。请重试,或检查插件的构建资源是否已安装。"
#: src/preview.js:68
msgid ""
"The recording is taking too long to load. Check your connection and try "
"again."
msgstr "录制文件加载超时。请检查网络连接后重试。"
#: src/edit.js:129
msgid "Theme"
msgstr "主题"
#: src/preview.js:59
msgid ""
"Unable to load the recording. Check the URL, file format, and the source "
"server’s CORS permissions."
msgstr "无法加载录制文件。请检查 URL、文件格式及来源服务器的跨域请求(CORS)权限。"
#: src/view.js:12
msgid ""
"Unable to load this terminal recording. The file may be unavailable, "
"invalid, or blocked by the source server’s CORS policy."
msgstr "无法加载此终端录屏。文件可能无法访问、格式无效,或被来源服务器的跨域请求(CORS)策略阻止。"
#: includes/uploads.php:197
msgid ""
"Upload a valid Asciicast v2/v3 JSONL or pretty-printed v1 .cast recording "
"(up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, and "
"1,000 columns or rows)."
msgstr ""
"请上传有效的 Asciicast v2/v3 JSONL 或格式化的 v1 .cast 录制文件(最大 32 MiB;v1 最大 2 MiB;最多 "
"100,000 个事件;每行 JSONL最大 256 KiB;列数和行数均不超过 1,000)。"
#: src/edit.js:115
msgid ""
"Use a CSS length, such as 480px or 65%. The player stays within its "
"available space."
msgstr "使用 CSS 长度,例如 480px 或 65%。播放器不会超出可用空间。"
#: src/edit.js:16
msgid "Use recording size"
msgstr "使用录制尺寸"
#: src/edit.js:140
msgid ""
"Use the player controls to play, pause, and seek. Autoplay is disabled only "
"in the editor."
msgstr "使用播放器控件播放、暂停和跳转。仅编辑器预览禁用自动播放。"
#: src/edit.js:86
msgid "Width"
msgstr "按宽度缩放"
#: src/edit.js:89
msgid "Width and height (legacy)"
msgstr "按宽高缩放(旧版)"
#: includes/uploads.php:195
msgid "You are not allowed to upload Asciicast files."
msgstr "你没有上传 Asciicast 文件的权限。"
#: src/index.js:19
#: block.json:1
msgctxt "block description"
msgid ""
"Embed and preview a terminal recording with the locally bundled asciinema "
"player."
msgstr "使用本地附带的 asciinema 播放器嵌入和预览终端录屏。"
#: src/index.js:20
#: block.json:1
msgctxt "block keyword"
msgid "asciinema"
msgstr "asciinema"
#: src/index.js:20
#: block.json:1
msgctxt "block keyword"
msgid "recording"
msgstr "录屏"
#: src/index.js:20
#: block.json:1
msgctxt "block keyword"
msgid "terminal"
msgstr "终端"
#: src/index.js:18
#: block.json:1
msgctxt "block title"
msgid "Asciicast Player"
msgstr "Asciicast 播放器"
+360
View File
@@ -0,0 +1,360 @@
msgid ""
msgstr ""
"Project-Id-Version: wp-asciiplayer 1.1.0-dev\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Domain: wp-asciiplayer\n"
#: src/edit.js:91
msgid "A terminal recording, right in your post."
msgstr ""
#: src/edit.js:139
msgid ""
"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."
msgstr ""
#: src/edit.js:165
msgid "Add a caption…"
msgstr ""
#: asciicast-player.php:1
msgid ""
"Add interactive terminal recordings to posts and pages with a block or "
"shortcode."
msgstr ""
#: src/edit.js:132
msgid "Always show"
msgstr ""
#: src/edit.js:128
msgid "Appearance"
msgstr ""
#: src/edit.js:147
msgid "Apply URL"
msgstr ""
#: src/edit.js:163
#: asciicast-player.php:1
msgid "Asciicast Player"
msgstr ""
#: src/edit.js:73
msgid "Asciinema"
msgstr ""
#: src/edit.js:123
msgid "Autoplay on published page"
msgstr ""
#: src/edit.js:116
msgid "Center"
msgstr ""
#: src/edit.js:154
msgid "Choose an Asciicast (.cast) file from the Media Library."
msgstr ""
#: src/edit.js:150
msgid "Choose an Asciicast recording"
msgstr ""
#: src/edit.js:151
msgid "Choose recording"
msgstr ""
#: src/edit.js:104
msgid "Close"
msgstr ""
#: src/edit.js:12
msgid "Columns"
msgstr ""
#: src/edit.js:81
msgid "Custom"
msgstr ""
#: src/edit.js:115
msgid "Custom width"
msgstr ""
#: src/edit.js:113
msgid "Display"
msgstr ""
#: src/edit.js:116
msgid "Display alignment"
msgstr ""
#: src/edit.js:117
msgid ""
"Display width scales the recording without changing its terminal columns or "
"rows. Add a caption directly below the player."
msgstr ""
#: src/edit.js:115
msgid ""
"Enter a positive width with a unit, such as 480px or 65%. The last valid "
"width is kept."
msgstr ""
#: src/edit.js:163
msgid ""
"Enter a recording URL to load its preview automatically. Playback starts "
"only when you press play."
msgstr ""
#: src/edit.js:155
msgid "Enter an HTTP(S) recording URL or a path starting with a single /."
msgstr ""
#: src/edit.js:91
msgid "Example terminal recording"
msgstr ""
#: src/edit.js:135
msgid "Fit"
msgstr ""
#: src/edit.js:12
#: src/edit.js:13
msgid "From recording"
msgstr ""
#: src/edit.js:89
msgid "Height (legacy)"
msgstr ""
#: src/edit.js:135
msgid "Height-based fitting requires a fixed container height in your site CSS."
msgstr ""
#: src/edit.js:167
msgid ""
"Height-based previews use the shortcode’s fixed height when available, or a "
"320px editor frame. Published height still comes from your container style."
msgstr ""
#: src/edit.js:138
msgid "Help"
msgstr ""
#: src/edit.js:133
msgid "Hide"
msgstr ""
#: src/edit.js:126
msgid "Idle time limit (seconds)"
msgstr ""
#: src/preview.js:85
msgid "Interactive terminal recording preview"
msgstr ""
#: src/edit.js:116
msgid "Left"
msgstr ""
#: src/preview.js:83
msgid "Loading recording…"
msgstr ""
#: src/edit.js:124
msgid ""
"Loads the recording before the visitor presses play. The editor preview "
"always preloads a valid recording URL."
msgstr ""
#: src/edit.js:122
msgid "Loop playback"
msgstr ""
#: src/edit.js:87
msgid "Original size"
msgstr ""
#: src/edit.js:15
msgid ""
"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."
msgstr ""
#: src/edit.js:120
msgid "Playback"
msgstr ""
#: src/edit.js:121
msgid "Playback speed"
msgstr ""
#: src/edit.js:130
msgid "Player controls"
msgstr ""
#: src/edit.js:114
msgid "Player width"
msgstr ""
#: src/edit.js:124
msgid "Preload on published page"
msgstr ""
#: src/edit.js:165
msgid "Recording caption"
msgstr ""
#: src/edit.js:74
msgid "Recording theme (automatic)"
msgstr ""
#: src/edit.js:146
msgid "Recording URL"
msgstr ""
#: src/preview.js:84
msgid "Retry preview"
msgstr ""
#: src/edit.js:116
msgid "Right"
msgstr ""
#: src/edit.js:13
msgid "Rows"
msgstr ""
#: src/edit.js:126
msgid "Shorten long pauses. Use 0 to keep the recording’s default."
msgstr ""
#: src/edit.js:131
msgid "Show on interaction"
msgstr ""
#: src/edit.js:125
msgid "Start at (seconds)"
msgstr ""
#: src/edit.js:99
#: src/edit.js:101
#: src/edit.js:110
msgid "Terminal size"
msgstr ""
#: src/edit.js:102
msgid "Terminal size (columns × rows)"
msgstr ""
#: src/edit.js:136
msgid ""
"The custom container style from your shortcode is preserved on the "
"published page."
msgstr ""
#: src/edit.js:123
msgid "The editor preview always waits for you to press play."
msgstr ""
#: src/preview.js:70
msgid ""
"The local player could not start. Try again, or check that the plugin’s "
"built assets are installed."
msgstr ""
#: src/preview.js:68
msgid ""
"The recording is taking too long to load. Check your connection and try "
"again."
msgstr ""
#: src/edit.js:129
msgid "Theme"
msgstr ""
#: src/preview.js:59
msgid ""
"Unable to load the recording. Check the URL, file format, and the source "
"server’s CORS permissions."
msgstr ""
#: src/view.js:12
msgid ""
"Unable to load this terminal recording. The file may be unavailable, "
"invalid, or blocked by the source server’s CORS policy."
msgstr ""
#: includes/uploads.php:197
msgid ""
"Upload a valid Asciicast v2/v3 JSONL or pretty-printed v1 .cast recording "
"(up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, and "
"1,000 columns or rows)."
msgstr ""
#: src/edit.js:115
msgid ""
"Use a CSS length, such as 480px or 65%. The player stays within its "
"available space."
msgstr ""
#: src/edit.js:16
msgid "Use recording size"
msgstr ""
#: src/edit.js:140
msgid ""
"Use the player controls to play, pause, and seek. Autoplay is disabled only "
"in the editor."
msgstr ""
#: src/edit.js:86
msgid "Width"
msgstr ""
#: src/edit.js:89
msgid "Width and height (legacy)"
msgstr ""
#: includes/uploads.php:195
msgid "You are not allowed to upload Asciicast files."
msgstr ""
#: src/index.js:19
#: block.json:1
msgctxt "block description"
msgid ""
"Embed and preview a terminal recording with the locally bundled asciinema "
"player."
msgstr ""
#: src/index.js:20
#: block.json:1
msgctxt "block keyword"
msgid "asciinema"
msgstr ""
#: src/index.js:20
#: block.json:1
msgctxt "block keyword"
msgid "recording"
msgstr ""
#: src/index.js:20
#: block.json:1
msgctxt "block keyword"
msgid "terminal"
msgstr ""
#: src/index.js:18
#: block.json:1
msgctxt "block title"
msgid "Asciicast Player"
msgstr ""
+5 -3
View File
@@ -1,20 +1,22 @@
{ {
"name": "wp-asciiplayer", "name": "wp-asciiplayer",
"version": "1.1.0", "version": "1.1.0-dev",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "wp-asciiplayer", "name": "wp-asciiplayer",
"version": "1.1.0", "version": "1.1.0-dev",
"license": "GPL-3.0-only", "license": "GPL-3.0-only",
"dependencies": { "dependencies": {
"asciinema-player": "3.17.0" "asciinema-player": "3.17.0"
}, },
"devDependencies": { "devDependencies": {
"@babel/parser": "7.29.9",
"@playwright/test": "1.64.0", "@playwright/test": "1.64.0",
"@wordpress/env": "11.17.0", "@wordpress/env": "11.17.0",
"@wordpress/scripts": "36.1.0" "@wordpress/scripts": "36.1.0",
"gettext-parser": "1.4.0"
}, },
"engines": { "engines": {
"node": ">=22.22.2" "node": ">=22.22.2"
+19 -5
View File
@@ -1,6 +1,6 @@
{ {
"name": "wp-asciiplayer", "name": "wp-asciiplayer",
"version": "1.1.0", "version": "1.1.0-dev",
"private": true, "private": true,
"description": "Native WordPress asciicast block with real playback previews and compatible shortcodes", "description": "Native WordPress asciicast block with real playback previews and compatible shortcodes",
"type": "module", "type": "module",
@@ -9,13 +9,15 @@
"node": ">=22.22.2" "node": ">=22.22.2"
}, },
"scripts": { "scripts": {
"build": "wp-scripts build --config webpack.config.cjs && node scripts/vendor.mjs && node scripts/verify-build.mjs", "build": "wp-scripts build --config webpack.config.cjs && node scripts/vendor.mjs && npm run i18n && node scripts/verify-build.mjs",
"start": "wp-scripts start --config webpack.config.cjs", "start": "wp-scripts start --config webpack.config.cjs",
"test": "node --test tests/js/*.test.js", "test": "npm run i18n:check && node --test tests/js/*.test.js",
"test:php": "php tests/php/run.php", "test:php": "php tests/php/run.php",
"test:e2e": "playwright test", "test:e2e": "playwright test",
"wp-env": "wp-env", "wp-env": "wp-env",
"package": "node scripts/package.mjs" "package": "node scripts/package.mjs",
"i18n": "node scripts/i18n.mjs",
"i18n:check": "node scripts/i18n.mjs --check"
}, },
"dependencies": { "dependencies": {
"asciinema-player": "3.17.0" "asciinema-player": "3.17.0"
@@ -23,6 +25,18 @@
"devDependencies": { "devDependencies": {
"@playwright/test": "1.64.0", "@playwright/test": "1.64.0",
"@wordpress/env": "11.17.0", "@wordpress/env": "11.17.0",
"@wordpress/scripts": "36.1.0" "@wordpress/scripts": "36.1.0",
"@babel/parser": "7.29.9",
"gettext-parser": "1.4.0"
},
"cssnano": {
"preset": [
"default",
{
"discardComments": {
"removeAll": false
}
}
]
} }
} }
+28 -5
View File
@@ -4,7 +4,7 @@ Tags: asciicast, asciiplayer, asciinema, terminal, block
Requires at least: 6.3 Requires at least: 6.3
Tested up to: 7.1 Tested up to: 7.1
Requires PHP: 7.4 Requires PHP: 7.4
Stable tag: 1.1.0 Stable tag: 1.1.0-dev
License: GPL-3.0-only License: GPL-3.0-only
License URI: https://www.gnu.org/licenses/gpl-3.0.html License URI: https://www.gnu.org/licenses/gpl-3.0.html
@@ -17,14 +17,15 @@ Insert an Asciicast Player block, apply a recording-file URL, and play it direct
* Locally bundled asciinema-player, JavaScript, CSS and WebAssembly. * Locally bundled asciinema-player, JavaScript, CSS and WebAssembly.
* Native block-editor controls and iframe-aware interactive preview. * Native block-editor controls and iframe-aware interactive preview.
* Compatible shortcode rendering in posts and pages. * Compatible shortcode rendering in posts and pages.
* Explicit editor preview loading and clear loading/failure feedback. * Automatic preview loading for valid URLs, debounced editing, and clear loading/failure feedback.
* No account, analytics, remote proxy, custom post type or extra upload permissions. * Media Library selection and validated .cast uploads using existing WordPress upload permissions.
* No account, analytics, remote proxy, custom post type or extra upload capabilities.
The source and reproducible build instructions are included in the ZIP and available at https://github.com/LamGC/wp-asciiplayer . Third-party licenses are in THIRD-PARTY-NOTICES.md and licenses/. The source and reproducible build instructions are included in the ZIP and available at https://github.com/LamGC/wp-asciiplayer . Third-party licenses are in THIRD-PARTY-NOTICES.md and licenses/.
= External recordings and privacy = = External recordings and privacy =
The plugin itself uses no external runtime service. When you choose an external recording URL, the visitor's browser requests that URL directly. The host may receive IP address, browser request metadata and a referrer according to browser/site policy. Applying a URL or loading a preview in the editor makes the same request. Choose a trusted host and consult its privacy policy. Use a same-site HTTPS recording URL to avoid third-party requests. Review terminal output for sensitive data before publishing. The plugin itself uses no external runtime service. When you choose an external recording URL, the visitor's browser requests that URL directly. The host may receive IP address, browser request metadata and a referrer according to browser/site policy. A valid URL automatically loads the editor preview and makes the same request, including when reopening a saved block. Choose a trusted host and consult its privacy policy. Use a same-site HTTPS recording URL to avoid third-party requests. Review terminal output for sensitive data before publishing.
== Installation == == Installation ==
@@ -52,9 +53,31 @@ No. The JavaScript, CSS and WebAssembly ship with the plugin. The previous ap_us
Existing shortcodes work in the Classic Editor. The new visual controls and inline playback preview are for the block editor. Existing shortcodes work in the Classic Editor. The new visual controls and inline playback preview are for the block editor.
= Which languages are included? =
English (en_US fallback) and Simplified Chinese (zh_CN) are bundled and work offline. Plugin-owned editor controls follow the WordPress user language; public pages follow the site language. Set these in Users > Profile and Settings > General. Other Chinese locales, including zh_TW, are not mapped to zh_CN. Recording output and author captions are never translated. The upstream player's own controls and help remain English.
== Changelog == == Changelog ==
= 1.1.0 = = 1.1.0-dev (unreleased) =
* Development preview only, not a tagged or published release. Earlier draft package labels 1.1.0 and 1.2.0–1.2.3 were internal iteration labels, not releases.
* Bundle English/Simplified Chinese plugin UI translations using WordPress gettext, with reproducible PO/MO/JSON catalogs and real locale integration tests.
* Use asset content hashes to prevent stale resources between development builds.
* Move recording/privacy and playback explanations from the block canvas to a collapsed sidebar Help panel.
* Show original cast dimensions as toolbar/sidebar placeholders without forcing overrides.
* Refresh recording metadata when the URL changes, reusing the preview request.
* Select and upload validated .cast recordings through the native Media Library.
* Automatically load saved recording previews without enabling playback autoplay.
* Debounce recording URL edits; retain immediate apply, retry and request cleanup.
* Add terminal Columns/Rows and reset controls to the floating block toolbar, synchronized with the collapsed sidebar panel.
* 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.
* Add a native block with typed controls and interactive, iframe-aware preview. * Add a native block with typed controls and interactive, iframe-aware preview.
* Preserve shortcode support and normalize historical parameter names and types. * Preserve shortcode support and normalize historical parameter names and types.
* Escape output, constrain recording URLs, and filter custom styles. * Escape output, constrain recording URLs, and filter custom styles.
+84
View File
@@ -0,0 +1,84 @@
/** Deterministic gettext catalogs. English msgids are the en_US fallback. */
import fs from 'node:fs';
import path from 'node:path';
import assert from 'node:assert/strict';
import { parse } from '@babel/parser';
import gettext from 'gettext-parser';
const domain = 'wp-asciiplayer';
const version = JSON.parse(fs.readFileSync('package.json')).version;
const entries = new Map();
function add(msgid, context, file, line) {
assert.equal(typeof msgid, 'string', `Static gettext string required: ${file}:${line}`);
const key = `${context || ''}\u0004${msgid}`;
if (!entries.has(key)) entries.set(key, { msgid, msgctxt: context || undefined, msgstr: [''], comments: { reference: '' } });
const entry = entries.get(key);
entry.comments.reference += `${entry.comments.reference ? '\n' : ''}${file}:${line}`;
}
function walk(node, file) {
if (!node || typeof node !== 'object') return;
if (node.type === 'CallExpression' && ['__', '_x', '_n', '_nx'].includes(node.callee?.name)) {
const name = node.callee.name;
assert.ok(['__', '_x'].includes(name), `Add plural extraction before using ${name}: ${file}`);
const args = node.arguments;
assert.equal(args[name === '__' ? 1 : 2]?.value, domain, `Explicit textdomain required: ${file}`);
assert.equal(args[0]?.type, 'StringLiteral', `Literal gettext message required: ${file}`);
if (name === '_x') assert.equal(args[1]?.type, 'StringLiteral');
add(args[0].value, name === '_x' ? args[1].value : '', file, node.loc.start.line);
}
for (const value of Object.values(node)) {
if (Array.isArray(value)) for (const child of value) walk(child, file);
else if (value && typeof value === 'object') walk(value, file);
}
}
for (const file of fs.readdirSync('src').filter((name) => name.endsWith('.js')).map((name) => `src/${name}`)) {
walk(parse(fs.readFileSync(file, 'utf8'), { sourceType: 'module', plugins: ['jsx'] }), file);
}
for (const file of ['asciicast-player.php', ...fs.readdirSync('includes').filter((name) => name.endsWith('.php')).map((name) => `includes/${name}`)]) {
const source = fs.readFileSync(file, 'utf8');
const calls = [...source.matchAll(/\b__\s*\(/g)];
const matches = [...source.matchAll(/\b__\(\s*'((?:\\.|[^'\\])*)'\s*,\s*'wp-asciiplayer'\s*\)/g)];
assert.equal(matches.length, calls.length, `Unsupported PHP gettext syntax in ${file}; extend extractor first.`);
assert.ok(!/\b(?:_x|_n|_nx|_e|esc_html__|esc_attr__)\s*\(/.test(source), `Extend PHP extractor for new gettext functions: ${file}`);
for (const match of matches) add(match[1].replace(/\\(['\\])/g, '$1'), '', file, source.slice(0, match.index).split('\n').length);
}
const pluginHeader = fs.readFileSync('asciicast-player.php', 'utf8');
for (const label of ['Plugin Name', 'Description']) {
const value = pluginHeader.match(new RegExp(` \* ${label}: (.+)`))?.[1];
if (value) add(value, '', 'asciicast-player.php', 1);
}
const metadata = JSON.parse(fs.readFileSync('block.json'));
for (const [field, context] of [['title', 'block title'], ['description', 'block description'], ['keywords', 'block keyword']]) {
for (const value of [].concat(metadata[field])) add(value, context, 'block.json', 1);
}
const headers = { 'project-id-version': `${domain} ${version}`, 'mime-version': '1.0', 'content-type': 'text/plain; charset=UTF-8', 'content-transfer-encoding': '8bit', 'x-domain': domain };
const pot = { charset: 'utf-8', headers, translations: { '': {} } };
for (const entry of [...entries.values()].sort((a, b) => `${a.msgctxt || ''}\u0004${a.msgid}`.localeCompare(`${b.msgctxt || ''}\u0004${b.msgid}`, 'en'))) {
const context = entry.msgctxt || '';
(pot.translations[context] ||= {})[entry.msgid] = entry;
}
fs.mkdirSync('languages', { recursive: true });
const output = new Map([['languages/wp-asciiplayer.pot', gettext.po.compile(pot)]]);
if (!process.argv.includes('--pot-only')) {
const po = gettext.po.parse(fs.readFileSync('languages/wp-asciiplayer-zh_CN.po'));
assert.equal(po.headers.language, 'zh_CN');
assert.match(po.headers['plural-forms'], /^nplurals=1;\s*plural=0;$/);
const messages = { '': { domain, lang: 'zh_CN', 'plural-forms': 'nplurals=1; plural=0;' } };
for (const entry of entries.values()) {
const translation = po.translations[entry.msgctxt || '']?.[entry.msgid];
assert.ok(translation?.msgstr?.[0], `Missing zh_CN translation: ${entry.msgid}`);
assert.ok(!translation.comments?.flag?.includes('fuzzy'), `Fuzzy translation: ${entry.msgid}`);
assert.ok(!translation.msgid_plural && translation.msgstr.length === 1, `Unexpected plural: ${entry.msgid}`);
const placeholders = (text) => [...text.matchAll(/%(?:\d+\$)?[sdif]/g)].map((match) => match[0]).sort();
assert.deepEqual(placeholders(translation.msgstr[0]), placeholders(entry.msgid), `Placeholder mismatch: ${entry.msgid}`);
messages[entry.msgctxt ? `${entry.msgctxt}\u0004${entry.msgid}` : entry.msgid] = translation.msgstr;
}
output.set('languages/wp-asciiplayer-zh_CN.mo', gettext.mo.compile(po));
const json = `${JSON.stringify({ domain, locale_data: { messages } }, null, 2)}\n`;
for (const handle of ['lamgc-asciiplayer-editor', 'lamgc-asciiplayer-view']) output.set(`languages/wp-asciiplayer-zh_CN-${handle}.json`, json);
}
for (const [file, content] of output) {
if (process.argv.includes('--check')) assert.deepEqual(fs.readFileSync(file), Buffer.from(content), `Stale catalog: ${file}; run npm run i18n.`);
else fs.writeFileSync(file, content);
}
console.log(`Verified ${entries.size} gettext entries; ${output.size} reproducible artifacts${process.argv.includes('--check') ? ' checked' : ' written'}.`);
+3 -2
View File
@@ -4,7 +4,8 @@ import path from 'node:path';
import os from 'node:os'; import os from 'node:os';
const root = path.resolve(import.meta.dirname, '..'); const root = path.resolve(import.meta.dirname, '..');
const required = ['build/block.json', 'build/index.js', 'build/index.asset.php', 'build/view.js', 'build/view.asset.php', 'build/player.js', 'build/player.css']; execFileSync(process.execPath, ['scripts/i18n.mjs', '--check'], { cwd: root, stdio: 'inherit' });
const required = ['build/block.json', 'build/index.js', 'build/index.asset.php', 'build/view.js', 'build/view.asset.php', 'build/player.js', 'build/player.css', 'build/runtime.asset.php', 'languages/wp-asciiplayer-zh_CN.mo', 'languages/wp-asciiplayer-zh_CN-lamgc-asciiplayer-editor.json', 'languages/wp-asciiplayer-zh_CN-lamgc-asciiplayer-view.json'];
for (const file of required) await stat(path.join(root, file)); for (const file of required) await stat(path.join(root, file));
const pkg = JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8')); const pkg = JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8'));
const php = await readFile(path.join(root, 'asciicast-player.php'), 'utf8'); const php = await readFile(path.join(root, 'asciicast-player.php'), 'utf8');
@@ -12,7 +13,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.'); 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 temp = await mkdtemp(path.join(os.tmpdir(), 'wp-asciiplayer-package-'));
const target = path.join(temp, 'wp-asciiplayer'); 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', 'languages', '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'];
try { try {
await mkdir(target); await mkdir(target);
for (const file of inputs) await cp(path.join(root, file), path.join(target, file), { recursive: true }); for (const file of inputs) await cp(path.join(root, file), path.join(target, file), { recursive: true });
+10 -1
View File
@@ -1,5 +1,6 @@
import { copyFile, mkdir, readFile } from 'node:fs/promises'; import { copyFile, mkdir, readFile, writeFile } from 'node:fs/promises';
import path from 'node:path'; import path from 'node:path';
import { createHash } from 'node:crypto';
const root = path.resolve(import.meta.dirname, '..'); const root = path.resolve(import.meta.dirname, '..');
const pkg = JSON.parse(await readFile(path.join(root, 'node_modules/asciinema-player/package.json'), 'utf8')); const pkg = JSON.parse(await readFile(path.join(root, 'node_modules/asciinema-player/package.json'), 'utf8'));
@@ -13,3 +14,11 @@ for (const [source, destination] of [
} }
await copyFile(path.join(root, 'block.json'), path.join(root, 'build/block.json')); await copyFile(path.join(root, 'block.json'), path.join(root, 'build/block.json'));
console.log(`Bundled local asciinema-player ${pkg.version}; no CDN is used.`); console.log(`Bundled local asciinema-player ${pkg.version}; no CDN is used.`);
// Content hashes avoid stale assets across successive builds of 1.1.0-dev.
const versions = [];
for (const file of ['player.js', 'player.css', 'style-index.css', 'index.css']) {
const hash = createHash('sha256').update(await readFile(path.join(root, 'build', file))).digest('hex').slice(0, 16);
versions.push(`'${file}' => '${hash}'`);
}
await writeFile(path.join(root, 'build/runtime.asset.php'), `<?php return array(${versions.join(', ')});\n`);
+8
View File
@@ -51,3 +51,11 @@ for (const readyState of ['loading', 'complete']) {
assert.equal(container.dataset.apStatus, 'idle'); assert.equal(container.dataset.apStatus, 'idle');
} }
console.log('Verified WordPress 6.3 dependencies, block metadata, exact vendor files, and emitted frontend boot.'); 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/);
}
+108 -22
View File
@@ -1,17 +1,51 @@
import { InspectorControls, useBlockProps } from '@wordpress/block-editor'; import { BlockAlignmentToolbar, BlockControls, InspectorControls, MediaUpload, MediaUploadCheck, RichText, useBlockProps } from '@wordpress/block-editor';
import { Button, Notice, PanelBody, Placeholder, RangeControl, SelectControl, TextControl, ToggleControl } from '@wordpress/components'; import { Button, Dropdown, Notice, PanelBody, Placeholder, RangeControl, SelectControl, TextControl, ToggleControl, ToolbarButton, ToolbarGroup } from '@wordpress/components';
import { useEffect, useState } from '@wordpress/element'; import { useCallback, useEffect, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n'; 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'; import Preview from './preview.js';
export default function Edit( { attributes, setAttributes } ) { /** One shared set of dimension controls in the block toolbar and settings sidebar. */
const { source, theme, speed, loop, controls, fit, startAt, idleTimeLimit, autoPlay, preload, width } = attributes; 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 [ draftSource, setDraftSource ] = useState( source );
const [ approvedSource, setApprovedSource ] = useState( '' );
const [ urlError, setUrlError ] = useState( false ); 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 [ attempt, setAttempt ] = useState( 0 );
useEffect( () => setDraftSource( source ), [ source ] ); 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 blockProps = useBlockProps( { className: 'asciiplayer-editor' } );
const applySource = ( event ) => { const applySource = ( event ) => {
event.preventDefault(); event.preventDefault();
@@ -20,7 +54,19 @@ export default function Edit( { attributes, setAttributes } ) {
if ( ! next ) return; if ( ! next ) return;
setAttributes( { source: next } ); setAttributes( { source: next } );
setDraftSource( next ); setDraftSource( next );
setApprovedSource( 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 ); setAttempt( ( current ) => current + 1 );
}; };
const themes = [ const themes = [
@@ -31,21 +77,51 @@ export default function Edit( { attributes, setAttributes } ) {
{ label: 'Solarized Light', value: 'solarized-light' }, { label: 'Tango', value: 'tango' }, { label: 'Solarized Light', value: 'solarized-light' }, { label: 'Tango', value: 'tango' },
]; ];
if ( ! themes.some( ( option ) => option.value === theme ) ) themes.push( { label: theme, value: theme } ); if ( ! themes.some( ( option ) => option.value === theme ) ) themes.push( { label: theme, value: theme } );
const widthOptions = [ '100%', '80%', '60%', '50%' ].map( ( value ) => ( { label: value, value } ) ); const widthPresets = [ '100%', '80%', '60%', '50%', '25%' ];
if ( ! widthOptions.some( ( option ) => option.value === width ) ) widthOptions.push( { label: width, value: width } ); 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 = [ const fitOptions = [
{ label: __( 'Width', 'wp-asciiplayer' ), value: 'width' }, { label: __( 'Width', 'wp-asciiplayer' ), value: 'width' },
{ label: __( 'Original size', 'wp-asciiplayer' ), value: 'none' }, { 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 ( 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 ( 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> <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' ) }> <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 ) } ) } /> <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={ __( '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={ __( '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 always preloads after you apply the URL.', 'wp-asciiplayer' ) } checked={ preload } onChange={ ( value ) => setAttributes( { preload: 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={ __( '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 ) } ) } /> <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>
@@ -57,28 +133,38 @@ export default function Edit( { attributes, setAttributes } ) {
{ label: __( 'Hide', 'wp-asciiplayer' ), value: 'never' }, { label: __( 'Hide', 'wp-asciiplayer' ), value: 'never' },
] } onChange={ ( value ) => setAttributes( { controls: value } ) } /> ] } 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={ __( '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> } { attributes.legacyStyle && <p>{ __( 'The custom container style from your shortcode is preserved on the published page.', 'wp-asciiplayer' ) }</p> }
</PanelBody> </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> </InspectorControls>
<div { ...blockProps }> <div { ...blockProps }>
<div className="asciiplayer-editor__source"> <div className="asciiplayer-editor__source">
<form onSubmit={ applySource }> <form onSubmit={ applySource }>
<TextControl label={ __( 'Recording URL', 'wp-asciiplayer' ) } placeholder="https://example.com/recording.cast" value={ draftSource } onChange={ ( value ) => { setDraftSource( value ); setUrlError( false ); } } autoComplete="off" /> <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> <Button type="submit" variant="primary">{ __( 'Apply URL', 'wp-asciiplayer' ) }</Button>
</form> </form>
<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> <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> } { urlError && <Notice status="error" isDismissible={ false }>{ __( 'Enter an HTTP(S) recording URL or a path starting with a single /.', 'wp-asciiplayer' ) }</Notice> }
</div> </div>
{ approvedSource && approvedSource === source ? ( <figure className={ `asciiplayer-figure asciiplayer-align-${ placement }` } style={ { width: normalizeWidth( width ) } }>
<div style={ { width: normalizeWidth( width ), maxWidth: '100%' } }> { showPreview ? (
<Preview source={ source } attributes={ attributes } attempt={ attempt } onRetry={ () => setAttempt( ( current ) => current + 1 ) } /> <>
</div> <Preview source={ previewSource } attributes={ attributes } attempt={ attempt } onRecordingSize={ onRecordingSize } onRetry={ () => setAttempt( ( current ) => current + 1 ) } />
</>
) : ( ) : (
<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' ) }> <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' ) } />
{ source && <Button variant="secondary" onClick={ () => { setApprovedSource( source ); setAttempt( ( current ) => current + 1 ); } }>{ __( 'Load preview', 'wp-asciiplayer' ) }</Button> }
</Placeholder>
) } ) }
<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> </div>
</> </>
); );
+25
View File
@@ -1,4 +1,5 @@
.asciiplayer-editor { .asciiplayer-editor {
box-sizing: border-box;
border: 1px solid #ddd; border: 1px solid #ddd;
border-radius: 4px; border-radius: 4px;
padding: 16px; padding: 16px;
@@ -30,10 +31,12 @@
margin-top: 16px; margin-top: 16px;
} }
/*! rtl:begin:ignore */
.asciiplayer-editor__player { .asciiplayer-editor__player {
min-width: 0; min-width: 0;
text-align: left; text-align: left;
} }
/*! rtl:end:ignore */
.asciiplayer-editor__status { .asciiplayer-editor__status {
display: flex; display: flex;
@@ -48,3 +51,25 @@
flex-direction: column; 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; }
+4
View File
@@ -2,6 +2,7 @@ import { createBlock, registerBlockType } from '@wordpress/blocks';
import { next } from '@wordpress/shortcode'; import { next } from '@wordpress/shortcode';
import { decodeEntities } from '@wordpress/html-entities'; import { decodeEntities } from '@wordpress/html-entities';
import metadata from '../block.json'; import metadata from '../block.json';
import { _x } from '@wordpress/i18n';
import Edit from './edit.js'; import Edit from './edit.js';
import { attributesFromShortcode, canTransformShortcode, normalizeSource } from './options.js'; import { attributesFromShortcode, canTransformShortcode, normalizeSource } from './options.js';
import './style.css'; import './style.css';
@@ -14,6 +15,9 @@ function matchShortcodeBlock( text = '' ) {
registerBlockType( metadata.name, { registerBlockType( metadata.name, {
...metadata, ...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, edit: Edit,
save: () => null, save: () => null,
transforms: { transforms: {
+10
View File
@@ -39,6 +39,16 @@ export function normalizeWidth( value ) {
? value.trim() : DEFAULTS.width; ? 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. */ /** A bounded editor frame for old height-fitting shortcodes; never persisted. */
export function previewHeight( attributes ) { export function previewHeight( attributes ) {
if ( ! [ 'height', 'both' ].includes( attributes.fit ) ) return undefined; if ( ! [ 'height', 'both' ].includes( attributes.fit ) ) return undefined;
+27 -7
View File
@@ -1,39 +1,61 @@
import { Button, Notice, Spinner } from '@wordpress/components'; import { Button, Notice, Spinner } from '@wordpress/components';
import { useRefEffect } from '@wordpress/compose'; import { useRefEffect } from '@wordpress/compose';
import { useState } from '@wordpress/element'; import { useRef, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n'; import { __ } from '@wordpress/i18n';
import { normalizePlayerOptions, previewHeight } from './options.js'; import { normalizePlayerOptions, previewHeight } from './options.js';
import { playerAssets, playerForDocument } from './player-bridge.js'; import { playerAssets, playerForDocument } from './player-bridge.js';
import { readRecordingSize } from './recording-metadata.js';
export default function Preview( { source, attributes, attempt, onRetry } ) { export default function Preview( { source, attributes, attempt, onRetry, onRecordingSize } ) {
const [ status, setStatus ] = useState( 'loading' ); const [ status, setStatus ] = useState( 'loading' );
const [ problem, setProblem ] = useState( '' ); const [ problem, setProblem ] = useState( '' );
const onRecordingSizeRef = useRef( onRecordingSize );
onRecordingSizeRef.current = onRecordingSize;
const optionsJSON = JSON.stringify( normalizePlayerOptions( attributes, { preview: true } ) ); const optionsJSON = JSON.stringify( normalizePlayerOptions( attributes, { preview: true } ) );
const playerRef = useRefEffect( ( container ) => { const playerRef = useRefEffect( ( container ) => {
let disposed = false; let disposed = false;
let failed = false;
let player; let player;
let readinessTimer; let readinessTimer;
let deadline; let deadline;
const canvasWindow = container.ownerDocument.defaultView; const canvasWindow = container.ownerDocument.defaultView;
const request = new canvasWindow.AbortController(); const request = new canvasWindow.AbortController();
const reportSize = ( size ) => {
if ( ! disposed ) onRecordingSizeRef.current?.( source, size );
};
setStatus( 'loading' ); setStatus( 'loading' );
setProblem( '' ); setProblem( '' );
reportSize( null );
const fail = ( message ) => { const fail = ( message ) => {
if ( disposed ) return; if ( disposed || failed ) return;
failed = true;
request.abort();
canvasWindow.clearInterval( readinessTimer ); canvasWindow.clearInterval( readinessTimer );
canvasWindow.clearTimeout( deadline ); canvasWindow.clearTimeout( deadline );
reportSize( null );
setProblem( message ); setProblem( message );
setStatus( 'error' ); setStatus( 'error' );
}; };
const ready = () => { const ready = () => {
if ( disposed ) return; if ( disposed || failed ) return;
canvasWindow.clearInterval( readinessTimer ); canvasWindow.clearInterval( readinessTimer );
canvasWindow.clearTimeout( deadline ); canvasWindow.clearTimeout( deadline );
setStatus( 'ready' ); setStatus( 'ready' );
}; };
playerForDocument( container.ownerDocument, playerAssets() ).then( ( api ) => { playerForDocument( container.ownerDocument, playerAssets() ).then( ( api ) => {
if ( disposed ) return; if ( disposed ) return;
player = api.create( { url: source, fetchOpts: { signal: request.signal } }, container, JSON.parse( optionsJSON ) ); 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( '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 ); player.addEventListener( 'playing', ready );
// getDuration is public API; a mounted wrapper alone does not mean the // getDuration is public API; a mounted wrapper alone does not mean the
@@ -61,8 +83,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 === '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> } { 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 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> </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( () => {} );
}
}
+63 -1
View File
@@ -1,15 +1,77 @@
.wp-block-lamgc-asciiplayer,
.asciiplayer-container { .asciiplayer-container {
box-sizing: border-box; box-sizing: border-box;
max-width: 100%; max-width: 100%;
margin-inline: auto; margin-inline: auto;
} }
/*! rtl:begin:ignore */
.asciiplayer-container .ap-wrapper { .asciiplayer-container .ap-wrapper {
text-align: left; text-align: left;
} }
/*! rtl:end:ignore */
.asciiplayer-container[data-ap-status="error"] .asciiplayer-error { .asciiplayer-container[data-ap-status="error"] .asciiplayer-error {
padding: 1em; padding: 1em;
border: 1px solid #b32d2e; 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;
}
+40 -2
View File
@@ -13,8 +13,12 @@ npm ci
npm run build npm run build
npm test npm test
npm run package npm run package
mkdir -p .wp-env-uploads
npm run wp-env -- start npm run wp-env -- start
npm run wp-env -- run cli wp plugin install /var/www/html/wp-content/asciiplayer-packages/wp-asciiplayer.zip --activate --force npm run wp-env -- run cli wp plugin install /var/www/html/wp-content/asciiplayer-packages/wp-asciiplayer.zip --activate --force
npm run wp-env -- run cli wp language core install zh_CN
npm run wp-env -- run cli wp site switch-language en_US
npm run wp-env -- run cli wp user meta update admin locale en_US
npx --no-install playwright install chromium npx --no-install playwright install chromium
npm run test:e2e npm run test:e2e
npm run wp-env -- stop npm run wp-env -- stop
@@ -29,6 +33,8 @@ The plugin's source tree is deliberately not mounted as an active plugin in the
committed wp-env configuration. The build ZIP is installed into WordPress through committed wp-env configuration. The build ZIP is installed into WordPress through
WP-CLI, so missing package files cause a real integration failure. Fixtures are WP-CLI, so missing package files cause a real integration failure. Fixtures are
mapped under uploads; the package directory is mapped separately for WP-CLI. mapped under uploads; the package directory is mapped separately for WP-CLI.
The host-owned .wp-env-uploads directory keeps real Media Library uploads writable
without relaxing file modes or modifying the fixture files.
## Coverage ## Coverage
@@ -42,8 +48,22 @@ mapped under uploads; the package directory is mapped separately for WP-CLI.
- Actual terminal output proves successful front-end parsing/playback - Actual terminal output proves successful front-end parsing/playback
- Editor and front-end requests must not load plugin assets from jsDelivr - Editor and front-end requests must not load plugin assets from jsDelivr
The preview intentionally requires an Apply URL / Load preview action for each The preview automatically loads valid saved URLs and debounces typed changes.
editing session before contacting the recording server. Tests respect that gate. Tests check the request count, stale-response cleanup, immediate Apply, error
retry, and no requests for empty/invalid URLs or static inserter examples.
Floating-toolbar dimension controls are checked against the collapsed sidebar,
including keyboard focus, Escape/close/reopen, and shared attribute values.
Both controls show the recording header's native columns and rows as placeholders
without saving overrides. URL replacement, pending/error/invalid sources and late
responses cover metadata cleanup; recorded resize events still control blank axes.
Pretty-printed v1 and comment-bearing v3 fixtures also exercise actual parsing,
native-size placeholders and playback output, alongside the existing v2 fixtures.
Media Library tests use WordPress's real upload dialog, file input and attachment
tiles. They upload a valid `.cast`, select and play it without Apply URL, cancel a
replacement, reopen to select the existing replacement, and reload the saved URL.
A malformed `.cast` must be rejected by the real upload endpoint and shown as an
upload error. These tests create small attachments in the isolated wp-env database.
## CI evidence and limits ## CI evidence and limits
@@ -65,3 +85,21 @@ References:
- https://developer.wordpress.org/block-editor/reference-guides/packages/packages-env/ - https://developer.wordpress.org/block-editor/reference-guides/packages/packages-env/
- https://developer.wordpress.org/block-editor/reference-guides/block-api/block-api-versions/block-migration-for-iframe-editor-compatibility/ - https://developer.wordpress.org/block-editor/reference-guides/block-api/block-api-versions/block-migration-for-iframe-editor-compatibility/
- https://github.com/WordPress/plugin-check/blob/trunk/docs/CLI.md - https://github.com/WordPress/plugin-check/blob/trunk/docs/CLI.md
Native recording-size hints are checked against v1/v2/v3 headers, explicit
overrides, URL replacement, error/empty states and recorded resize events.
The Media Library tests use actual isolated WordPress upload dialogs to upload
validated fixtures, reject malformed casts, cancel/reopen and select an existing
recording. No production-site media is accessed.
## Plugin localization
Five `@i18n` cases set real site and user languages via the authenticated WordPress
REST API, covering all en_US/zh_CN combinations and site-default inheritance.
They verify bundled PHP upload errors, editor metadata and controls, recoverable
preview errors, and logged-in/anonymous frontend messages. Author captions and
actual recording content remain unchanged, and upstream player controls stay
English. Original site/user locale values are restored after each test.
Run these only against the isolated test site, with zh_CN installed first.
CI runs the existing English suite before the locale suite and retains separate
reports/screenshots. No catalog data is injected into the browser by the tests.
+207 -11
View File
@@ -53,13 +53,6 @@ async function readyPreview(block) {
await expect(block.locator('.ap-wrapper')).toBeVisible(); await expect(block.locator('.ap-wrapper')).toBeVisible();
} }
async function loadPreview(block) {
await expect(block).toBeVisible();
const load = block.getByRole('button', { name: 'Load preview', exact: true });
if (await load.count()) await load.click();
await readyPreview(block);
}
async function publish(page, title) { async function publish(page, title) {
return page.evaluate(async (postTitle) => { return page.evaluate(async (postTitle) => {
const editor = window.wp.data.dispatch('core/editor'); const editor = window.wp.data.dispatch('core/editor');
@@ -145,12 +138,12 @@ test('real iframe preview survives edits, duplicate, delete, undo, save and relo
await window.wp.data.dispatch('core/block-editor').duplicateBlocks([clientId]); await window.wp.data.dispatch('core/block-editor').duplicateBlocks([clientId]);
return window.wp.data.select('core/block-editor').getBlocks().find((entry) => entry.name === 'lamgc/asciiplayer' && entry.clientId !== clientId).clientId; return window.wp.data.select('core/block-editor').getBlocks().find((entry) => entry.name === 'lamgc/asciiplayer' && entry.clientId !== clientId).clientId;
}, id); }, id);
await loadPreview(playerBlock(page, duplicateId)); await readyPreview(playerBlock(page, duplicateId));
await expect(canvas(page).locator('.asciiplayer-editor__player .ap-wrapper')).toHaveCount(2); await expect(canvas(page).locator('.asciiplayer-editor__player .ap-wrapper')).toHaveCount(2);
await page.evaluate((clientId) => window.wp.data.dispatch('core/block-editor').removeBlocks([clientId]), duplicateId); await page.evaluate((clientId) => window.wp.data.dispatch('core/block-editor').removeBlocks([clientId]), duplicateId);
await expect(canvas(page).locator('.asciiplayer-editor__player .ap-wrapper')).toHaveCount(1); await expect(canvas(page).locator('.asciiplayer-editor__player .ap-wrapper')).toHaveCount(1);
await page.evaluate(() => window.wp.data.dispatch('core/editor').undo()); await page.evaluate(() => window.wp.data.dispatch('core/editor').undo());
await loadPreview(playerBlock(page, duplicateId)); await readyPreview(playerBlock(page, duplicateId));
await expect(canvas(page).locator('.asciiplayer-editor__player .ap-wrapper')).toHaveCount(2); await expect(canvas(page).locator('.asciiplayer-editor__player .ap-wrapper')).toHaveCount(2);
await page.evaluate((clientId) => window.wp.data.dispatch('core/block-editor').removeBlocks([clientId]), duplicateId); await page.evaluate((clientId) => window.wp.data.dispatch('core/block-editor').removeBlocks([clientId]), duplicateId);
@@ -161,7 +154,7 @@ test('real iframe preview survives edits, duplicate, delete, undo, save and relo
const reloaded = await page.evaluate(() => window.wp.data.select('core/block-editor').getBlocks().find((entry) => entry.name === 'lamgc/asciiplayer')); const reloaded = await page.evaluate(() => window.wp.data.select('core/block-editor').getBlocks().find((entry) => entry.name === 'lamgc/asciiplayer'));
expect(reloaded.name).toBe(blockName); expect(reloaded.name).toBe(blockName);
expect(reloaded.attributes).toMatchObject({ source, speed: 1.5, theme: 'solarized-dark' }); expect(reloaded.attributes).toMatchObject({ source, speed: 1.5, theme: 'solarized-dark' });
await loadPreview(playerBlock(page, reloaded.clientId)); await readyPreview(playerBlock(page, reloaded.clientId));
await page.goto(saved.url); await page.goto(saved.url);
const container = page.locator('.asciiplayer-container'); const container = page.locator('.asciiplayer-container');
@@ -177,7 +170,7 @@ test('a published Page plays its block at desktop and mobile widths', async ({ p
await openEditor(page, 'page'); await openEditor(page, 'page');
const source = new URL(fixturePath, page.url()).href; const source = new URL(fixturePath, page.url()).href;
const id = await insertPlayer(page, { source, controls: 'always', preload: true }); const id = await insertPlayer(page, { source, controls: 'always', preload: true });
await loadPreview(playerBlock(page, id)); await readyPreview(playerBlock(page, id));
const saved = await publish(page, 'Page playback integration'); const saved = await publish(page, 'Page playback integration');
await page.goto(saved.url); await page.goto(saved.url);
const container = page.locator('.asciiplayer-container'); const container = page.locator('.asciiplayer-container');
@@ -259,3 +252,206 @@ test('a real cross-origin server without CORS permission shows an error and reco
await new Promise((resolve) => server.close(resolve)); await new Promise((resolve) => server.close(resolve));
} }
}); });
test('a saved Recording URL loads once without a click and never autoplays in the editor', async ({ page }) => {
await openEditor(page);
const source = new URL(`${fixturePath}?automatic=saved`, page.url()).href;
const recording = await readFile(new URL('../fixtures/hello.cast', import.meta.url));
const requests = [];
await page.route(source, async (route) => {
requests.push(route.request().url());
await route.fulfill({ contentType: 'text/plain', body: recording });
});
const id = await insertPlayer(page, { source, autoPlay: true, preload: false });
const block = playerBlock(page, id);
await readyPreview(block);
await expect(block.getByRole('button', { name: 'Load preview', exact: true })).toHaveCount(0);
await expect(block.locator('.ap-overlay-start .ap-play-button')).toBeVisible();
await expect(block.locator('.asciiplayer-editor__privacy')).toHaveCount(0);
await expect(block.locator(':scope > .asciiplayer-editor__hint')).toHaveCount(0);
await expect(block.getByRole('textbox', { name: 'Recording URL', exact: true })).toBeVisible();
await expect(block.getByRole('button', { name: 'Choose recording', exact: true })).toBeVisible();
await expect(block.locator('figcaption[contenteditable="true"]')).toBeVisible();
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
const helpToggle = page.locator('.components-panel__body-toggle').filter({ hasText: /^Help$/ });
await expect(helpToggle).toHaveAttribute('aria-expanded', 'false');
await helpToggle.click();
const help = page.locator('.components-panel__body').filter({ has: helpToggle });
await expect(help.locator('.asciiplayer-editor__privacy')).toContainText(/automatic/i);
await expect(help.locator('.asciiplayer-editor__privacy')).toContainText(/server/i);
await expect(help).toContainText('Use the player controls to play, pause, and seek.');
await helpToggle.click();
await expect(helpToggle).toHaveAttribute('aria-expanded', 'false');
await page.waitForTimeout(750); // Catch a second fetch from a pending debounce.
expect(requests).toEqual([source]);
await expect(block.locator('.ap-overlay-start .ap-play-button')).toBeVisible();
});
test('rapid URL edits debounce to one recording fetch and Apply cancels its pending debounce', async ({ page }) => {
await openEditor(page);
const prefix = new URL(`${fixturePath}?automatic=`, page.url()).href;
const recording = await readFile(new URL('../fixtures/hello.cast', import.meta.url));
const requests = [];
await page.route(`${prefix}*`, async (route) => {
requests.push(route.request().url());
await route.fulfill({ contentType: 'text/plain', body: recording });
});
const id = await insertPlayer(page);
const block = playerBlock(page, id);
const input = block.getByRole('textbox', { name: 'Recording URL', exact: true });
await input.fill(`${prefix}first`);
await input.fill(`${prefix}second`);
await input.fill(`${prefix}final`);
await readyPreview(block);
await page.waitForTimeout(750);
expect(requests).toEqual([`${prefix}final`]);
await expect.poll(() => page.evaluate((clientId) =>
window.wp.data.select('core/block-editor').getBlockAttributes(clientId).source, id
)).toBe(`${prefix}final`);
await input.fill(`${prefix}applied`);
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
await expect.poll(() => requests).toEqual([`${prefix}final`, `${prefix}applied`]);
await readyPreview(block);
await page.waitForTimeout(750);
expect(requests).toEqual([`${prefix}final`, `${prefix}applied`]);
});
test('replacing a pending recording ignores its stale response', async ({ page }) => {
await openEditor(page);
const source = new URL(`${fixturePath}?automatic=stale`, page.url()).href;
const latest = new URL(`${fixturePath}?automatic=latest`, page.url()).href;
const recording = await readFile(new URL('../fixtures/hello.cast', import.meta.url), 'utf8');
let release;
const pending = new Promise((resolve) => { release = resolve; });
let oldRequested = false;
let oldResponseSettled = false;
await page.route(source, async (route) => {
oldRequested = true;
await pending;
// Aborting a replaced player may cancel this intercepted request. Both
// cancellation and safely ignoring a late response are valid outcomes.
await route.fulfill({ contentType: 'text/plain', body: recording.replace('"width":64', '"width":120') }).catch(() => {});
oldResponseSettled = true;
});
await page.route(latest, (route) => route.fulfill({ contentType: 'text/plain', body: recording }));
try {
const id = await insertPlayer(page, { source });
const block = playerBlock(page, id);
await expect.poll(() => oldRequested).toBe(true);
await block.getByRole('textbox', { name: 'Recording URL', exact: true }).fill(latest);
await expect.poll(() => page.evaluate((clientId) =>
window.wp.data.select('core/block-editor').getBlockAttributes(clientId).source, id
)).toBe(latest);
await readyPreview(block);
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
const columns = page.getByRole('spinbutton', { name: 'Columns', exact: true });
const rows = page.getByRole('spinbutton', { name: 'Rows', exact: true });
if (!await columns.isVisible()) {
await page.locator('.components-panel__body-toggle').filter({ hasText: /^Terminal size$/ }).click();
}
await expect(columns).toHaveAttribute('placeholder', '64');
await expect(rows).toHaveAttribute('placeholder', '12');
release();
await expect.poll(() => oldResponseSettled).toBe(true);
await page.waitForTimeout(750);
await readyPreview(block);
await expect.poll(() => block.locator('.ap-term').evaluate((terminal) =>
Number(terminal.style.getPropertyValue('--term-cols'))
)).toBe(64);
// A late header from the old 120-column cast must not become a hint.
await expect(columns).toHaveAttribute('placeholder', '64');
await expect(rows).toHaveAttribute('placeholder', '12');
await expect(columns).toHaveValue('');
await expect(rows).toHaveValue('');
await expect(block.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveValue(latest);
} finally {
release();
}
});
test('automatic preview errors retry the unchanged URL through Retry preview and Apply URL', async ({ page }) => {
await openEditor(page);
const source = new URL(`${fixturePath}?automatic=retry`, page.url()).href;
const recording = await readFile(new URL('../fixtures/hello.cast', import.meta.url));
let requests = 0;
await page.route(source, async (route) => {
requests += 1;
await route.fulfill(requests < 3
? { status: 503, contentType: 'text/plain', body: 'Temporarily unavailable' }
: { contentType: 'text/plain', body: recording });
});
const id = await insertPlayer(page, { source });
const block = playerBlock(page, id);
const preview = block.locator('.asciiplayer-editor__preview');
await expect(preview).toHaveAttribute('data-preview-status', 'error');
expect(requests).toBe(1);
await block.getByRole('button', { name: 'Retry preview', exact: true }).click();
await expect.poll(() => requests).toBe(2);
await expect(preview).toHaveAttribute('data-preview-status', 'error');
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
await readyPreview(block);
await page.waitForTimeout(750);
expect(requests).toBe(3);
});
test('empty and invalid sources never create a preview or fetch a recording', async ({ page }) => {
await openEditor(page);
const requests = [];
page.on('request', (request) => {
if (/\.cast(?:[?#]|$)|asciinema\.org|jsdelivr\.net/.test(request.url())) requests.push(request.url());
});
const emptyId = await insertPlayer(page);
const empty = playerBlock(page, emptyId);
const invalidId = await insertPlayer(page, { source: 'javascript:alert(1)' });
const invalid = playerBlock(page, invalidId);
await expect(empty.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveValue('');
await expect(invalid.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveValue('javascript:alert(1)');
await page.waitForTimeout(750);
await expect(empty.locator('.asciiplayer-editor__preview')).toHaveCount(0);
await expect(invalid.locator('.asciiplayer-editor__preview')).toHaveCount(0);
const input = empty.getByRole('textbox', { name: 'Recording URL', exact: true });
await input.fill(new URL(fixturePath, page.url()).href);
await input.fill('');
await page.waitForTimeout(750);
await expect(empty.locator('.asciiplayer-editor__preview')).toHaveCount(0);
await input.fill('https://');
await page.waitForTimeout(750);
await expect(empty.locator('.asciiplayer-editor__preview')).toHaveCount(0);
expect(requests).toEqual([]);
});
test('external source changes and undo clear an invalid draft error and restore the valid preview', async ({ page }) => {
await openEditor(page);
const original = new URL(`${fixturePath}?automatic=undo-original`, page.url()).href;
const replacement = new URL(`${fixturePath}?automatic=undo-replacement`, page.url()).href;
const id = await insertPlayer(page, { source: original });
const block = playerBlock(page, id);
const input = block.getByRole('textbox', { name: 'Recording URL', exact: true });
const validation = block.locator('.asciiplayer-editor__source .components-notice');
await readyPreview(block);
// Save a baseline so Undo below targets the external source replacement,
// rather than an insertion or another edit batched into the same history.
await publish(page, 'Automatic preview source synchronization regression');
await input.fill('https://');
await expect(validation).toContainText('Enter an HTTP(S) recording URL');
await expect(block.locator('.asciiplayer-editor__preview')).toHaveCount(0);
await page.evaluate(({ clientId, source }) =>
window.wp.data.dispatch('core/block-editor').updateBlockAttributes(clientId, { source }),
{ clientId: id, source: replacement });
await expect(input).toHaveValue(replacement);
await readyPreview(block);
await expect(validation).toHaveCount(0);
// An invalid local draft does not change the saved source or undo history.
await input.fill('javascript:alert(1)');
await expect(validation).toContainText('Enter an HTTP(S) recording URL');
await expect(block.locator('.asciiplayer-editor__preview')).toHaveCount(0);
await page.evaluate(() => window.wp.data.dispatch('core/editor').undo());
await expect(input).toHaveValue(original);
await readyPreview(block);
await expect(validation).toHaveCount(0);
await page.waitForTimeout(750); // A canceled invalid-draft timer cannot reappear.
await expect(validation).toHaveCount(0);
await expect.poll(() => page.evaluate((clientId) =>
window.wp.data.select('core/block-editor').getBlockAttributes(clientId).source, id
)).toBe(original);
});
+218
View File
@@ -0,0 +1,218 @@
import { test as base, expect } from '@playwright/test';
import { readFile } from 'node:fs/promises';
const blockName = 'lamgc/asciiplayer';
const fixturePath = '/wp-content/uploads/asciiplayer-fixtures';
const copy = {
en_US: {
title: 'Asciicast Player', source: 'Recording URL', apply: 'Apply URL',
choose: 'Choose recording', dimensions: 'Terminal size', columns: 'Columns', rows: 'Rows',
help: 'Help', retry: 'Retry preview', captionLabel: 'Recording caption',
previewError: 'Unable to load the recording. Check the URL, file format, and the source server’s CORS permissions.',
frontendError: 'Unable to load this terminal recording. The file may be unavailable, invalid, or blocked by the source server’s CORS policy.',
uploadError: 'Upload a valid Asciicast v2/v3 JSONL or pretty-printed v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, and 1,000 columns or rows).',
},
zh_CN: {
title: 'Asciicast 播放器', source: '录制文件 URL', apply: '应用 URL',
choose: '选择录制文件', dimensions: '终端尺寸', columns: '列数', rows: '行数',
help: '帮助', retry: '重试预览', captionLabel: '录屏说明文字',
previewError: '无法加载录制文件。请检查 URL、文件格式及来源服务器的跨域请求(CORS)权限。',
frontendError: '无法加载此终端录屏。文件可能无法访问、格式无效,或被来源服务器的跨域请求(CORS)策略阻止。',
uploadError: '请上传有效的 Asciicast v2/v3 JSONL 或格式化的 v1 .cast 录制文件(最大 32 MiB;v1 最大 2 MiB;最多 100,000 个事件;每行 JSONL最大 256 KiB;列数和行数均不超过 1,000)。',
},
};
async function login(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\//);
}
async function openEditor(page) {
await page.goto('/wp-admin/post-new.php');
await page.waitForFunction((name) => Boolean(
window.wp?.apiFetch && 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();
}
// Change actual WordPress settings, never navigator.language or wp.i18n mocks.
// Keep an authenticated control page alive so cleanup also works if a test
// finishes on the public site or fails during a player/media interaction.
const test = base.extend({
localeSession: async ({ context }, use) => {
const control = await context.newPage();
await login(control);
await control.goto('/wp-admin/profile.php');
const language = control.locator('#locale');
await expect(language, 'Install the zh_CN core language pack before this suite.').toBeVisible();
await expect(language.locator('option[value="zh_CN"]')).toHaveCount(1);
const selectedUserLocale = await language.inputValue();
const originalUserLocale = selectedUserLocale === 'site-default' ? '' : selectedUserLocale;
await openEditor(control);
const originalSiteLocale = await control.evaluate(async () =>
(await window.wp.apiFetch({ path: '/wp/v2/settings' })).language
);
const setLocales = async (siteLocale, userLocale) => control.evaluate(async ({ site, user }) => {
const settings = await window.wp.apiFetch({ path: '/wp/v2/settings', method: 'POST', data: { language: site } });
const currentUser = await window.wp.apiFetch({ path: '/wp/v2/users/me', method: 'POST', data: { locale: user } });
return { site: settings.language || 'en_US', user: currentUser.locale };
}, { site: siteLocale, user: userLocale });
try {
await use({ setLocales, control });
} finally {
await setLocales(originalSiteLocale, originalUserLocale);
await control.close();
}
},
});
async function insertPlayer(page) {
const id = await page.evaluate((name) => {
const block = window.wp.blocks.createBlock(name, { controls: 'always' });
window.wp.data.dispatch('core/block-editor').insertBlocks(block);
window.wp.data.dispatch('core/block-editor').selectBlock(block.clientId);
return block.clientId;
}, blockName);
return page.frameLocator('iframe[name="editor-canvas"]').locator(`[data-block="${id}"]`);
}
async function assertTranslatedError(locator, locale, kind) {
// Expected strings are independent literals, never read from the loaded
// catalog: a missing translation must fail instead of defining expectations.
await expect(locator).toHaveText(copy[locale][kind]);
}
async function rejectInvalidUpload(page, block, locale, testInfo) {
await block.getByRole('button', { name: copy[locale].choose, exact: true }).click();
const dialog = page.locator('.media-modal[role="dialog"]');
await expect(dialog).toBeVisible();
await dialog.locator('#menu-item-upload').click();
const input = page.locator('.moxie-shim input[type="file"]').last();
await expect(input).toBeAttached();
const response = page.waitForResponse((result) =>
/\/wp-admin\/async-upload\.php(?:\?|$)/.test(result.url()) && result.request().method() === 'POST'
);
await input.setInputFiles({
name: `asciiplayer-locale-invalid-${Date.now()}-${testInfo.retry}.cast`,
mimeType: 'application/x-asciicast',
buffer: await readFile(new URL('../fixtures/malformed.cast', import.meta.url)),
});
const result = await (await response).json();
expect(result.success, JSON.stringify(result)).toBe(false);
expect(result.data.message).toBe(copy[locale].uploadError);
await expect(dialog).toContainText(result.data.message);
await expect(dialog.locator('.media-button-select')).toBeDisabled();
await dialog.locator('.media-modal-close').click();
}
async function verifyFrontend(page, url, locale) {
await page.goto(url);
await expect(page.locator('html')).toHaveAttribute('lang', locale === 'zh_CN' ? /^zh-(CN|Hans)$/ : 'en-US');
const players = page.locator('.asciiplayer-container');
await expect(players).toHaveCount(3);
await assertTranslatedError(players.nth(1).locator('.asciiplayer-error'), locale, 'frontendError');
for (const index of [0, 2]) {
const player = players.nth(index);
await expect(player.locator('.ap-wrapper')).toBeVisible();
await player.locator('.ap-overlay-start .ap-play-button').click();
await expect(player.locator('.ap-term-text')).toContainText('Hello from wp-asciiplayer');
}
await expect(page.locator('.asciiplayer-figure figcaption')).toHaveText('Author caption / 作者说明');
}
test.describe('@i18n real WordPress site and user locales', () => {
// Locale is site-global. The repository config has one worker; do not run
// these cases concurrently against a shared WordPress database.
test.describe.configure({ mode: 'default' });
for (const [siteLocale, userLocale] of [
['en_US', 'en_US'], ['zh_CN', 'zh_CN'],
['zh_CN', 'en_US'], ['en_US', 'zh_CN'],
]) {
test(`site ${siteLocale}, user ${userLocale}: editor, PHP upload and public player`, async ({ page, browser, localeSession }, testInfo) => {
test.setTimeout(150_000);
const locales = await localeSession.setLocales(siteLocale, userLocale);
expect(locales).toEqual({ site: siteLocale, user: userLocale });
const ui = copy[userLocale];
const pageErrors = [];
page.on('pageerror', (error) => pageErrors.push(error.message));
await openEditor(page);
await expect(page.locator('html')).toHaveAttribute('lang', userLocale === 'zh_CN' ? /^zh-(CN|Hans)$/ : 'en-US');
expect(await page.evaluate((name) => window.wp.blocks.getBlockType(name).title, blockName)).toBe(ui.title);
const block = await insertPlayer(page);
const source = block.getByRole('textbox', { name: ui.source, exact: true });
await expect(source).toBeVisible();
await expect(block.getByRole('button', { name: ui.apply, exact: true })).toBeVisible();
await expect(block.getByRole('button', { name: ui.choose, exact: true })).toBeVisible();
await expect(block.locator('figcaption[contenteditable="true"]')).toHaveAttribute('aria-label', ui.captionLabel);
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
await page.locator('.components-panel__body-toggle').filter({ hasText: new RegExp(`^${ui.dimensions}$`) }).click();
await expect(page.getByRole('spinbutton', { name: ui.columns, exact: true })).toBeVisible();
await expect(page.getByRole('spinbutton', { name: ui.rows, exact: true })).toBeVisible();
await expect(page.locator('.components-panel__body-toggle').filter({ hasText: new RegExp(`^${ui.help}$`) })).toBeVisible();
const valid = new URL(`${fixturePath}/hello.cast`, page.url()).href;
const missing = new URL(`${fixturePath}/missing-i18n.cast`, page.url()).href;
await source.fill(missing);
await block.getByRole('button', { name: ui.apply, exact: true }).click();
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'error');
await assertTranslatedError(block.locator('.components-notice__content > p'), userLocale, 'previewError');
await expect(block.getByRole('button', { name: ui.retry, exact: true })).toBeVisible();
await source.fill(valid);
await block.getByRole('button', { name: ui.apply, exact: true }).click();
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready');
await block.locator('.ap-overlay-start .ap-play-button').click();
await expect(block.locator('.ap-term-text')).toContainText('Hello from wp-asciiplayer');
// Upstream 3.17.0 has no localization API. Its unmodified controls
// deliberately retain their English accessibility labels in both locales.
await expect(block.locator('.ap-playback-button')).toHaveAttribute('aria-label', 'Pause');
await block.locator('.ap-playback-button').click();
await expect(block.locator('.ap-playback-button')).toHaveAttribute('aria-label', 'Play');
await rejectInvalidUpload(page, block, userLocale, testInfo);
const editorShot = testInfo.outputPath(`editor-${siteLocale}-${userLocale}.png`);
await page.screenshot({ path: editorShot, fullPage: true });
await testInfo.attach('editor-locale', { path: editorShot, contentType: 'image/png' });
const saved = await page.evaluate(async ({ name, good, bad }) => {
const blockContent = window.wp.blocks.serialize(window.wp.blocks.createBlock(name, {
source: good, controls: 'always', preload: true, caption: 'Author caption / 作者说明',
}));
return window.wp.apiFetch({ path: '/wp/v2/posts', method: 'POST', data: {
title: `Asciiplayer locale integration ${Date.now()}`, status: 'publish',
content: `${blockContent}\n[asciiplayer preload="true"]${bad}[/asciiplayer]\n[asciiplayer preload="true"]${good}[/asciiplayer]`,
} });
}, { name: blockName, good: valid, bad: missing });
// A logged-in user's language must not leak into public frontend JS.
await verifyFrontend(page, saved.link, siteLocale);
const anonymous = await browser.newContext();
try {
const visitor = await anonymous.newPage();
visitor.on('pageerror', (error) => pageErrors.push(error.message));
await verifyFrontend(visitor, saved.link, siteLocale);
const frontendShot = testInfo.outputPath(`frontend-${siteLocale}-${userLocale}.png`);
await visitor.screenshot({ path: frontendShot, fullPage: true });
await testInfo.attach('frontend-locale', { path: frontendShot, contentType: 'image/png' });
} finally {
await anonymous.close();
}
expect(pageErrors).toEqual([]);
});
}
test('a user with the site default language inherits zh_CN in the editor', async ({ page, localeSession }) => {
expect(await localeSession.setLocales('zh_CN', '')).toEqual({ site: 'zh_CN', user: 'zh_CN' });
await openEditor(page);
expect(await page.evaluate((name) => window.wp.blocks.getBlockType(name).title, blockName)).toBe(copy.zh_CN.title);
const block = await insertPlayer(page);
await expect(block.getByRole('textbox', { name: copy.zh_CN.source, exact: true })).toBeVisible();
});
});
+548
View File
@@ -0,0 +1,548 @@
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 readyPreview(block) {
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.locator('.components-panel__body-toggle').filter({ hasText: new RegExp(`^${name}$`) }).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 readyPreview(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 readyPreview(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('toolbar terminal dimensions are discoverable, preserve focus and synchronize with the collapsed sidebar', async ({ page }, testInfo) => {
await openEditor(page);
const source = new URL(fixturePath, page.url()).href;
const { id, block } = await insertPlayer(page, { source });
await readyPreview(block);
await expect(block.getByRole('spinbutton', { name: 'Columns', exact: true })).toHaveCount(0);
await expect(block.getByRole('spinbutton', { name: 'Rows', exact: true })).toHaveCount(0);
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').closeGeneralSidebar());
// Core hides contextual tools while typing; mirror its own test utility.
await page.mouse.move(50, 50);
await page.mouse.move(75, 75);
await page.mouse.move(100, 100);
const toolbar = page.getByRole('toolbar', { name: 'Block tools', exact: true });
const toggle = toolbar.getByRole('button', { name: 'Terminal size', exact: true });
await expect(toggle).toBeVisible();
await block.scrollIntoViewIfNeeded();
await page.waitForTimeout(300); // Let the sidebar-close layout transition settle.
const before = await block.boundingBox();
await toggle.click();
const popover = page.getByRole('dialog', { name: 'Terminal size', exact: true });
const columns = popover.getByRole('spinbutton', { name: 'Columns', exact: true });
const rows = popover.getByRole('spinbutton', { name: 'Rows', exact: true });
await expect(popover).toBeVisible();
await expect(columns).toBeVisible();
await expect(rows).toBeVisible();
await expect(columns).toBeFocused();
await expect(columns).toHaveValue('');
await expect(rows).toHaveValue('');
await expect(columns).toHaveAttribute('placeholder', '64');
await expect(rows).toHaveAttribute('placeholder', '12');
expect((await attributes(page, id)).cols).toBeUndefined();
expect((await attributes(page, id)).rows).toBeUndefined();
const after = await block.boundingBox();
expect(Math.abs(after.width - before.width)).toBeLessThan(2);
expect(Math.abs(after.height - before.height)).toBeLessThan(2);
await screenshot(page, testInfo, 'terminal-size-toolbar-popover');
// Invalid overrides are cleared rather than changing the recording grid.
await columns.fill('0');
await columns.press('Tab');
await rows.fill('1001');
await rows.press('Tab');
await expect(columns).toHaveValue('');
await expect(rows).toHaveValue('');
expect((await attributes(page, id)).cols).toBeUndefined();
expect((await attributes(page, id)).rows).toBeUndefined();
await expectGrid(block, 64, 12);
await columns.fill('88');
await columns.press('Tab');
await rows.fill('16');
await rows.press('Tab');
await expectGrid(block, 88, 16);
await rows.press('Escape');
await expect(popover).toBeHidden();
await expect(toggle).toBeFocused();
await toggle.click();
await expect(columns).toHaveValue('88');
await expect(rows).toHaveValue('16');
// A manual override must not become the displayed recording metadata.
await expect(columns).toHaveAttribute('placeholder', '64');
await expect(rows).toHaveAttribute('placeholder', '12');
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 popover.getByRole('button', { name: 'Use recording size', exact: true }).click();
await expectGrid(block, 64, 12);
await expect(columns).toHaveValue('');
await expect(rows).toHaveValue('');
await columns.fill('88');
await rows.fill('16');
await rows.press('Tab');
await expectGrid(block, 88, 16);
await popover.getByRole('button', { name: 'Close', exact: true }).click();
await expect(popover).toBeHidden();
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
const panelToggle = page.locator('.components-panel__body-toggle').filter({ hasText: /^Terminal size$/ });
await expect(panelToggle).toHaveAttribute('aria-expanded', 'false');
await panelToggle.click();
const sidebarColumns = page.getByRole('spinbutton', { name: 'Columns', exact: true });
const sidebarRows = page.getByRole('spinbutton', { name: 'Rows', exact: true });
await expect(sidebarColumns).toHaveValue('88');
await expect(sidebarRows).toHaveValue('16');
await expect(sidebarColumns).toHaveAttribute('placeholder', '64');
await expect(sidebarRows).toHaveAttribute('placeholder', '12');
await sidebarRows.fill('');
await sidebarRows.press('Tab');
await expectGrid(block, 88, 12);
await page.getByRole('button', { name: 'Use recording size', exact: true }).click();
await expectGrid(block, 64, 12);
expect((await attributes(page, id)).cols).toBeUndefined();
expect((await attributes(page, id)).rows).toBeUndefined();
await toggle.click();
await expect(columns).toHaveValue('');
await expect(rows).toHaveValue('');
await expect(columns).toHaveAttribute('placeholder', '64');
await expect(rows).toHaveAttribute('placeholder', '12');
await popover.getByRole('button', { name: 'Close', exact: true }).click();
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 { id, block } = await insertPlayer(page, { source, startAt: 2, ...entry.overrides });
await readyPreview(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 columns = page.getByRole('spinbutton', { name: 'Columns', exact: true });
const rows = page.getByRole('spinbutton', { name: 'Rows', exact: true });
await openInspectorPanel(page, 'Terminal size', columns);
// Placeholders describe the cast header, even after its resize event.
await expect(columns).toHaveAttribute('placeholder', '64');
await expect(rows).toHaveAttribute('placeholder', '12');
expect((await attributes(page, id)).cols).toBe(entry.overrides.cols);
expect((await attributes(page, id)).rows).toBe(entry.overrides.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 &amp; 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());
});
// A saved URL must never turn an inserter example into a network preview.
const { block } = await insertPlayer(page, { ...example.attributes, source: new URL(fixturePath, page.url()).href });
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 page.waitForTimeout(750); // Exceed the automatic URL debounce window.
await screenshot(page, testInfo, 'static-inserter-example');
expect(recordingRequests).toEqual([]);
});
test('outer editor blocks respect WordPress content gutters and core wide/full boundaries', async ({ page }, testInfo) => {
await openEditor(page);
const source = new URL(fixturePath, page.url()).href;
const cases = await page.evaluate(({ name, sourceUrl }) => {
const { createBlock, getBlockType } = window.wp.blocks;
const paragraph = (text) => createBlock('core/paragraph', { content: text });
const before = paragraph('Paragraph before the player: the standard editor content boundary.');
const player = createBlock(name, { source: sourceUrl, width: '100%' });
const after = paragraph('Paragraph after the player: the same standard content boundary.');
const blocks = [before, player, after];
const entries = [{ alignment: 'default', playerId: player.clientId, referenceIds: [before.clientId, after.clientId] }];
const supportsAlignment = (block, align) => {
const support = getBlockType(block)?.supports?.align;
return support === true || Array.isArray(support) && support.includes(align);
};
for (const align of ['wide', 'full']) {
if (!supportsAlignment(name, align) || !supportsAlignment('core/group', align)) continue;
// Paragraphs do not support wide/full. A core Group supplies the
// native aligned boundary for its paragraph without custom sizing.
const reference = createBlock('core/group', { align, layout: { type: 'default' } }, [
paragraph(`${align} core Group paragraph: native WordPress alignment reference.`),
]);
const alignedPlayer = createBlock(name, { source: sourceUrl, width: '100%', align });
blocks.push(reference, alignedPlayer);
entries.push({ alignment: align, playerId: alignedPlayer.clientId, referenceIds: [reference.clientId] });
}
window.wp.data.dispatch('core/block-editor').insertBlocks(blocks);
window.wp.data.dispatch('core/block-editor').selectBlock(player.clientId);
return entries;
}, { name: blockName, sourceUrl: source });
const canvas = page.frameLocator('iframe[name="editor-canvas"]');
for (const entry of cases) await readyPreview(canvas.locator(`[data-block="${entry.playerId}"]`));
for (const viewport of [{ width: 1280, height: 900 }, { width: 390, height: 844 }]) {
await page.setViewportSize(viewport);
for (const entry of cases) {
const block = canvas.locator(`[data-block="${entry.playerId}"]`);
const measure = () => block.evaluate((element, referenceIds) => {
const document = element.ownerDocument;
const horizontal = (node) => {
const box = node.getBoundingClientRect();
return { left: box.left, right: box.right, width: box.width };
};
const outer = horizontal(element);
const references = referenceIds.map((id) => horizontal(document.querySelector(`[data-block="${id}"]`)));
const root = element.closest('.is-root-container');
if (!root) throw new Error('WordPress editor content root was not found.');
const rootBounds = horizontal(root);
const rootStyle = getComputedStyle(root);
const contentLeft = rootBounds.left + parseFloat(rootStyle.borderLeftWidth) + parseFloat(rootStyle.paddingLeft);
const contentRight = rootBounds.right - parseFloat(rootStyle.borderRightWidth) - parseFloat(rootStyle.paddingRight);
return {
outer, references, contentLeft, contentRight,
viewportWidth: document.documentElement.clientWidth,
leftError: Math.max(...references.map((reference) => Math.abs(outer.left - reference.left))),
rightError: Math.max(...references.map((reference) => Math.abs(outer.right - reference.right))),
player: horizontal(element.querySelector('.ap-wrapper')),
boxSizing: getComputedStyle(element).boxSizing,
};
}, entry.referenceIds);
// Compare the OUTER border box to independently rendered native
// blocks. Inner-figure/parent checks alone miss a 34px padding leak.
await expect.poll(async () => (await measure()).leftError).toBeLessThan(2);
await expect.poll(async () => (await measure()).rightError).toBeLessThan(2);
const geometry = await measure();
expect(geometry.boxSizing).toBe('border-box');
expect(geometry.outer.left).toBeGreaterThanOrEqual(-2);
expect(geometry.outer.right).toBeLessThanOrEqual(geometry.viewportWidth + 2);
if (entry.alignment === 'default') {
expect(geometry.outer.left).toBeGreaterThanOrEqual(geometry.contentLeft - 2);
expect(geometry.outer.right).toBeLessThanOrEqual(geometry.contentRight + 2);
expect(geometry.outer.left).toBeGreaterThan(0);
expect(geometry.outer.right).toBeLessThan(geometry.viewportWidth);
}
expect(geometry.player.left).toBeGreaterThanOrEqual(geometry.outer.left);
expect(geometry.player.right).toBeLessThanOrEqual(geometry.outer.right + 1);
await expectGrid(block, 64, 12);
await testInfo.attach(`editor-gutters-${entry.alignment}-${viewport.width}`, {
body: Buffer.from(JSON.stringify(geometry, null, 2)), contentType: 'application/json',
});
}
await canvas.locator(`[data-block="${cases[0].playerId}"]`).scrollIntoViewIfNeeded();
await screenshot(page, testInfo, `editor-content-gutters-${viewport.width}`);
}
});
+290
View File
@@ -0,0 +1,290 @@
import { test, expect } from '@playwright/test';
import { readFile } from 'node:fs/promises';
const blockName = 'lamgc/asciiplayer';
const fixtures = '/wp-content/uploads/asciiplayer-fixtures';
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();
}
function playerBlock(page, id) {
return page.frameLocator('iframe[name="editor-canvas"]').locator(`[data-block="${id}"]`);
}
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: playerBlock(page, id) };
}
async function attributes(page, id) {
return page.evaluate((clientId) => window.wp.data.select('core/block-editor').getBlockAttributes(clientId), id);
}
async function readyPreview(block) {
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready');
await expect(block.locator('.ap-wrapper')).toHaveCount(1);
await expect(block.locator('.ap-term')).toBeVisible();
}
async function expectGrid(block, cols, rows) {
await expect.poll(() => block.locator('.ap-term').evaluate((terminal) => ({
cols: Number(terminal.style.getPropertyValue('--term-cols')),
rows: Number(terminal.style.getPropertyValue('--term-rows')),
}))).toEqual({ cols, rows });
}
async function openDimensions(page) {
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
const columns = page.getByRole('spinbutton', { name: 'Columns', exact: true });
const rows = page.getByRole('spinbutton', { name: 'Rows', exact: true });
if (!await columns.isVisible()) {
await page.locator('.components-panel__body-toggle').filter({ hasText: /^Terminal size$/ }).click();
}
await expect(columns).toBeVisible();
return { columns, rows };
}
async function expectNativeSize(controls, cols, rows) {
await expect(controls.columns).toHaveAttribute('placeholder', cols === undefined ? 'From recording' : String(cols));
await expect(controls.rows).toHaveAttribute('placeholder', rows === undefined ? 'From recording' : String(rows));
}
async function openMedia(page, block) {
await block.getByRole('button', { name: 'Choose recording', exact: true }).click();
const dialog = page.getByRole('dialog', { name: 'Choose an Asciicast recording', exact: true });
await expect(dialog).toBeVisible();
return dialog;
}
async function uploadRecording(page, dialog, name, buffer) {
await dialog.getByRole('tab', { name: 'Upload files', exact: true }).click();
// Native WP media uses Plupload. Its file input is intentionally hidden and
// may live outside the modal; setInputFiles exercises the actual uploader.
const input = page.locator('.moxie-shim input[type="file"]').last();
await expect(input).toBeAttached();
const response = page.waitForResponse((result) =>
/\/wp-admin\/async-upload\.php(?:\?|$)/.test(result.url()) && result.request().method() === 'POST'
);
await input.setInputFiles({ name, mimeType: 'application/x-asciicast', buffer });
return (await response).json();
}
async function selectAttachment(dialog, id) {
await dialog.getByRole('tab', { name: 'Media Library', exact: true }).click();
const attachment = dialog.locator(`.attachment[data-id="${id}"]`);
await expect(attachment).toBeVisible();
// Newly uploaded files are already selected; clicking them again deselects.
if (!await attachment.evaluate((element) => element.classList.contains('selected'))) await attachment.click();
const confirm = dialog.locator('.media-button-select');
await expect(confirm).toBeEnabled();
await confirm.click();
await expect(dialog).toBeHidden();
}
test('recording metadata follows URL changes, clears while loading or invalid, and never replaces explicit dimensions', async ({ page }) => {
await openEditor(page);
const original = new URL(`${fixtures}/hello.cast`, page.url()).href;
const replacement = new URL(`${fixtures}/replacement.cast?metadata=delayed`, page.url()).href;
const unavailable = new URL(`${fixtures}/missing.cast?metadata=error`, page.url()).href;
const malformed = new URL(`${fixtures}/malformed.cast?metadata=valid-header`, page.url()).href;
const recording = await readFile(new URL('../fixtures/replacement.cast', import.meta.url));
let release;
let requested = false;
const pending = new Promise((resolve) => { release = resolve; });
await page.route(replacement, async (route) => {
requested = true;
await pending;
await route.fulfill({ contentType: 'text/plain', body: recording }).catch(() => {});
});
await page.route(unavailable, (route) => route.fulfill({ status: 503, contentType: 'text/plain', body: 'Unavailable' }));
await page.route(malformed, (route) => route.fulfill({
contentType: 'text/plain', body: '{"version":2,"width":101,"height":31}\n[invalid event]\n',
}));
try {
const { id, block } = await insertPlayer(page, { source: original });
await readyPreview(block);
const dimensions = await openDimensions(page);
await expectNativeSize(dimensions, 64, 12);
await expect(dimensions.columns).toHaveValue('');
await expect(dimensions.rows).toHaveValue('');
expect((await attributes(page, id)).cols).toBeUndefined();
expect((await attributes(page, id)).rows).toBeUndefined();
await dimensions.columns.fill('80');
await dimensions.rows.fill('20');
await dimensions.rows.press('Tab');
await readyPreview(block);
await expectGrid(block, 80, 20);
await expectNativeSize(dimensions, 64, 12);
const input = block.getByRole('textbox', { name: 'Recording URL', exact: true });
await input.fill(replacement);
await expectNativeSize(dimensions);
await expect.poll(() => requested).toBe(true);
await expectNativeSize(dimensions);
await expect(dimensions.columns).toHaveValue('80');
await expect(dimensions.rows).toHaveValue('20');
release();
await readyPreview(block);
await expectNativeSize(dimensions, 100, 30);
await expectGrid(block, 80, 20);
expect(await attributes(page, id)).toMatchObject({ source: replacement, cols: 80, rows: 20 });
await input.fill('javascript:alert(1)');
await expect(block.locator('.asciiplayer-editor__preview')).toHaveCount(0);
await expectNativeSize(dimensions);
// Invalid drafts do not overwrite the last valid saved URL or overrides.
expect(await attributes(page, id)).toMatchObject({ source: replacement, cols: 80, rows: 20 });
await input.fill(original);
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
await readyPreview(block);
await expectNativeSize(dimensions, 64, 12);
for (const failingSource of [unavailable, malformed]) {
await input.fill(failingSource);
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'error');
// Even a readable header must be discarded if the player fails.
await expectNativeSize(dimensions);
expect(await attributes(page, id)).toMatchObject({ source: failingSource, cols: 80, rows: 20 });
}
await input.fill('');
await expect.poll(async () => (await attributes(page, id)).source).toBe('');
await expectNativeSize(dimensions);
expect(await attributes(page, id)).toMatchObject({ cols: 80, rows: 20 });
} finally {
release();
}
});
test('pretty v1 and commented v3 recordings play with native header dimensions', async ({ page }) => {
await openEditor(page);
// Fixtures follow the official formats, including v1's multiline JSON and
// v3's comments after its single-line header and relative event timestamps:
// https://docs.asciinema.org/manual/asciicast/v1/
// https://docs.asciinema.org/manual/asciicast/v3/
const cases = [
{ filename: 'v1-pretty.cast', cols: 72, rows: 18, output: 'Pretty v1 recording' },
{ filename: 'v3-comments.cast', cols: 92, rows: 22, output: 'Commented v3 recording' },
];
for (const entry of cases) {
const source = new URL(`${fixtures}/${entry.filename}`, page.url()).href;
const { id, block } = await insertPlayer(page, { source });
await readyPreview(block);
await expectGrid(block, entry.cols, entry.rows);
const dimensions = await openDimensions(page);
await expectNativeSize(dimensions, entry.cols, entry.rows);
await expect(dimensions.columns).toHaveValue('');
await expect(dimensions.rows).toHaveValue('');
expect((await attributes(page, id)).cols).toBeUndefined();
expect((await attributes(page, id)).rows).toBeUndefined();
await block.locator('.ap-overlay-start .ap-play-button').click();
await expect(block.locator('.ap-term-text')).toContainText(entry.output);
}
});
test('native Media Library uploads, selects and replaces a cast while cancel leaves the current recording intact', async ({ page }, testInfo) => {
await openEditor(page);
const { id, block } = await insertPlayer(page);
const firstCast = await readFile(new URL('../fixtures/hello.cast', import.meta.url));
const secondCast = await readFile(new URL('../fixtures/replacement.cast', import.meta.url));
const unique = `${Date.now()}-${testInfo.retry}`;
let dialog = await openMedia(page, block);
const first = await uploadRecording(page, dialog, `asciiplayer-original-${unique}.cast`, firstCast);
expect(first.success, JSON.stringify(first)).toBe(true);
expect(first.data.mime).toBe('application/x-asciicast');
await selectAttachment(dialog, first.data.id);
const input = block.getByRole('textbox', { name: 'Recording URL', exact: true });
await expect(input).toHaveValue(first.data.url);
// Selecting in the native media frame applies and autoloads, with no Apply URL click.
await readyPreview(block);
await expectGrid(block, 64, 12);
let dimensions = await openDimensions(page);
await expectNativeSize(dimensions, 64, 12);
expect(await attributes(page, id)).toMatchObject({ source: first.data.url });
expect((await attributes(page, id)).cols).toBeUndefined();
expect((await attributes(page, id)).rows).toBeUndefined();
await block.locator('.ap-term').evaluate((element) => { element.dataset.mediaIdentity = 'original'; });
dialog = await openMedia(page, block);
const second = await uploadRecording(page, dialog, `asciiplayer-replacement-${unique}.cast`, secondCast);
expect(second.success, JSON.stringify(second)).toBe(true);
await dialog.locator('.media-modal-close').click();
await expect(dialog).toBeHidden();
await expect(input).toHaveValue(first.data.url);
expect((await attributes(page, id)).source).toBe(first.data.url);
await expectNativeSize(dimensions, 64, 12);
await expect(block.locator('.ap-term')).toHaveAttribute('data-media-identity', 'original');
// The upload above is now an existing media item. Reopen the real frame and
// select its tile rather than changing block attributes through the store.
dialog = await openMedia(page, block);
await selectAttachment(dialog, second.data.id);
await expect(input).toHaveValue(second.data.url);
await readyPreview(block);
await expectGrid(block, 100, 30);
await expectNativeSize(dimensions, 100, 30);
await block.locator('.ap-overlay-start .ap-play-button').click();
await expect(block.locator('.ap-term-text')).toContainText('Replacement recording');
expect((await attributes(page, id)).source).toBe(second.data.url);
expect((await attributes(page, id)).cols).toBeUndefined();
expect((await attributes(page, id)).rows).toBeUndefined();
const path = testInfo.outputPath('media-library-selected-recording.png');
await page.screenshot({ path, fullPage: true });
await testInfo.attach('media-library-selected-recording', { path, contentType: 'image/png' });
await page.evaluate(async () => {
const editor = window.wp.data.dispatch('core/editor');
editor.editPost({ title: 'Native media recording selection regression' });
await editor.savePost();
if (window.wp.data.select('core/editor').didPostSaveRequestFail()) throw new Error('WordPress could not save the test post.');
});
await page.reload();
await page.waitForFunction((name) => window.wp?.data?.select('core/block-editor')?.getBlocks().some((entry) => entry.name === name), blockName);
const reloaded = await page.evaluate((name) => {
const block = window.wp.data.select('core/block-editor').getBlocks().find((entry) => entry.name === name);
window.wp.data.dispatch('core/block-editor').selectBlock(block.clientId);
return block;
}, blockName);
expect(reloaded.attributes.source).toBe(second.data.url);
expect(reloaded.attributes.cols).toBeUndefined();
expect(reloaded.attributes.rows).toBeUndefined();
await readyPreview(playerBlock(page, reloaded.clientId));
dimensions = await openDimensions(page);
await expectNativeSize(dimensions, 100, 30);
});
test('native Media Library rejects an invalid cast upload without applying a source', async ({ page }, testInfo) => {
await openEditor(page);
const { id, block } = await insertPlayer(page);
const dialog = await openMedia(page, block);
const malformed = await readFile(new URL('../fixtures/malformed.cast', import.meta.url));
const result = await uploadRecording(page, dialog, `asciiplayer-invalid-${Date.now()}-${testInfo.retry}.cast`, malformed);
expect(result.success, JSON.stringify(result)).toBe(false);
const validationMessage = 'Upload a valid Asciicast v2/v3 JSONL or pretty-printed v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, and 1,000 columns or rows).';
// A filesystem/permission failure is not evidence of content validation.
expect(result.data.message).toBe(validationMessage);
await expect(dialog).toContainText(validationMessage);
await expect(dialog.locator('.media-button-select')).toBeDisabled();
await dialog.locator('.media-modal-close').click();
await expect(block.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveValue('');
expect((await attributes(page, id)).source).toBe('');
await expect(block.locator('.asciiplayer-editor__preview')).toHaveCount(0);
});
+4
View File
@@ -0,0 +1,4 @@
{"version":2,"width":100,"height":30,"timestamp":1700000000,"env":{"TERM":"xterm-256color","SHELL":"/bin/sh"},"title":"Replacement recording with a different native size"}
[0.0,"o","$ printf 'Replacement recording'\r\n"]
[0.1,"o","Replacement recording\r\n"]
[12.0,"o","$ "]
+6
View File
@@ -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","$ "]
+17
View File
@@ -0,0 +1,17 @@
{
"version": 1,
"width": 72,
"height": 18,
"duration": 12,
"command": "/bin/sh",
"title": "Pretty-printed v1 integration fixture",
"env": {
"TERM": "xterm-256color",
"SHELL": "/bin/sh"
},
"stdout": [
[0.0, "$ printf 'Pretty v1 recording'\r\n"],
[0.1, "Pretty v1 recording\r\n"],
[11.9, "$ "]
]
}
+6
View File
@@ -0,0 +1,6 @@
{"version":3,"term":{"cols":92,"rows":22,"type":"xterm-256color"},"timestamp":1700000000,"title":"v3 recording with comments","env":{"SHELL":"/bin/sh"}}
# Comments are permitted after the header in asciicast v3.
[0.0,"o","$ printf 'Commented v3 recording'\r\n"]
[0.1,"o","Commented v3 recording\r\n"]
# v3 timestamps are delays from the previous event.
[11.9,"o","$ "]
+45
View File
@@ -0,0 +1,45 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import gettext from 'gettext-parser';
const po = gettext.po.parse(fs.readFileSync('languages/wp-asciiplayer-zh_CN.po'));
const mo = gettext.mo.parse(fs.readFileSync('languages/wp-asciiplayer-zh_CN.mo'));
const pot = gettext.po.parse(fs.readFileSync('languages/wp-asciiplayer.pot'));
const editor = JSON.parse(fs.readFileSync('languages/wp-asciiplayer-zh_CN-lamgc-asciiplayer-editor.json')).locale_data.messages;
const view = JSON.parse(fs.readFileSync('languages/wp-asciiplayer-zh_CN-lamgc-asciiplayer-view.json')).locale_data.messages;
test('all extracted strings and gettext contexts round-trip through MO and both script catalogs', () => {
let count = 0;
for (const [context, entries] of Object.entries(pot.translations)) {
for (const entry of Object.values(entries)) {
if (!entry.msgid) continue;
count++;
const translated = po.translations[context][entry.msgid].msgstr;
assert.ok(translated[0]);
assert.deepEqual(mo.translations[context][entry.msgid].msgstr, translated);
const key = context ? `${context}\u0004${entry.msgid}` : entry.msgid;
assert.deepEqual(editor[key], translated);
assert.deepEqual(view[key], translated);
}
}
assert.ok(count >= 75);
});
test('catalogs use Chinese plural rules, exact locale, and standard WordPress textdomain', () => {
assert.equal(po.headers.language, 'zh_CN');
assert.equal(mo.headers.language, 'zh_CN');
assert.equal(editor[''].lang, 'zh_CN');
assert.equal(editor[''].domain, 'wp-asciiplayer');
assert.equal(editor['']['plural-forms'], 'nplurals=1; plural=0;');
assert.equal(editor['block title\u0004Asciicast Player'][0], 'Asciicast 播放器');
assert.equal(editor['Recording URL'][0], '录制文件 URL');
});
test('Unicode, punctuation, percentages and literal author content are preserved', () => {
assert.equal(editor['Add a caption…'][0], '添加说明文字…');
assert.match(editor['Use a CSS length, such as 480px or 65%. The player stays within its available space.'][0], /480px.*65%/);
assert.equal(editor['Author caption / 作者说明'], undefined);
const serialized = JSON.stringify(editor);
assert.deepEqual(JSON.parse(serialized), editor);
});
+24
View File
@@ -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);
});
+124
View File
@@ -0,0 +1,124 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { MAX_HEADER_BYTES, readRecordingSize, recordingSizeFromHeader } from '../../src/recording-metadata.js';
test( 'original dimensions use each supported asciicast header schema', () => {
assert.deepEqual( recordingSizeFromHeader( { version: 1, width: 132, height: 43 } ), { cols: 132, rows: 43 } );
assert.deepEqual( recordingSizeFromHeader( { version: 2, width: 110, height: 35 } ), { cols: 110, rows: 35 } );
assert.deepEqual( recordingSizeFromHeader( { version: 3, term: { cols: 150, rows: 50 }, width: 1, height: 1 } ), { cols: 150, rows: 50 } );
assert.deepEqual( recordingSizeFromHeader( { version: 2, width: 1, height: 1000 } ), { cols: 1, rows: 1000 } );
assert.deepEqual( recordingSizeFromHeader( { version: 2, width: 1500, height: 1200 } ), { cols: 1500, rows: 1200 } );
assert.deepEqual( recordingSizeFromHeader( { version: 2, width: Number.MAX_SAFE_INTEGER, height: 1 } ), { cols: Number.MAX_SAFE_INTEGER, rows: 1 } );
} );
test( 'missing, unsupported and invalid dimensions stay unknown, never 80 by 24', () => {
for ( const header of [ null, undefined, '', [], {}, { width: 80, height: 24 }, { version: '2', width: 80, height: 24 }, { version: 4, width: 80, height: 24 }, { version: 3, width: 80, height: 24 }, { version: 3, term: {} } ] ) {
assert.equal( recordingSizeFromHeader( header ), null );
}
for ( const invalid of [ undefined, null, '', '80', true, false, NaN, Infinity, -1, 0, 1.5, Number.MAX_SAFE_INTEGER + 1 ] ) {
assert.equal( recordingSizeFromHeader( { version: 2, width: invalid, height: 24 } ), null );
assert.equal( recordingSizeFromHeader( { version: 3, term: { cols: 80, rows: invalid } } ), null );
}
} );
test( 'metadata reads the first header and preserves the full original response for playback', async () => {
const text = '{"version":2,"width":132,"height":43}\n[1,"r","200x60"]\n[2,"o","hello"]\n';
const response = new Response( text );
let clones = 0;
const clone = response.clone.bind( response );
response.clone = () => { clones++; return clone(); };
assert.deepEqual( await readRecordingSize( response ), { cols: 132, rows: 43 } );
assert.equal( clones, 1 );
assert.equal( response.bodyUsed, false );
assert.equal( await response.text(), text );
} );
test( 'v3 reads terminal metadata, not nested output or subsequent resize events', async () => {
const text = '{"version":3,"env":{"cols":500,"rows":500},"term":{"cols":120,"rows":30}}\n[0,"r","90x20"]\n';
const response = new Response( text );
assert.deepEqual( await readRecordingSize( response ), { cols: 120, rows: 30 } );
await response.text();
} );
function chunkedResponse( chunks ) {
let reads = 0;
let canceled = false;
return {
response: {
ok: true,
body: { getReader() { throw new Error( 'Do not read the original response.' ); } },
clone: () => ( {
body: { getReader: () => ( {
async read() {
const value = chunks[ reads++ ];
return value ? { value, done: false } : { done: true };
},
cancel() {
canceled = true;
// A real tee's cancel can wait for its other branch.
return new Promise( () => {} );
},
} ) },
} ),
},
get reads() { return reads; },
get canceled() { return canceled; },
};
}
test( 'pretty-printed v1 reads dimensions before stdout and does not await tee cancellation', async () => {
const encode = new TextEncoder();
const stream = chunkedResponse( [
encode.encode( '{\n "version": 1,\n "width": 104,\n' ),
encode.encode( ' "height": 28,\n "stdout": [\n' ),
encode.encode( `[0,${ JSON.stringify( 'output'.repeat( MAX_HEADER_BYTES ) ) }]]}` ),
] );
assert.deepEqual( await readRecordingSize( stream.response ), { cols: 104, rows: 28 } );
assert.equal( stream.reads, 2 );
assert.equal( stream.canceled, true );
} );
test( 'streaming JSON handles split UTF-8, escapes and nested objects without false fields', async () => {
const text = JSON.stringify( { title: '尺寸 \\ " }, \\ ', env: { width: 300, height: 500 }, width: 137, height: 47, version: 1, stdout: [] } );
const chunks = Array.from( new TextEncoder().encode( text ), ( value ) => Uint8Array.of( value ) );
const stream = chunkedResponse( chunks );
assert.deepEqual( await readRecordingSize( stream.response ), { cols: 137, rows: 47 } );
assert.ok( stream.reads < chunks.length );
assert.equal( stream.canceled, true );
} );
test( 'headers over the byte limit stay unknown without draining the recording', async () => {
const encode = new TextEncoder();
const stream = chunkedResponse( [
encode.encode( '{"version":2,"title":"' + 'x'.repeat( MAX_HEADER_BYTES ) ),
encode.encode( '","width":132,"height":43}\n[1,"o","hello"]' ),
] );
assert.equal( await readRecordingSize( stream.response ), null );
assert.equal( stream.reads, 1 );
assert.equal( stream.canceled, true );
} );
test( 'byte limit accepts a complete header at its boundary and ignores larger output chunks', async () => {
const base = '{"version":2,"width":132,"height":43,"title":"';
const header = base + 'x'.repeat( MAX_HEADER_BYTES - base.length - 2 ) + '"}';
const stream = chunkedResponse( [ new TextEncoder().encode( header + '\n[1,"o","' + 'x'.repeat( MAX_HEADER_BYTES ) + '"]' ) ] );
assert.deepEqual( await readRecordingSize( stream.response ), { cols: 132, rows: 43 } );
assert.equal( stream.reads, 1 );
} );
test( 'invalid JSON, nested lookalikes and incomplete dimensions never become defaults', async () => {
for ( const text of [ '', 'not a cast', '<html>error</html>', '[]', '{}', '{"version":2,"env":{"width":80,"height":24}}', '{"version":2,"width":80,"height":24,}', '{"version":2,,"width":80,"height":24}', '{"version":2,"width":80,"height":24]', '{"version":2,"width":80,"height":24', '{"version":3,"term":{"cols":80}}' ] ) {
const response = new Response( text );
assert.equal( await readRecordingSize( response ), null, text );
await response.text();
}
} );
test( 'failed responses, unavailable streams and rejected reads quietly stay unknown', async () => {
assert.equal( await readRecordingSize( { ok: false } ), null );
assert.equal( await readRecordingSize( { ok: true, body: null } ), null );
assert.equal( await readRecordingSize( { ok: true, body: { getReader() {} }, clone() { throw new Error( 'locked' ); } } ), null );
const broken = chunkedResponse( [] );
broken.response.clone = () => ( { body: { getReader: () => ( { read: () => Promise.reject( new Error( 'aborted' ) ), cancel: () => Promise.reject( new Error( 'aborted' ) ) } ) } } );
assert.equal( await readRecordingSize( broken.response ), null );
} );
+43
View File
@@ -17,6 +17,45 @@ function ap_record( $key, $value ) {
function add_action( $hook, $callback, $priority = 10 ) { function add_action( $hook, $callback, $priority = 10 ) {
ap_record( 'actions', array( $hook, $callback, $priority ) ); ap_record( 'actions', array( $hook, $callback, $priority ) );
} }
function add_filter( $hook, $callback, $priority = 10, $accepted_args = 1 ) {
ap_record( 'filters', array( $hook, $callback, $priority, $accepted_args ) );
}
function load_plugin_textdomain( $domain, $deprecated, $path ) {
ap_record( 'textdomains', array( $domain, $path ) );
}
function plugin_basename( $file ) {
return 'wp-asciiplayer/asciicast-player.php';
}
function __( $text, $domain = 'default' ) {
return $text;
}
function current_user_can( $capability ) {
return ! empty( $GLOBALS['ap_test']['capabilities'][ $capability ] );
}
function user_can( $user, $capability ) {
return ! empty( $GLOBALS['ap_test']['user_capabilities'][ $user ][ $capability ] );
}
function is_multisite() {
return ! empty( $GLOBALS['ap_test']['multisite'] );
}
function get_site_option( $key, $default = false ) {
return $GLOBALS['ap_test']['site_options'][ $key ] ?? $default;
}
function get_allowed_mime_types() {
return $GLOBALS['ap_test']['allowed_mimes'] ?? LamGC\Asciiplayer\allow_cast_upload_mime( array( 'txt' => 'text/plain', 'jpg' => 'image/jpeg' ) );
}
function wp_check_filetype( $filename, $mimes = null ) {
// Mirrors core's empty-map fallback to cover explicit MIME deny-lists.
if ( empty( $mimes ) ) {
$mimes = get_allowed_mime_types();
}
foreach ( $mimes as $extension => $mime ) {
if ( preg_match( '/\.(' . $extension . ')$/i', $filename, $matches ) ) {
return array( 'ext' => $matches[1], 'type' => $mime );
}
}
return array( 'ext' => false, 'type' => false );
}
function add_shortcode( $tag, $callback ) { function add_shortcode( $tag, $callback ) {
ap_record( 'shortcodes', array( $tag, $callback ) ); ap_record( 'shortcodes', array( $tag, $callback ) );
} }
@@ -54,6 +93,10 @@ function get_block_wrapper_attributes( $attributes ) {
} }
return implode( ' ', $output ); 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 ) { function wp_json_encode( $value, $flags = 0 ) {
return json_encode( $value, $flags ); return json_encode( $value, $flags );
} }
+32 -5
View File
@@ -48,6 +48,14 @@ try {
same( true, is_callable( $action[1] ), 'Every registered callback is callable.' ); same( true, is_callable( $action[1] ), 'Every registered callback is callable.' );
} }
register_plugin(); register_plugin();
same( array( 'wp-asciiplayer', 'wp-asciiplayer/languages' ), $GLOBALS['ap_test']['textdomains'][0], 'Bundled PHP catalogs register during init.' );
if ( file_exists( dirname( __DIR__, 2 ) . '/build/runtime.asset.php' ) ) {
$versions = require dirname( __DIR__, 2 ) . '/build/runtime.asset.php';
same( $versions['player.js'], $GLOBALS['ap_test']['scripts']['lamgc-asciiplayer-player']['version'], 'Player script uses its content hash.' );
foreach ( array( 'lamgc-asciiplayer-player-style' => 'player.css', 'lamgc-asciiplayer-style' => 'style-index.css', 'lamgc-asciiplayer-editor-style' => 'index.css' ) as $handle => $file ) {
same( $versions[ $file ], $GLOBALS['ap_test']['styles'][ $handle ]['version'], 'Each stylesheet uses its own content hash.' );
}
}
same( 'asciiplayer', $GLOBALS['ap_test']['shortcodes'][0][0], 'Legacy shortcode stays registered.' ); same( 'asciiplayer', $GLOBALS['ap_test']['shortcodes'][0][0], 'Legacy shortcode stays registered.' );
contains( '/build', $GLOBALS['ap_test']['blocks'][0]['path'], 'Block uses local metadata.' ); contains( '/build', $GLOBALS['ap_test']['blocks'][0]['path'], 'Block uses local metadata.' );
same( 'LamGC\\Asciiplayer\\render_block', $GLOBALS['ap_test']['blocks'][0]['args']['render_callback'], 'Block is server rendered.' ); same( 'LamGC\\Asciiplayer\\render_block', $GLOBALS['ap_test']['blocks'][0]['args']['render_callback'], 'Block is server rendered.' );
@@ -60,8 +68,8 @@ try {
same( array( 'lamgc-asciiplayer-player-style' ), $GLOBALS['ap_test']['styles']['lamgc-asciiplayer-style']['deps'], 'Frontend style depends on player stylesheet.' ); 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.' ); 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.' ); 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.js?ver=' . $GLOBALS['ap_test']['scripts']['lamgc-asciiplayer-player']['version'], $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.css?ver=' . $GLOBALS['ap_test']['styles']['lamgc-asciiplayer-player-style']['version'], $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. // 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 ) { 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 +136,30 @@ try {
same( true, isset( $GLOBALS['ap_test']['enqueued_styles']['lamgc-asciiplayer-style'] ), 'Every valid render requests CSS.' ); 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))' ) ); $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.' ); 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.' ); 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( '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( '', 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( 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-container', end( $GLOBALS['ap_test']['block_wrappers'] )['class'], 'Block wrapper classes/layout pass through WordPress block supports.' ); 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 &amp; 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 &amp; 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. // No is_single gate: query lookahead supports Pages and archive results.
reset_enqueues(); reset_enqueues();
$GLOBALS['wp_query'] = (object) array( 'posts' => array( (object) array( 'post_content' => 'Ordinary content' ), (object) array( 'post_content' => '[asciiplayer]/demo.cast[/asciiplayer]' ) ) ); $GLOBALS['wp_query'] = (object) array( 'posts' => array( (object) array( 'post_content' => 'Ordinary content' ), (object) array( 'post_content' => '[asciiplayer]/demo.cast[/asciiplayer]' ) ) );
@@ -153,6 +178,8 @@ try {
print_late_styles(); print_late_styles();
same( array( 'lamgc-asciiplayer-style' ), $GLOBALS['ap_test']['style_print_calls'], 'Late/widget styles print once in the footer.' ); same( array( 'lamgc-asciiplayer-style' ), $GLOBALS['ap_test']['style_print_calls'], 'Late/widget styles print once in the footer.' );
require __DIR__ . '/uploads.php';
echo "OK: {$assertions} assertions passed.\n"; echo "OK: {$assertions} assertions passed.\n";
} catch ( Throwable $error ) { } catch ( Throwable $error ) {
fwrite( STDERR, $error->getMessage() . "\n" ); fwrite( STDERR, $error->getMessage() . "\n" );
+183
View File
@@ -0,0 +1,183 @@
<?php
/** Upload validation contracts. Included by run.php after its assertion helpers. */
use function LamGC\Asciiplayer\allow_cast_upload_mime;
use function LamGC\Asciiplayer\check_cast_filetype;
use function LamGC\Asciiplayer\is_valid_cast_file;
use function LamGC\Asciiplayer\validate_cast_upload;
use const LamGC\Asciiplayer\CAST_MAX_BYTES;
use const LamGC\Asciiplayer\CAST_MAX_EVENTS;
use const LamGC\Asciiplayer\CAST_MAX_LINE_BYTES;
use const LamGC\Asciiplayer\CAST_MAX_V1_BYTES;
use const LamGC\Asciiplayer\CAST_MIME;
function cast_contents_are_valid( $contents ) {
$path = tempnam( sys_get_temp_dir(), 'ap-cast-' );
try {
file_put_contents( $path, $contents );
return is_valid_cast_file( $path );
} finally {
unlink( $path );
}
}
$required_filters = array(
'upload_mimes' => array( 'LamGC\\Asciiplayer\\allow_cast_upload_mime', 2 ),
'wp_check_filetype_and_ext' => array( 'LamGC\\Asciiplayer\\check_cast_filetype', 5 ),
'wp_handle_upload_prefilter' => array( 'LamGC\\Asciiplayer\\validate_cast_upload', 1 ),
'wp_handle_sideload_prefilter' => array( 'LamGC\\Asciiplayer\\validate_cast_upload', 1 ),
);
foreach ( $GLOBALS['ap_test']['filters'] ?? array() as $filter ) {
if ( isset( $required_filters[ $filter[0] ] ) ) {
same( $required_filters[ $filter[0] ][0], $filter[1], 'Upload hook uses the intended callback.' );
same( $required_filters[ $filter[0] ][1], $filter[3], 'Upload hook receives all required arguments.' );
same( true, is_callable( $filter[1] ), 'Upload callback is callable.' );
unset( $required_filters[ $filter[0] ] );
}
}
same( array(), $required_filters, 'All safe-upload hooks are registered.' );
$mimes = array( 'jpg|jpeg' => 'image/jpeg', 'txt' => 'text/plain' );
same( $mimes, allow_cast_upload_mime( $mimes ), 'Anonymous/non-uploaders get no extra MIME permissions.' );
$GLOBALS['ap_test']['capabilities'] = array( 'upload_files' => true );
same( array_merge( $mimes, array( 'cast' => CAST_MIME ) ), allow_cast_upload_mime( $mimes ), 'Only .cast receives the canonical MIME.' );
same( $mimes, allow_cast_upload_mime( $mimes, 42 ), 'Explicit non-uploading user does not inherit current user permissions.' );
$GLOBALS['ap_test']['user_capabilities'][42] = array( 'upload_files' => true );
same( CAST_MIME, allow_cast_upload_mime( $mimes, 42 )['cast'], 'An explicit eligible user can upload casts.' );
$GLOBALS['ap_test']['multisite'] = true;
$GLOBALS['ap_test']['site_options']['upload_filetypes'] = 'jpg jpeg txt';
same( $mimes, allow_cast_upload_mime( $mimes ), 'Multisite network extension restrictions remain in effect.' );
$GLOBALS['ap_test']['site_options']['upload_filetypes'] = "jpg\ncast txt";
same( CAST_MIME, allow_cast_upload_mime( $mimes )['cast'], 'Network-authorized cast uploads are available.' );
$GLOBALS['ap_test']['multisite'] = false;
$v2 = '{"version":2,"width":80,"height":24}';
$v3 = '{"version":3,"term":{"cols":100,"rows":30}}';
$v1 = array( 'version' => 1, 'width' => 80, 'height' => 24, 'duration' => 1.5, 'stdout' => array( array( 0.1, "Hello\r\n" ), array( 1.4, 'World' ) ) );
foreach ( array(
'pretty v1' => json_encode( $v1, JSON_PRETTY_PRINT ),
'v2 output' => $v2 . "\n[0.1,\"o\",\"Hello\\r\\n\"]\n",
'v3 relative events' => $v3 . "\n[5,\"o\",\"Hello\"]\n[0.1,\"r\",\"120x40\"]\n[0,\"x\",\"0\"]\n",
'v3 comments' => $v3 . "\n# comment before events\n[0,\"o\",\"ok\"]\n# trailing comment\n",
'v2 input markers resize extensions' => $v2 . "\n[0,\"i\",\"x\"]\n[0,\"m\",\"A\"]\n[1,\"r\",\"90x25\"]\n[1,\"future\",\"data\"]",
'CRLF' => $v2 . "\r\n[0,\"o\",\"hello\"]\r\n",
'header only' => $v2,
'unknown header fields' => '{"version":2,"width":80,"height":24,"future":{"key":true}}' . "\n[0,\"o\",\"ok\"]\n",
'literal terminal markup' => $v2 . "\n[0,\"o\",\"<script> is plain terminal output</script>\"]\n",
) as $description => $contents ) {
same( true, cast_contents_are_valid( $contents ), 'Accept valid ' . $description . '.' );
}
same( true, is_valid_cast_file( dirname( __DIR__ ) . '/fixtures/hello.cast' ), 'Accept repository hello recording.' );
same( true, is_valid_cast_file( dirname( __DIR__ ) . '/fixtures/resize.cast' ), 'Accept repository resize recording.' );
foreach ( array(
'empty' => '',
'plain text' => 'Hello world',
'JSON object' => '{"message":"arbitrary JSON"}',
'JSON list' => '[1,2,3]',
'HTML' => '<!doctype html><script>alert(1)</script>',
'SVG' => '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>',
'unsupported version' => '{"version":4,"width":80,"height":24}',
'string version' => '{"version":"2","width":80,"height":24}',
'zero width' => '{"version":2,"width":0,"height":24}',
'oversized width' => '{"version":2,"width":1001,"height":24}',
'negative height' => '{"version":2,"width":80,"height":-1}',
'fractional width' => '{"version":2,"width":80.5,"height":24}',
'string width' => '{"version":2,"width":"80","height":24}',
'v3 old dimensions' => '{"version":3,"width":80,"height":24}',
'v3 terminal array' => '{"version":3,"term":[100,30]}',
'v1 absent stdout' => "{\n\"version\":1,\"width\":80,\"height\":24\n}",
'v1 stdout object' => "{\n\"version\":1,\"width\":80,\"height\":24,\"stdout\":{\"0\":[0,\"x\"]}\n}",
'compact v1 unsupported by bundled player' => json_encode( $v1 ),
'large compact v1 unsupported by bundled player' => json_encode( array_merge( $v1, array( 'title' => str_repeat( 'a', CAST_MAX_LINE_BYTES + 1 ) ) ) ),
'v1 negative delay' => json_encode( array_merge( $v1, array( 'stdout' => array( array( -1, 'x' ) ) ) ), JSON_PRETTY_PRINT ),
'v1 malformed later frame' => json_encode( array_merge( $v1, array( 'stdout' => array( array( 0, 'ok' ), array( 0, array( 'x' ) ) ) ) ), JSON_PRETTY_PRINT ),
'v1 extra frame element' => json_encode( array_merge( $v1, array( 'stdout' => array( array( 0, 'ok', 'extra' ) ) ) ), JSON_PRETTY_PRINT ),
'v1 bad duration' => json_encode( array_merge( $v1, array( 'duration' => '1' ) ), JSON_PRETTY_PRINT ),
'negative event time' => $v2 . "\n[-1,\"o\",\"bad\"]\n",
'string event time' => $v2 . "\n[\"0\",\"o\",\"bad\"]\n",
'boolean event time' => $v2 . "\n[false,\"o\",\"bad\"]\n",
'infinite time' => $v2 . "\n[1e999,\"o\",\"bad\"]\n",
'milliseconds overflow' => $v2 . "\n[1e308,\"o\",\"bad\"]\n",
'v3 cumulative milliseconds overflow' => $v3 . "\n[1e305,\"o\",\"first\"]\n[1e305,\"o\",\"second\"]\n",
'v2 out of order' => $v2 . "\n[2,\"o\",\"first\"]\n[1,\"o\",\"second\"]\n",
'event object' => $v2 . "\n{\"0\":0,\"1\":\"o\",\"2\":\"bad\"}\n",
'missing event data' => $v2 . "\n[0,\"o\"]\n",
'extra event element' => $v2 . "\n[0,\"o\",\"bad\",1]\n",
'event data array' => $v2 . "\n[0,\"o\",[\"bad\"]]\n",
'empty event type' => $v2 . "\n[0,\"\",\"bad\"]\n",
'zero resize' => $v2 . "\n[0,\"r\",\"0x20\"]\n",
'oversized resize' => $v2 . "\n[0,\"r\",\"2000x20\"]\n",
'malformed resize' => $v2 . "\n[0,\"r\",\"80,24\"]\n",
'bad later JSON' => $v2 . "\n[0,\"o\",\"ok\"]\n[1,\"o\",\"truncated\"\n",
'trailing HTML' => $v2 . "\n[0,\"o\",\"ok\"]\n<script>alert(1)</script>\n",
'trailing JSON object' => $v2 . "\n[0,\"o\",\"ok\"]\n{\"unrelated\":true}\n",
'blank event line' => $v2 . "\n\n",
'indented event ignored by bundled player' => $v2 . "\n [0,\"o\",\"invisible\"]\n",
'v2 comment' => $v2 . "\n# comment\n",
'v3 indented comment' => $v3 . "\n # not a comment\n",
'UTF-8 BOM' => "\xef\xbb\xbf" . $v2,
'invalid UTF-8' => $v2 . "\n[0,\"o\",\"\xff\"]\n",
'oversized JSONL line' => $v2 . "\n[0,\"o\",\"" . str_repeat( 'a', CAST_MAX_LINE_BYTES ) . "\"]\n",
'oversized comment line' => $v3 . "\n#" . str_repeat( 'a', CAST_MAX_LINE_BYTES ) . "\n",
'deep JSON' => $v2 . "\n[0,\"o\"," . str_repeat( '[', 20 ) . '0' . str_repeat( ']', 20 ) . "]\n",
) as $description => $contents ) {
same( false, cast_contents_are_valid( $contents ), 'Reject ' . $description . '.' );
}
same( false, is_valid_cast_file( dirname( __DIR__ ) . '/fixtures/malformed.cast' ), 'Reject repository malformed recording.' );
same( false, is_valid_cast_file( '/does-not-exist/asciicast.cast' ), 'Reject missing files.' );
same( false, is_valid_cast_file( __DIR__ ), 'Reject directories.' );
same( false, is_valid_cast_file( 'data://text/plain,' . $v2 ), 'Reject stream wrappers before opening.' );
same( false, is_valid_cast_file( null ), 'Reject missing temporary upload path.' );
same( true, cast_contents_are_valid( $v2 . "\n" . str_repeat( "[0,\"o\",\"x\"]\n", CAST_MAX_EVENTS ) ), 'Accept the documented event-count boundary.' );
same( false, cast_contents_are_valid( $v2 . "\n" . str_repeat( "[0,\"o\",\"x\"]\n", CAST_MAX_EVENTS + 1 ) ), 'Reject excessive event count.' );
same( false, cast_contents_are_valid( json_encode( array_merge( $v1, array( 'title' => str_repeat( 'a', CAST_MAX_V1_BYTES ) ) ), JSON_PRETTY_PRINT ) ), 'Bound whole-document legacy decoding.' );
$path = tempnam( sys_get_temp_dir(), 'ap-cast-' );
try {
$handle = fopen( $path, 'wb' );
ftruncate( $handle, CAST_MAX_BYTES + 1 );
fclose( $handle );
same( false, is_valid_cast_file( $path ), 'Reject files over the byte limit before reading their contents.' );
file_put_contents( $path, $v2 . "\n[0,\"o\",\"ok\"]\n" );
clearstatcache( true, $path );
$upload = array( 'name' => 'recording.cast', 'tmp_name' => $path, 'error' => 0, 'type' => 'text/plain', 'size' => 1 );
same( $upload, validate_cast_upload( $upload ), 'Valid content passes without trusting or changing browser MIME or size.' );
$denied = array( 'ext' => false, 'type' => false, 'proper_filename' => false );
$approved = array( 'ext' => 'cast', 'type' => CAST_MIME, 'proper_filename' => false );
foreach ( array( 'text/plain', 'application/json', 'application/octet-stream', false ) as $detected_mime ) {
same( $approved, check_cast_filetype( $denied, $path, 'recording.cast', null, $detected_mime ), 'Content validation safely handles generic fileinfo guesses.' );
}
same( $approved, check_cast_filetype( $denied, $path, 'recording.CAST' ), 'Uppercase cast extension is supported.' );
same( $denied, check_cast_filetype( $denied, $path, 'recording.cast', array() ), 'An explicitly empty MIME allow-list stays empty.' );
same( $denied, check_cast_filetype( $denied, $path, 'recording.cast', array( 'txt' => 'text/plain' ) ), 'An explicit MIME allow-list excluding cast remains restricted.' );
same( $denied, check_cast_filetype( $denied, $path, 'recording.cast', array( 'cast' => 'text/plain' ) ), 'Only our canonical allowed type can receive the MIME override.' );
$GLOBALS['ap_test']['allowed_mimes'] = array( 'txt' => 'text/plain' );
same( $denied, check_cast_filetype( $denied, $path, 'recording.cast', array( 'cast' => CAST_MIME ) ), 'An explicit allow-list cannot bypass a later global MIME restriction.' );
same( true, is_string( validate_cast_upload( $upload )['error'] ), 'Prefilter also preserves later global MIME restrictions.' );
unset( $GLOBALS['ap_test']['allowed_mimes'] );
$unrelated = array( 'ext' => 'svg', 'type' => 'image/svg+xml', 'proper_filename' => 'x.svg' );
foreach ( array( 'x.json', 'x.html', 'x.svg', 'x.cast.php', "x.cast\n" ) as $filename ) {
same( $unrelated, check_cast_filetype( $unrelated, $path, $filename ), 'Other extensions and double-extension executables remain untouched.' );
}
same( true, is_string( validate_cast_upload( array_merge( $upload, array( 'tmp_name' => '/missing' ) ) )['error'] ), 'Missing temporary upload fails closed.' );
$GLOBALS['ap_test']['capabilities'] = array();
same( true, is_string( validate_cast_upload( $upload )['error'] ), 'Upload permissions are enforced for valid content too.' );
same( $denied, check_cast_filetype( $approved, $path, 'recording.cast' ), 'MIME override never grants upload capability.' );
$GLOBALS['ap_test']['capabilities'] = array( 'upload_files' => true, 'unfiltered_upload' => true );
file_put_contents( $path, $v2 . "\n<script>alert(1)</script>\n" );
clearstatcache( true, $path );
same( true, is_string( validate_cast_upload( $upload )['error'] ), 'Malformed content fails even with unfiltered_upload.' );
same( $denied, check_cast_filetype( $approved, $path, 'recording.cast' ), 'Invalid content cannot keep a previous MIME approval.' );
$other_upload = array_merge( $upload, array( 'name' => 'ordinary.txt' ) );
same( $other_upload, validate_cast_upload( $other_upload ), 'Other extensions keep core upload behavior.' );
$existing_error = array_merge( $upload, array( 'error' => 'Rejected by another plugin.' ) );
same( $existing_error, validate_cast_upload( $existing_error ), 'Existing upload errors are preserved.' );
$php_error = array_merge( $upload, array( 'error' => 3 ) );
same( $php_error, validate_cast_upload( $php_error ), 'PHP partial-upload errors are preserved.' );
} finally {
unlink( $path );
}
unset( $GLOBALS['ap_test']['capabilities'], $GLOBALS['ap_test']['user_capabilities'], $GLOBALS['ap_test']['multisite'], $GLOBALS['ap_test']['site_options'], $GLOBALS['ap_test']['allowed_mimes'] );