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

* Refresh player with native block editor preview and local assets

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

* Fix emitted frontend boot and verify bundled runtime initialization

* Record verified WordPress 7.1.3 compatibility

* Use WordPress readme major-version compatibility format

* Add responsive player layout, captions and native terminal sizing

* Keep editor caption geometry stable during block selection

* Respect WordPress editor gutters with border-box sizing

* Improve automatic previews and toolbar terminal sizing (1.2.1)

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

* Fix Media Library test storage and scope sidebar selectors

* Document bounded temporary-upload stream exceptions

* Move block explanations into collapsed sidebar help (1.2.3)

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

* Use native RichText labels and supported Chinese HTML language tags in locale tests
This commit is contained in:
2026-10-14 15:56:05 +08:00
committed by GitHub
parent 40e2bf0733
commit 85e5ffa0ec
109 changed files with 32680 additions and 2090 deletions
+105
View File
@@ -0,0 +1,105 @@
# Real WordPress browser integration
These tests run Chromium against WordPress itself. They do not replace WordPress,
PHP rendering, the editor iframe, the media parser, or the player with static mocks.
Recording files are small local fixtures; playback does not depend on a public CDN.
## Run locally (Docker)
Use Node 24 and Docker, then run from the repository root:
```sh
npm ci
npm run build
npm test
npm run package
mkdir -p .wp-env-uploads
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 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
npm run test:e2e
npm run wp-env -- stop
```
The default site is http://localhost:8888 with wp-env's development-only account
`admin` / `password`. Never use these credentials on a public site. `WP_BASE_URL`,
`WP_USERNAME` and `WP_PASSWORD` can override browser-test settings. Set
`PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` to use an already-installed Chromium binary.
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
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.
The host-owned .wp-env-uploads directory keeps real Media Library uploads writable
without relaxing file modes or modifying the fixture files.
## Coverage
- A real iframe editor loads and plays the real local player after applying a URL
- The iframe player actually plays; Space pauses/resumes it and resizing stays inside the canvas
- An inspector speed/theme change rebuilds the player without duplicate instances
- Duplicate, delete, undo, save, reload, and front-end playback preserve the block
- Posts and Pages work, including a mobile-width published Page
- Multiple legacy shortcodes preserve false booleans, hidden controls, and camelCase options
- HTTP 404, malformed asciicast, and an actual no-CORS second origin recover after a valid URL
- Actual terminal output proves successful front-end parsing/playback
- Editor and front-end requests must not load plugin assets from jsDelivr
The preview automatically loads valid saved URLs and debounces typed changes.
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
GitHub Actions checks the minimum WordPress 6.3 / PHP 7.4 combination and the latest
stable WordPress / PHP 8.2. It logs the actual core version, installs the ZIP, and
retains screenshots, failure traces/video, WordPress logs, and the package. A
separate job checks PHP 7.4 and 8.3 syntax and focused regression tests.
Latest WordPress also runs Plugin Check and retains its report as an advisory
step. Advisory output is not a passing directory review. Review any findings
before submission, and do not interpret a green browser job as marketplace
approval. Tests do not cover every browser, theme, or third-party plugin.
WordPress Playground is also usable for local smoke tests when Docker is absent,
but its SQLite/PHP-WASM runtime is additional evidence, not a substitute for the
Docker/MySQL matrix above.
References:
- 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://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.
+457
View File
@@ -0,0 +1,457 @@
import { test, expect } from '@playwright/test';
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
const blockName = 'lamgc/asciiplayer';
const fixturePath = '/wp-content/uploads/asciiplayer-fixtures/hello.cast';
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, postType = 'post') {
await page.goto(`/wp-admin/post-new.php?post_type=${postType}`);
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);
}
});
// A block-pattern picker can appear on a new Page in some core releases.
const closeDialog = page.getByRole('dialog').getByRole('button', { name: /close/i });
if (await closeDialog.count()) await closeDialog.first().click();
await expect(page.locator('iframe[name="editor-canvas"]')).toBeVisible();
}
async function insertPlayer(page, attributes = {}) {
return 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 });
}
function canvas(page) {
return page.frameLocator('iframe[name="editor-canvas"]');
}
function playerBlock(page, clientId) {
return canvas(page).locator(`[data-block="${clientId}"]`);
}
async function readyPreview(block) {
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready');
await expect(block.locator('.asciiplayer-editor__player .ap-wrapper')).toHaveCount(1);
await expect(block.locator('.ap-wrapper')).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 createContent(page, postType, content) {
return page.evaluate(async ({ type, html }) => window.wp.apiFetch({
path: `/wp/v2/${type === 'page' ? 'pages' : 'posts'}`,
method: 'POST',
data: { title: `Asciiplayer integration ${Date.now()}`, status: 'publish', content: html },
}), { type: postType, html: content });
}
async function expectFrontendPlayer(container) {
await expect(container.locator('.ap-wrapper')).toBeVisible();
// This starts actual playback and checks parsed terminal output. Merely
// finding the player's outer DOM would miss fetch/CORS/parser failures.
const start = container.locator('.ap-overlay-start .ap-play-button');
if (await start.isVisible()) await start.click();
await expect(container).toContainText('Hello from wp-asciiplayer');
}
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.beforeEach(async ({ page }) => {
await logIn(page);
});
test('real iframe preview survives edits, duplicate, delete, undo, save and reload', async ({ page }, testInfo) => {
const cdnRequests = [];
const pageErrors = [];
page.on('request', (request) => {
if (new URL(request.url()).hostname.endsWith('jsdelivr.net')) cdnRequests.push(request.url());
});
page.on('pageerror', (error) => pageErrors.push(error.message));
await openEditor(page);
const source = new URL(fixturePath, page.url()).href;
const id = await insertPlayer(page);
const block = playerBlock(page, id);
await block.getByRole('textbox', { name: 'Recording URL', exact: true }).fill(source);
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
await readyPreview(block);
await block.locator('.ap-overlay-start .ap-play-button').click();
await expect(block.locator('.ap-term-text')).toContainText('Hello from wp-asciiplayer');
const playback = block.locator('.ap-playback-button');
await expect(playback).toHaveAttribute('aria-label', 'Pause');
await block.locator('.ap-term-text').press('Space');
await expect(playback).toHaveAttribute('aria-label', 'Play');
await block.locator('.ap-term-text').press('Space');
await expect(playback).toHaveAttribute('aria-label', 'Pause');
await block.locator('.ap-term-text').press('Space');
await page.setViewportSize({ width: 900, height: 800 });
await expect(block.locator('.ap-wrapper')).toBeVisible();
const canvasWidth = await page.locator('iframe[name="editor-canvas"]').evaluate((element) => element.clientWidth);
await expect.poll(async () => (await block.locator('.ap-wrapper').boundingBox()).width).toBeLessThanOrEqual(canvasWidth);
await page.setViewportSize({ width: 1280, height: 720 });
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
// Exercise a real inspector input; data-store operations below cover core's
// block lifecycle without depending on changing toolbar/menu copy.
const speed = page.getByRole('spinbutton', { name: 'Playback speed', exact: true });
await speed.fill('1.5');
await speed.press('Tab');
await expect.poll(() => page.evaluate((clientId) =>
window.wp.data.select('core/block-editor').getBlockAttributes(clientId).speed, id
)).toBe(1.5);
await readyPreview(block);
await page.getByRole('combobox', { name: 'Theme', exact: true }).selectOption('solarized-dark');
await readyPreview(block);
await expect(block.locator('.ap-player')).toHaveClass(/asciinema-player-theme-solarized-dark/);
const duplicateId = await page.evaluate(async (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;
}, id);
await readyPreview(playerBlock(page, duplicateId));
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 expect(canvas(page).locator('.asciiplayer-editor__player .ap-wrapper')).toHaveCount(1);
await page.evaluate(() => window.wp.data.dispatch('core/editor').undo());
await readyPreview(playerBlock(page, duplicateId));
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);
const saved = await publish(page, 'Inline preview lifecycle integration');
await screenshot(page, testInfo, 'real-wordpress-editor');
await page.reload();
await page.waitForFunction(() => window.wp?.data?.select('core/block-editor')?.getBlocks().length > 0);
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.attributes).toMatchObject({ source, speed: 1.5, theme: 'solarized-dark' });
await readyPreview(playerBlock(page, reloaded.clientId));
await page.goto(saved.url);
const container = page.locator('.asciiplayer-container');
await expect(container).toHaveCount(1);
expect(JSON.parse(await container.getAttribute('data-ap-options'))).toMatchObject({ speed: 1.5, theme: 'solarized-dark' });
await expectFrontendPlayer(container);
await screenshot(page, testInfo, 'real-wordpress-post');
expect(cdnRequests, 'No plugin runtime may be loaded from jsDelivr').toEqual([]);
expect(pageErrors).toEqual([]);
});
test('a published Page plays its block at desktop and mobile widths', async ({ page }, testInfo) => {
await openEditor(page, 'page');
const source = new URL(fixturePath, page.url()).href;
const id = await insertPlayer(page, { source, controls: 'always', preload: true });
await readyPreview(playerBlock(page, id));
const saved = await publish(page, 'Page playback integration');
await page.goto(saved.url);
const container = page.locator('.asciiplayer-container');
await expectFrontendPlayer(container);
await page.setViewportSize({ width: 375, height: 812 });
await expect(container.locator('.ap-wrapper')).toBeVisible();
const bounds = await container.locator('.ap-wrapper').boundingBox();
expect(bounds.width).toBeLessThanOrEqual(375);
await screenshot(page, testInfo, 'real-wordpress-page-mobile');
});
for (const postType of ['post', 'page']) {
test(`legacy shortcodes play multiple recordings on a ${postType}`, async ({ page }) => {
await openEditor(page, postType);
const source = new URL(fixturePath, page.url()).href;
const content = `[asciiplayer controls="false" autoPlay="true" startAt="0.1" idleTimeLimit="1" speed="1.5" loop="false" style="max-width: 640px;"]${source}[/asciiplayer]\n` +
`[asciiplayer controls="true" theme="solarized-dark" preload="true"]${source}[/asciiplayer]`;
const saved = await createContent(page, postType, content);
await page.goto(saved.link);
const containers = page.locator('.asciiplayer-container');
await expect(containers).toHaveCount(2);
const options = JSON.parse(await containers.nth(0).getAttribute('data-ap-options'));
expect(options).toMatchObject({ autoPlay: true, startAt: 0.1, idleTimeLimit: 1, speed: 1.5, loop: false });
expect(options.controls).toBe(false);
const otherOptions = JSON.parse(await containers.nth(1).getAttribute('data-ap-options'));
expect(otherOptions.controls).toBe(true);
await expectFrontendPlayer(containers.nth(0));
await expect(containers.nth(0).locator('.ap-control-bar')).toHaveCount(0);
await expectFrontendPlayer(containers.nth(1));
});
}
for (const filename of ['missing.cast', 'malformed.cast']) {
test(`a ${filename} recording produces a recoverable inline error`, async ({ page }) => {
const pageErrors = [];
page.on('pageerror', (error) => pageErrors.push(error.message));
await openEditor(page);
const source = new URL(`/wp-content/uploads/asciiplayer-fixtures/${filename}`, page.url()).href;
const id = await insertPlayer(page);
const block = playerBlock(page, id);
await block.getByRole('textbox', { name: 'Recording URL', exact: true }).fill(source);
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'error');
await expect(block).toContainText('Unable to load the recording.');
await expect(block.getByRole('button', { name: 'Retry preview', exact: true })).toBeVisible();
await block.getByRole('textbox', { name: 'Recording URL', exact: true }).fill(new URL(fixturePath, page.url()).href);
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
await readyPreview(block);
expect(pageErrors).toEqual([]);
});
}
test('a real cross-origin server without CORS permission shows an error and recovers', async ({ page }) => {
const recording = await readFile(new URL('../fixtures/hello.cast', import.meta.url));
const server = createServer((_request, response) => {
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.end(recording);
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
try {
await openEditor(page);
const id = await insertPlayer(page);
const block = playerBlock(page, id);
const address = server.address();
const crossOriginSource = `http://127.0.0.1:${address.port}/hello.cast`;
await block.getByRole('textbox', { name: 'Recording URL', exact: true }).fill(crossOriginSource);
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'error');
await expect(block).toContainText('CORS permissions');
await block.getByRole('textbox', { name: 'Recording URL', exact: true }).fill(new URL(fixturePath, page.url()).href);
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
await readyPreview(block);
} finally {
server.closeAllConnections();
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);
});