diff --git a/package-lock.json b/package-lock.json index 01c9eb8b2de..c55d9f48198 100644 --- a/package-lock.json +++ b/package-lock.json @@ -34,6 +34,7 @@ "@preact/signals-react": "1.3.6", "@reduxjs/toolkit": "2.6.1", "@types/xml2js": "0.4.14", + "@uiw/react-codemirror": "4.23.0", "@wordpress/dataviews": "4.5.0", "@zip.js/zip.js": "2.7.57", "ajv": "8.12.0", @@ -111,6 +112,7 @@ "docusaurus-plugin-typedoc-api": "^4.4.0", "dts-bundle-generator": "^7.2.0", "esbuild": "0.19.9", + "esbuild-wasm": "0.20.1", "eslint": "9.24.0", "eslint-plugin-comment-length": "2.2.1", "eslint-plugin-cypress": "4.3.0", @@ -134,6 +136,7 @@ "react-markdown": "^8.0.7", "rimraf": "^4.4.0", "rollup": "^4.34.6", + "sass": "1.71.1", "tar-fs": "3.1.1", "ts-jest": "29.1.0", "ts-json-schema-generator": "1.2.0", @@ -2670,6 +2673,18 @@ "@marijn/find-cluster-break": "^1.0.0" } }, + "node_modules/@codemirror/theme-one-dark": { + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/@codemirror/theme-one-dark/-/theme-one-dark-6.1.3.tgz", + "integrity": "sha512-NzBdIvEJmx6fjeremiGp3t/okrLPYT0d9orIc7AFun8oZcRk58aejkqhv6spnz4MLAevrKNPMQYXEWMg4s+sKA==", + "license": "MIT", + "dependencies": { + "@codemirror/language": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.0.0", + "@lezer/highlight": "^1.0.0" + } + }, "node_modules/@codemirror/view": { "version": "6.38.3", "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.38.3.tgz", @@ -15026,6 +15041,59 @@ "url": "https://opencollective.com/eslint" } }, + "node_modules/@uiw/codemirror-extensions-basic-setup": { + "version": "4.23.0", + "resolved": "https://registry.npmjs.org/@uiw/codemirror-extensions-basic-setup/-/codemirror-extensions-basic-setup-4.23.0.tgz", + "integrity": "sha512-+k5nkRpUWGaHr1JWT8jcKsVewlXw5qBgSopm9LW8fZ6KnSNZBycz8kHxh0+WSvckmXEESGptkIsb7dlkmJT/hQ==", + "license": "MIT", + "dependencies": { + "@codemirror/autocomplete": "^6.0.0", + "@codemirror/commands": "^6.0.0", + "@codemirror/language": "^6.0.0", + "@codemirror/lint": "^6.0.0", + "@codemirror/search": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.0.0" + }, + "funding": { + "url": "https://jaywcjlove.github.io/#/sponsor" + }, + "peerDependencies": { + "@codemirror/autocomplete": ">=6.0.0", + "@codemirror/commands": ">=6.0.0", + "@codemirror/language": ">=6.0.0", + "@codemirror/lint": ">=6.0.0", + "@codemirror/search": ">=6.0.0", + "@codemirror/state": ">=6.0.0", + "@codemirror/view": ">=6.0.0" + } + }, + "node_modules/@uiw/react-codemirror": { + "version": "4.23.0", + "resolved": "https://registry.npmjs.org/@uiw/react-codemirror/-/react-codemirror-4.23.0.tgz", + "integrity": "sha512-MnqTXfgeLA3fsUUQjqjJgemEuNyoGALgsExVm0NQAllAAi1wfj+IoKFeK+h3XXMlTFRCFYOUh4AHDv0YXJLsOg==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.18.6", + "@codemirror/commands": "^6.1.0", + "@codemirror/state": "^6.1.1", + "@codemirror/theme-one-dark": "^6.0.0", + "@uiw/codemirror-extensions-basic-setup": "4.23.0", + "codemirror": "^6.0.0" + }, + "funding": { + "url": "https://jaywcjlove.github.io/#/sponsor" + }, + "peerDependencies": { + "@babel/runtime": ">=7.11.0", + "@codemirror/state": ">=6.0.0", + "@codemirror/theme-one-dark": ">=6.0.0", + "@codemirror/view": ">=6.0.0", + "codemirror": ">=6.0.0", + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, "node_modules/@ungap/structured-clone": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz", @@ -20260,6 +20328,21 @@ "node": ">= 0.12.0" } }, + "node_modules/codemirror": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/codemirror/-/codemirror-6.0.2.tgz", + "integrity": "sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw==", + "license": "MIT", + "dependencies": { + "@codemirror/autocomplete": "^6.0.0", + "@codemirror/commands": "^6.0.0", + "@codemirror/language": "^6.0.0", + "@codemirror/lint": "^6.0.0", + "@codemirror/search": "^6.0.0", + "@codemirror/state": "^6.0.0", + "@codemirror/view": "^6.0.0" + } + }, "node_modules/collapse-white-space": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/collapse-white-space/-/collapse-white-space-2.1.0.tgz", @@ -23071,6 +23154,19 @@ "@esbuild/win32-x64": "0.19.9" } }, + "node_modules/esbuild-wasm": { + "version": "0.20.1", + "resolved": "https://registry.npmjs.org/esbuild-wasm/-/esbuild-wasm-0.20.1.tgz", + "integrity": "sha512-6v/WJubRsjxBbQdz6izgvx7LsVFvVaGmSdwrFHmEzoVgfXL89hkKPoQHsnVI2ngOkcBUQT9kmAM1hVL1k/Av4A==", + "dev": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + } + }, "node_modules/escalade": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", @@ -26822,6 +26918,13 @@ "url": "https://opencollective.com/immer" } }, + "node_modules/immutable": { + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/immutable/-/immutable-4.3.7.tgz", + "integrity": "sha512-1hqclzwYwjRDFLjcFxOM5AYkkG0rpFPpr1RLPMEuGczoS7YA8gLhy8SWXYRAA/XwfEHpfo3cw5JGioS32fnMRw==", + "dev": true, + "license": "MIT" + }, "node_modules/import-fresh": { "version": "3.3.1", "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", @@ -42389,6 +42492,24 @@ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "license": "MIT" }, + "node_modules/sass": { + "version": "1.71.1", + "resolved": "https://registry.npmjs.org/sass/-/sass-1.71.1.tgz", + "integrity": "sha512-wovtnV2PxzteLlfNzbgm1tFXPLoZILYAMJtvoXXkD7/+1uP41eKkIt1ypWq5/q2uT94qHjXehEYfmjKOvjL9sg==", + "dev": true, + "license": "MIT", + "dependencies": { + "chokidar": ">=3.0.0 <4.0.0", + "immutable": "^4.0.0", + "source-map-js": ">=0.6.2 <2.0.0" + }, + "bin": { + "sass": "sass.js" + }, + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/sax": { "version": "1.4.3", "resolved": "https://registry.npmjs.org/sax/-/sax-1.4.3.tgz", @@ -49775,7 +49896,10 @@ }, "packages/playground/website-extras": { "name": "@wp-playground/website-extras", - "version": "0.0.1" + "version": "0.0.1", + "devDependencies": { + "@wordpress/a11y": "4.36.0" + } }, "packages/playground/wordpress": { "name": "@wp-playground/wordpress", diff --git a/package.json b/package.json index e647b5c8dc0..2085058ccb3 100644 --- a/package.json +++ b/package.json @@ -72,6 +72,7 @@ "private": true, "dependencies": { "@codemirror/autocomplete": "6.19.0", + "@uiw/react-codemirror": "4.23.0", "@codemirror/commands": "6.8.1", "@codemirror/lang-css": "6.3.1", "@codemirror/lang-html": "6.4.10", @@ -166,6 +167,7 @@ "docusaurus-plugin-typedoc-api": "^4.4.0", "dts-bundle-generator": "^7.2.0", "esbuild": "0.19.9", + "esbuild-wasm": "0.20.1", "eslint": "9.24.0", "eslint-plugin-comment-length": "2.2.1", "eslint-plugin-cypress": "4.3.0", @@ -189,6 +191,7 @@ "react-markdown": "^8.0.7", "rimraf": "^4.4.0", "rollup": "^4.34.6", + "sass": "1.71.1", "tar-fs": "3.1.1", "ts-jest": "29.1.0", "ts-json-schema-generator": "1.2.0", diff --git a/packages/playground/website-extras/package.json b/packages/playground/website-extras/package.json index 4623ed92223..37f2fe94dc2 100644 --- a/packages/playground/website-extras/package.json +++ b/packages/playground/website-extras/package.json @@ -2,5 +2,8 @@ "version": "0.0.1", "type": "commonjs", "private": true, - "name": "@wp-playground/website-extras" + "name": "@wp-playground/website-extras", + "devDependencies": { + "@wordpress/a11y": "4.36.0" + } } diff --git a/packages/playground/website-extras/playground-block-frame.html b/packages/playground/website-extras/playground-block-frame.html new file mode 100644 index 00000000000..9d93cb0e823 --- /dev/null +++ b/packages/playground/website-extras/playground-block-frame.html @@ -0,0 +1,36 @@ + + + + + WordPress Playground Demo + + + + + + + + + + + + + +
+ + + diff --git a/packages/playground/website-extras/playwright/e2e/playground-block-frame.spec.ts b/packages/playground/website-extras/playwright/e2e/playground-block-frame.spec.ts new file mode 100644 index 00000000000..15918705b74 --- /dev/null +++ b/packages/playground/website-extras/playwright/e2e/playground-block-frame.spec.ts @@ -0,0 +1,183 @@ +/** + * E2E tests for the playground-block-frame.html page. + * + * This page provides an interactive code editor with live WordPress Playground preview, + * supporting multi-file editing with syntax highlighting, JSX transpilation with + * esbuild-wasm, and URL parameter support for sharing configurations. + */ + +import { test, expect } from '../playground-block-fixtures'; + +/** + * Test 1: Simple Code Editor (PHP Plugin) + * + * Shows a basic PHP plugin with code editor and live preview side-by-side. + * The plugin outputs "Hello from the plugin" in the WordPress frontend. + */ +test.describe('Simple Code Editor (PHP Plugin)', () => { + const simplePluginUrl = + './playground-block-frame.html?playground-full-page=&playground-attributes=eyJjb2RlRWRpdG9yIjp0cnVlLCJjb2RlRWRpdG9yVHJhbnNwaWxlSnN4IjpmYWxzZSwiZmlsZXMiOlsiVzNzaWJtRnRaU0k2SW5Cc2RXZHBiaTV3YUhBaUxDSmpiMjUwWlc1MGN5STZJandcL2NHaHdYRzR2S2lwY2JpQXFJRkJzZFdkcGJpQk9ZVzFsT2lCWGIzSmtVSEpsYzNNZ1JHVnRieUJRYkhWbmFXNWNiaUFxTDF4dVhHNWhaR1JmWVdOMGFXOXVLQ2QzY0Y5b1pXRmtKeXdnWm5WdVkzUnBiMjRvS1NCN1hHNGdJQ0FnWldOb2J5QW5QR2d4UGtobGJHeHZJR1p5YjIwZ2RHaGxJSEJzZFdkcGJqd3ZhREUrUEdKeVBqeGljajQ4WW5JK1BHSnlQaWM3WEc1OUtUdGNiaUo5WFE9PSJdLCJjb2RlRWRpdG9yU2lkZUJ5U2lkZSI6dHJ1ZSwiY29kZUVkaXRvck11bHRpcGxlRmlsZXMiOmZhbHNlLCJjb2RlRWRpdG9yTW9kZSI6InBsdWdpbiIsImxvZ0luVXNlciI6dHJ1ZSwiY29uZmlndXJhdGlvblNvdXJjZSI6ImJsb2NrLWF0dHJpYnV0ZXMiLCJyZXF1aXJlTGl2ZVByZXZpZXdBY3RpdmF0aW9uIjpmYWxzZSwiY29uc3RhbnRzIjp7ImEiOiJiIn19'; + + test('should display code editor with PHP plugin code', async ({ + playgroundBlock, + }) => { + await playgroundBlock.goto(simplePluginUrl); + + // Verify the code editor is visible + await playgroundBlock.waitForCodeEditor(); + const isEditorVisible = await playgroundBlock.isCodeEditorVisible(); + expect(isEditorVisible).toBe(true); + + // Verify the editor contains the plugin code + const editorContent = await playgroundBlock.getCodeEditorContent(); + expect(editorContent).toContain('Plugin Name'); + expect(editorContent).toContain('add_action'); + }); + + test('should render WordPress with plugin output', async ({ + playgroundBlock, + wordpress, + }) => { + await playgroundBlock.goto(simplePluginUrl); + + // Verify WordPress is loaded and shows the plugin output + await expect(wordpress.locator('body')).toContainText( + 'Hello from the plugin', + { timeout: 60000 } + ); + }); + + test('should display side-by-side layout', async ({ playgroundBlock }) => { + await playgroundBlock.goto(simplePluginUrl); + + // Verify both code editor and preview are visible (side-by-side mode) + await playgroundBlock.waitForCodeEditor(); + const codeEditor = playgroundBlock.page.locator('.cm-editor'); + const playgroundIframe = + playgroundBlock.page.locator('.playground-iframe'); + + await expect(codeEditor).toBeVisible(); + await expect(playgroundIframe).toBeVisible(); + }); +}); + +/** + * Test 2: JSX Transpilation (Interactive React Counter) + * + * Demonstrates JSX transpilation with a multi-file plugin containing a React component. + * The plugin registers a shortcode that renders a React component greeting. + */ +test.describe('JSX Transpilation', () => { + const jsxPluginUrl = + './playground-block-frame.html?playground-full-page=&playground-attributes=eyJjb2RlRWRpdG9yIjp0cnVlLCJjb2RlRWRpdG9yVHJhbnNwaWxlSnN4Ijp0cnVlLCJmaWxlcyI6WyJXM3NpYm1GdFpTSTZJbkJzZFdkcGJpNXdhSEFpTENKamIyNTBaVzUwY3lJNklqdy9jR2h3WEc0dktpcGNiaUFxSUZCc2RXZHBiaUJPWVcxbE9pQktVMWdnUkdWdGJ5QlFiSFZuYVc1Y2JpQXFJRVJsYzJOeWFYQjBhVzl1T2lCRVpXMXZibk4wY21GMFpYTWdTbE5ZSUhSeVlXNXpjR2xzWVhScGIyNGdhVzRnVjI5eVpGQnlaWE56SUZCc1lYbG5jbTkxYm1SY2JpQXFMMXh1WEc1aFpHUmZZV04wYVc5dUtDZDNjRjlsYm5GMVpYVmxYM05qY21sd2RITW5MQ0JtZFc1amRHbHZiaWdwSUh0Y2JpQWdJQ0IzY0Y5bGJuRjFaWFZsWDNOamNtbHdkQ2hjYmlBZ0lDQWdJQ0FnSjJwemVDMWtaVzF2Snl4Y2JpQWdJQ0FnSUNBZ2NHeDFaMmx1YzE5MWNtd29KM1pwWlhjdWFuTW5MQ0JmWDBaSlRFVmZYeWtzWEc0Z0lDQWdJQ0FnSUdGeWNtRjVLQ2QzY0MxbGJHVnRaVzUwSnlrc1hHNGdJQ0FnSUNBZ0lDY3hMakFuTEZ4dUlDQWdJQ0FnSUNCMGNuVmxYRzRnSUNBZ0tUdGNibjBwTzF4dVhHNWhaR1JmYzJodmNuUmpiMlJsS0NkcWMzaGZaR1Z0Ynljc0lHWjFibU4wYVc5dUtDa2dlMXh1SUNBZ0lISmxkSFZ5YmlBblBHUnBkaUJwWkQxY0ltcHplQzFrWlcxdkxYSnZiM1JjSWo0OEwyUnBkajRuTzF4dWZTazdYRzRpZlN4N0ltNWhiV1VpT2lKMmFXVjNMbXB6SWl3aVkyOXVkR1Z1ZEhNaU9pSmpiMjV6ZENCN0lHTnlaV0YwWlVWc1pXMWxiblFzSUhKbGJtUmxjaUI5SUQwZ2QzQXVaV3hsYldWdWREdGNibHh1WTI5dWMzUWdSM0psWlhScGJtY2dQU0FvZXlCdVlXMWxJSDBwSUQwK0lDaGNiaUFnSUNBOFpHbDJJSE4wZVd4bFBYdDdJSEJoWkdScGJtYzZJQ2N5TUhCNEp5d2dZbUZqYTJkeWIzVnVaRG9nSnlObU1HWXdaakFuTENCaWIzSmtaWEpTWVdScGRYTTZJQ2M0Y0hnbkxDQnRZWEpuYVc0NklDY3lNSEI0SURBbklIMTlQbHh1SUNBZ0lDQWdJQ0E4YURJK1NHVnNiRzhnWm5KdmJTQktVMWdoUEM5b01qNWNiaUFnSUNBZ0lDQWdQSEErVkdocGN5QmpiMjF3YjI1bGJuUWdkMkZ6SUhSeVlXNXpjR2xzWldRZ1puSnZiU0JoSUR4emRISnZibWMrTG1welBDOXpkSEp2Ym1jK0lHWnBiR1VnZDJsMGFDQktVMWdnYzNsdWRHRjRMand2Y0Q1Y2JpQWdJQ0FnSUNBZ1BIQStWMlZzWTI5dFpTd2dlMjVoYldWOUlUd3ZjRDVjYmlBZ0lDQThMMlJwZGo1Y2JpazdYRzVjYm1SdlkzVnRaVzUwTG1Ga1pFVjJaVzUwVEdsemRHVnVaWElvSjBSUFRVTnZiblJsYm5STWIyRmtaV1FuTENBb0tTQTlQaUI3WEc0Z0lDQWdZMjl1YzNRZ2NtOXZkQ0E5SUdSdlkzVnRaVzUwTG1kbGRFVnNaVzFsYm5SQ2VVbGtLQ2RxYzNndFpHVnRieTF5YjI5MEp5azdYRzRnSUNBZ2FXWWdLSEp2YjNRcElIdGNiaUFnSUNBZ0lDQWdjbVZ1WkdWeUtEeEhjbVZsZEdsdVp5QnVZVzFsUFZ3aVYyOXlaRkJ5WlhOeklFUmxkbVZzYjNCbGNsd2lJQzgrTENCeWIyOTBLVHRjYmlBZ0lDQjlYRzU5S1R0Y2JpSjlYUT09Il0sImNvZGVFZGl0b3JTaWRlQnlTaWRlIjp0cnVlLCJjb2RlRWRpdG9yTXVsdGlwbGVGaWxlcyI6dHJ1ZSwiY29kZUVkaXRvck1vZGUiOiJwbHVnaW4iLCJsb2dJblVzZXIiOnRydWUsImxhbmRpbmdQYWdlVXJsIjoiLz9wPTEiLCJjcmVhdGVOZXdQb3N0Ijp0cnVlLCJjcmVhdGVOZXdQb3N0VHlwZSI6InBvc3QiLCJjcmVhdGVOZXdQb3N0VGl0bGUiOiJKU1ggRGVtbyIsImNyZWF0ZU5ld1Bvc3RDb250ZW50IjoiW2pzeF9kZW1vXSIsInJlZGlyZWN0VG9Qb3N0Ijp0cnVlLCJyZWRpcmVjdFRvUG9zdFR5cGUiOiJmcm9udCIsImNvbmZpZ3VyYXRpb25Tb3VyY2UiOiJibG9jay1hdHRyaWJ1dGVzIiwicmVxdWlyZUxpdmVQcmV2aWV3QWN0aXZhdGlvbiI6ZmFsc2V9'; + + test('should display code editor with multiple file tabs', async ({ + playgroundBlock, + }) => { + await playgroundBlock.goto(jsxPluginUrl); + + // Verify the code editor is visible + await playgroundBlock.waitForCodeEditor(); + const isEditorVisible = await playgroundBlock.isCodeEditorVisible(); + expect(isEditorVisible).toBe(true); + + // Verify multiple file tabs are present + // Use a specific button selector for file tabs + const tabs = playgroundBlock.page.locator('button.file-tab'); + const tabCount = await tabs.count(); + // Should have at least 2 file tabs for the multi-file JSX example + expect(tabCount).toBeGreaterThanOrEqual(2); + }); + + test('should transpile JSX and render React component', async ({ + playgroundBlock, + wordpress, + }) => { + await playgroundBlock.goto(jsxPluginUrl); + + // Verify WordPress is loaded with the transpiled React component + // The JSX component renders "Hello from JSX!" and a greeting message + await expect(wordpress.locator('body')).toContainText( + 'Hello from JSX', + { + timeout: 120000, + } + ); + }); + + test('should contain JSX syntax in the view.js file', async ({ + playgroundBlock, + }) => { + await playgroundBlock.goto(jsxPluginUrl); + + await playgroundBlock.waitForCodeEditor(); + + // Click on view.js tab + const viewJsTab = playgroundBlock.page.locator( + 'button.file-tab[aria-label="File: view.js"]' + ); + await viewJsTab.click(); + await playgroundBlock.page.waitForTimeout(500); + + // Verify the editor contains JSX syntax + const editorContent = await playgroundBlock.getCodeEditorContent(); + // JSX files contain createElement or JSX syntax like
+ expect( + editorContent.includes('createElement') || + editorContent.includes(' { + const playgroundOnlyUrl = + './playground-block-frame.html?playground-full-page&playground-attributes=eyJjb2RlRWRpdG9yIjpmYWxzZSwiY29kZUVkaXRvclJlYWRPbmx5IjpmYWxzZSwiY29kZUVkaXRvclNpZGVCeVNpZGUiOmZhbHNlLCJjb2RlRWRpdG9yVHJhbnNwaWxlSnN4IjpmYWxzZSwiY29kZUVkaXRvck11bHRpcGxlRmlsZXMiOmZhbHNlLCJjb2RlRWRpdG9yTW9kZSI6InBsdWdpbiIsImxvZ0luVXNlciI6dHJ1ZSwibGFuZGluZ1BhZ2VVcmwiOiIvd3AtYWRtaW4vIiwiY3JlYXRlTmV3UG9zdCI6ZmFsc2UsImNyZWF0ZU5ld1Bvc3RUeXBlIjoicG9zdCIsImNyZWF0ZU5ld1Bvc3RUaXRsZSI6IiIsImNyZWF0ZU5ld1Bvc3RDb250ZW50IjoiIiwicmVkaXJlY3RUb1Bvc3QiOmZhbHNlLCJyZWRpcmVjdFRvUG9zdFR5cGUiOiJmcm9udCIsImJsdWVwcmludCI6IiIsImJsdWVwcmludFVybCI6IiIsImNvbmZpZ3VyYXRpb25Tb3VyY2UiOiJibG9jay1hdHRyaWJ1dGVzIiwicmVxdWlyZUxpdmVQcmV2aWV3QWN0aXZhdGlvbiI6ZmFsc2UsImNvZGVFZGl0b3JFcnJvckxvZyI6ZmFsc2UsImNvbnN0YW50cyI6ImUzMD0iLCJmaWxlcyI6W119'; + + test('should not display code editor', async ({ playgroundBlock }) => { + await playgroundBlock.goto(playgroundOnlyUrl); + + // Verify the code editor is NOT visible + const codeEditor = playgroundBlock.page.locator('.cm-editor'); + await expect(codeEditor).not.toBeVisible({ timeout: 10000 }); + }); + + test('should display only WordPress Playground', async ({ + playgroundBlock, + wordpress, + }) => { + await playgroundBlock.goto(playgroundOnlyUrl); + + // Verify WordPress admin is loaded (landing page is /wp-admin/) + await expect(wordpress.locator('body')).toContainText('Dashboard', { + timeout: 60000, + }); + }); + + test('should have full-width playground viewport', async ({ + playgroundBlock, + }) => { + await playgroundBlock.goto(playgroundOnlyUrl); + + // Verify the playground viewport takes up significant space + // (no code editor taking up half the screen) + const playgroundIframe = + playgroundBlock.page.locator('.playground-iframe'); + await expect(playgroundIframe).toBeVisible(); + + const boundingBox = await playgroundIframe.boundingBox(); + expect(boundingBox).not.toBeNull(); + if (boundingBox) { + // The viewport should take most of the page width (at least 80% of viewport) + const pageWidth = await playgroundBlock.page.evaluate( + () => window.innerWidth + ); + expect(boundingBox.width).toBeGreaterThan(pageWidth * 0.8); + } + }); +}); diff --git a/packages/playground/website-extras/playwright/playground-block-fixtures.ts b/packages/playground/website-extras/playwright/playground-block-fixtures.ts new file mode 100644 index 00000000000..2de6edbc456 --- /dev/null +++ b/packages/playground/website-extras/playwright/playground-block-fixtures.ts @@ -0,0 +1,113 @@ +import type { FrameLocator, Page } from '@playwright/test'; +import { test as base, expect } from '@playwright/test'; + +type PlaygroundBlockFixtures = { + /** + * The WordPress iframe inside the playground viewport. + */ + wordpress: FrameLocator; + /** + * A helper class to interact with the playground block frame page. + */ + playgroundBlock: PlaygroundBlockPage; +}; + +export class PlaygroundBlockPage { + public readonly page: Page; + + constructor(page: Page) { + this.page = page; + } + + /** + * Wait for WordPress to fully load inside the Playground iframe. + * WordPress Playground can take a while to boot, so we use a generous timeout. + * + * The iframe structure is: + * 1. Main page: playground-block-frame.html + * 2. First iframe: .playground-iframe (which loads remote.html) + * 3. Second iframe (inside remote.html): #wp (the actual WordPress site) + */ + async waitForWordPressIframe(page = this.page) { + await expect( + page + .frameLocator('.playground-iframe') + .frameLocator('#wp') + .locator('body') + ).not.toBeEmpty({ timeout: 120000 }); + } + + /** + * Get the WordPress iframe locator. + */ + wordpress(page = this.page) { + return page.frameLocator('.playground-iframe').frameLocator('#wp'); + } + + /** + * Navigate to a URL and wait for WordPress to load. + * URLs should be relative to the baseURL configured in playwright.config.ts + */ + async goto(url: string, options?: any) { + // Resolve relative URLs against the baseURL + const baseURL = + process.env.PLAYWRIGHT_TEST_BASE_URL || + 'http://127.0.0.1:6400/website-extras/'; + const resolvedUrl = url.startsWith('./') + ? baseURL + url.slice(2) + : url.startsWith('/') + ? baseURL + url.slice(1) + : url; + + const response = await this.page.goto(resolvedUrl, options); + await this.waitForWordPressIframe(); + return response; + } + + /** + * Check if the code editor is visible. + */ + async isCodeEditorVisible(): Promise { + const editor = this.page.locator('.cm-editor'); + return editor.isVisible(); + } + + /** + * Get the code editor content. + */ + async getCodeEditorContent(): Promise { + const cmContent = this.page.locator('.cm-content'); + return cmContent.innerText(); + } + + /** + * Wait for the code editor to be ready. + */ + async waitForCodeEditor() { + await expect(this.page.locator('.cm-editor')).toBeVisible({ + timeout: 30000, + }); + } + + /** + * Click the Run button to apply changes. + */ + async clickRunButton() { + const runButton = this.page.getByRole('button', { name: /Run/i }); + await runButton.click(); + } +} + +export const test = base.extend({ + wordpress: async ({ page }, use) => { + const wpFrame = page + .frameLocator('.playground-iframe') + .frameLocator('#wp'); + await use(wpFrame); + }, + playgroundBlock: async ({ page }, use) => { + await use(new PlaygroundBlockPage(page)); + }, +}); + +export { expect } from '@playwright/test'; diff --git a/packages/playground/website-extras/playwright/playwright.config.ts b/packages/playground/website-extras/playwright/playwright.config.ts new file mode 100644 index 00000000000..5cf3afb2e02 --- /dev/null +++ b/packages/playground/website-extras/playwright/playwright.config.ts @@ -0,0 +1,44 @@ +import type { PlaywrightTestConfig } from '@playwright/test'; +import { defineConfig, devices } from '@playwright/test'; + +const baseURL = + process.env.PLAYWRIGHT_TEST_BASE_URL || + 'http://127.0.0.1:6400/website-extras/'; + +export const playwrightConfig: PlaywrightTestConfig = { + testDir: './e2e', + fullyParallel: true, + forbidOnly: !!process.env.CI, + retries: 3, + workers: 3, + reporter: [['html'], ['list', { printSteps: true }]], + use: { + baseURL, + trace: 'on-first-retry', + actionTimeout: 120000, + navigationTimeout: 120000, + }, + + timeout: 300000, + expect: { timeout: 60000 }, + + projects: [ + { + name: 'chromium', + use: { + ...devices['Desktop Chrome'], + launchOptions: { + args: ['--js-flags=--enable-experimental-webassembly-jspi'], + }, + }, + }, + ], + + webServer: { + command: 'npx nx run playground-website-extras:dev', + url: 'http://127.0.0.1:6400/website-extras/', + reuseExistingServer: !process.env.CI, + }, +}; + +export default defineConfig(playwrightConfig); diff --git a/packages/playground/website-extras/project.json b/packages/playground/website-extras/project.json index 0771f6b25ee..5e6d3a6837f 100644 --- a/packages/playground/website-extras/project.json +++ b/packages/playground/website-extras/project.json @@ -84,6 +84,13 @@ "tsc -p packages/playground/website-extras/tsconfig.app.json --noEmit" ] } + }, + "e2e": { + "executor": "nx:run-commands", + "options": { + "cwd": "packages/playground/website-extras/playwright", + "commands": ["npx playwright test"] + } } }, "tags": ["scope:web-client"] diff --git a/packages/playground/website-extras/src/playground-block-demo/base64.ts b/packages/playground/website-extras/src/playground-block-demo/base64.ts new file mode 100644 index 00000000000..eeb81fe955b --- /dev/null +++ b/packages/playground/website-extras/src/playground-block-demo/base64.ts @@ -0,0 +1,171 @@ +/** + * Base64 encoding/decoding utilities for playground block attributes. + * + * These functions handle Unicode-safe Base64 conversion, which the native + * browser btoa/atob functions don't support reliably. By converting strings + * to Uint8Arrays first, we ensure proper encoding of special characters. + */ + +export type EditorFile = { + name: string; + contents: string; + remoteUrl?: string; +}; + +export type Attributes = { + codeEditor: boolean; + codeEditorReadOnly: boolean; + codeEditorSideBySide: boolean; + codeEditorTranspileJsx: boolean; + codeEditorMultipleFiles: boolean; + codeEditorMode: string; + logInUser: boolean; + landingPageUrl: string; + createNewPost: boolean; + createNewPostType: string; + createNewPostTitle: string; + createNewPostContent: string; + redirectToPost: boolean; + redirectToPostType: string; + blueprint: string; + files?: EditorFile[]; + constants: Record; + codeEditorErrorLog: boolean; + blueprintUrl: string; + configurationSource: + | 'block-attributes' + | 'blueprint-url' + | 'blueprint-json'; + requireLivePreviewActivation: boolean; +}; + +const attributesToBase64 = [ + 'blueprint', + 'blueprintUrl', + 'codeEditorErrorLog', + 'constants', + 'files', +]; + +/** + * Convert a string to a Uint8Array using UTF-8 encoding. + */ +function stringToUint8Array(str: string): Uint8Array { + return new TextEncoder().encode(str); +} + +/** + * Convert a Uint8Array to a string using UTF-8 decoding. + */ +function uint8ArrayToString(arr: Uint8Array): string { + return new TextDecoder().decode(arr); +} + +/** + * Convert a Uint8Array to a Base64 string. + */ +function uint8ArrayToBase64(arr: Uint8Array): string { + let binary = ''; + for (let i = 0; i < arr.byteLength; i++) { + binary += String.fromCharCode(arr[i]); + } + return window.btoa(binary); +} + +/** + * Convert a Base64 string to a Uint8Array. + */ +function base64ToUint8Array(base64: string): Uint8Array { + const binary = window.atob(base64); + const arr = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) { + arr[i] = binary.charCodeAt(i); + } + return arr; +} + +/** + * Convert a string to Base64 (Unicode-safe). + */ +export function stringToBase64(str: string): string { + return uint8ArrayToBase64(stringToUint8Array(str)); +} + +/** + * Convert a Base64 string back to a regular string (Unicode-safe). + */ +export function base64ToString(base64: string): string { + return uint8ArrayToString(base64ToUint8Array(base64)); +} + +/** + * Encode block attributes to Base64 for storage/transmission. + * Only specific attributes are encoded (those in attributesToBase64). + */ +export function base64EncodeBlockAttributes( + attributes: Record +): Record { + const result: Record = {}; + + for (const [key, value] of Object.entries(attributes)) { + if (attributesToBase64.includes(key)) { + if (key === 'files' && Array.isArray(value)) { + // Wrap files array as base64 JSON string in an array + result[key] = [stringToBase64(JSON.stringify(value))]; + } else if (typeof value === 'string') { + result[key] = stringToBase64(value); + } else if (typeof value === 'object' && value !== null) { + result[key] = stringToBase64(JSON.stringify(value)); + } else { + result[key] = value; + } + } else { + result[key] = value; + } + } + + return result; +} + +/** + * Turns base64 encoded attributes back into their original form. + * It never throws, bales out early if we can't decode, and always + * returns a valid object. If any attribute cannot be decoded, it + * will be kept in its original form and presumed to have a non-base64 + * value to keep the older version of the block working without + * migrating the attributes. + * + * @param base64Attributes + * @returns + */ +export function base64DecodeBlockAttributes( + base64Attributes: Record +): Attributes { + const attributes: Record = {}; + for (const key in base64Attributes) { + let valueToDecode = base64Attributes[key]; + // The "files" attribute is of type array + if (key === 'files') { + valueToDecode = valueToDecode[0]; + } + if ( + !attributesToBase64.includes(key) || + !(typeof valueToDecode === 'string') + ) { + attributes[key] = base64Attributes[key]; + continue; + } + if (key in base64Attributes) { + try { + attributes[key] = JSON.parse(base64ToString(valueToDecode)); + } catch { + // Ignore errors and keep the base64 encoded string. + // Note this will also preserve any non-base64 encoded values. + // This is intentional as it seems to make more sense than + // throwing an error and breaking the block. + attributes[key] = base64Attributes[key]; + } + } + } + return attributes as Attributes; +} diff --git a/packages/playground/website-extras/src/playground-block-demo/components/playground-preview/download-zipped-package.ts b/packages/playground/website-extras/src/playground-block-demo/components/playground-preview/download-zipped-package.ts new file mode 100644 index 00000000000..3d952663b1e --- /dev/null +++ b/packages/playground/website-extras/src/playground-block-demo/components/playground-preview/download-zipped-package.ts @@ -0,0 +1,78 @@ +/** + * Utility for downloading plugin/theme files as a ZIP archive. + * + * Uses PHP's ZipArchive to create the ZIP file inside WordPress Playground, + * then downloads it to the user's machine. + */ + +import type { PlaygroundClient } from '@wp-playground/client'; + +export default async function downloadZippedPackage( + client: PlaygroundClient, + codeEditorMode: string +) { + const docroot = await client.documentRoot; + const isTheme = codeEditorMode === 'theme'; + const path = isTheme + ? `${docroot}/wp-content/themes/demo-theme` + : `${docroot}/wp-content/plugins/demo-plugin`; + const filename = isTheme ? 'demo-theme.zip' : 'demo-plugin.zip'; + + const zipBuffer = await zipPlaygroundFiles(client, path); + const blob = new Blob([zipBuffer], { type: 'application/zip' }); + downloadFile(blob, filename); +} + +async function zipPlaygroundFiles( + client: PlaygroundClient, + path: string +): Promise { + const zipPath = '/tmp/package.zip'; + + // Remove existing zip file if present + try { + await client.unlink(zipPath); + } catch { + // File doesn't exist, that's fine + } + + // Create ZIP using PHP's ZipArchive + await client.run({ + code: `open('${zipPath}', ZipArchive::CREATE | ZipArchive::OVERWRITE); + + $path = '${path}'; + $iterator = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS), + RecursiveIteratorIterator::SELF_FIRST + ); + + foreach ($iterator as $file) { + $filePath = $file->getRealPath(); + $relativePath = substr($filePath, strlen($path) + 1); + + if ($file->isDir()) { + $zip->addEmptyDir($relativePath); + } else { + $zip->addFile($filePath, $relativePath); + } + } + + $zip->close(); + `, + }); + + return await client.readFileAsBuffer(zipPath); +} + +function downloadFile(blob: Blob, filename: string) { + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = filename; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); +} diff --git a/packages/playground/website-extras/src/playground-block-demo/components/playground-preview/file-management-modals.tsx b/packages/playground/website-extras/src/playground-block-demo/components/playground-preview/file-management-modals.tsx new file mode 100644 index 00000000000..473b04d9f80 --- /dev/null +++ b/packages/playground/website-extras/src/playground-block-demo/components/playground-preview/file-management-modals.tsx @@ -0,0 +1,230 @@ +/** + * File management modals for creating and renaming files. + * + * Provides modal dialogs for adding new files and editing file names, + * with support for remote URL file sources. + */ + +import { + useState, + useImperativeHandle, + forwardRef, + type ForwardedRef, +} from 'react'; +import type { EditorFile } from '../../base64'; +import { __ } from '../../i18n'; +import type { EditorFileMapper } from './use-editor-files'; + +interface FileManagementModalsProps { + updateFile: (mapper: EditorFileMapper, index?: number) => void; + addFile: (file: EditorFile, index?: number) => void; + setActiveFileIndex: (index: number) => void; + files: EditorFile[]; + activeFileIndex: number; +} + +export interface FileManagerRef { + setEditFileNameModalOpen: (open: boolean) => void; + setNewFileModalOpen: (open: boolean) => void; +} + +interface FileNameModalProps { + isOpen: boolean; + onClose: () => void; + onSubmit: (name: string, remoteUrl?: string) => void; + initialName?: string; + initialRemoteUrl?: string; + title: string; + submitLabel: string; + isLoading?: boolean; + error?: string | null; +} + +function FileNameModal({ + isOpen, + onClose, + onSubmit, + initialName = '', + initialRemoteUrl = '', + title, + submitLabel, + isLoading = false, + error = null, +}: FileNameModalProps) { + const [name, setName] = useState(initialName); + const [remoteUrl, setRemoteUrl] = useState(initialRemoteUrl); + + if (!isOpen) return null; + + const handleSubmit = (e: React.FormEvent) => { + e.preventDefault(); + onSubmit(name, remoteUrl || undefined); + }; + + return ( +
+
e.stopPropagation()} + role="dialog" + aria-modal="true" + aria-labelledby="modal-title" + > + +
+
+ + setName(e.target.value)} + placeholder="example.php" + autoFocus + disabled={isLoading} + /> +
+
+ + setRemoteUrl(e.target.value)} + placeholder="https://example.com/file.php" + disabled={isLoading} + /> +

+ {__( + 'If provided, the file contents will be fetched from this URL.' + )} +

+
+ {error &&

{error}

} +
+ + +
+
+
+
+ ); +} + +const FileManagementModals = forwardRef(function FileManagementModals( + { + updateFile, + addFile, + setActiveFileIndex, + files, + activeFileIndex, + }: FileManagementModalsProps, + ref: ForwardedRef +) { + const [editFileNameModalOpen, setEditFileNameModalOpen] = useState(false); + const [newFileModalOpen, setNewFileModalOpen] = useState(false); + const [isDownloading, setIsDownloading] = useState(false); + const [downloadError, setDownloadError] = useState(null); + + useImperativeHandle(ref, () => ({ + setEditFileNameModalOpen: (open: boolean) => { + setDownloadError(null); + setEditFileNameModalOpen(open); + }, + setNewFileModalOpen: (open: boolean) => { + setDownloadError(null); + setNewFileModalOpen(open); + }, + })); + + async function resolveFileContents(remoteUrl?: string): Promise { + if (!remoteUrl) return ''; + const response = await fetch(remoteUrl, { credentials: 'omit' }); + if (!response.ok) { + throw new Error(`Failed to fetch: ${response.statusText}`); + } + return await response.text(); + } + + async function handleUpdateFile(name: string, remoteUrl?: string) { + setIsDownloading(true); + setDownloadError(null); + try { + const contents = await resolveFileContents(remoteUrl); + updateFile((file) => ({ + ...file, + name, + remoteUrl, + contents: remoteUrl ? contents : file.contents, + })); + setEditFileNameModalOpen(false); + } catch (error) { + setDownloadError( + error instanceof Error ? error.message : 'Failed to fetch file' + ); + } finally { + setIsDownloading(false); + } + } + + async function handleCreateFile(name: string, remoteUrl?: string) { + setIsDownloading(true); + setDownloadError(null); + try { + const contents = await resolveFileContents(remoteUrl); + addFile({ name, contents, remoteUrl }); + setActiveFileIndex(files.length); + setNewFileModalOpen(false); + } catch (error) { + setDownloadError( + error instanceof Error ? error.message : 'Failed to fetch file' + ); + } finally { + setIsDownloading(false); + } + } + + const activeFile = files[activeFileIndex]; + + return ( + <> + setEditFileNameModalOpen(false)} + onSubmit={handleUpdateFile} + initialName={activeFile?.name || ''} + initialRemoteUrl={activeFile?.remoteUrl || ''} + title={__('Edit File Name')} + submitLabel={__('Save')} + isLoading={isDownloading} + error={downloadError} + /> + setNewFileModalOpen(false)} + onSubmit={handleCreateFile} + title={__('New File')} + submitLabel={__('Create')} + isLoading={isDownloading} + error={downloadError} + /> + + ); +}); + +export default FileManagementModals; diff --git a/packages/playground/website-extras/src/playground-block-demo/components/playground-preview/icons.tsx b/packages/playground/website-extras/src/playground-block-demo/components/playground-preview/icons.tsx new file mode 100644 index 00000000000..6fbddbff45a --- /dev/null +++ b/packages/playground/website-extras/src/playground-block-demo/components/playground-preview/icons.tsx @@ -0,0 +1,122 @@ +/** + * SVG icon components. + * + * These replace the @wordpress/icons package for standalone use. + */ + +interface IconProps { + className?: string; + size?: number; +} + +export function IconPlus({ className, size = 24 }: IconProps) { + return ( + + ); +} + +export function IconDownload({ className, size = 24 }: IconProps) { + return ( + + ); +} + +export function IconCancel({ className, size = 24 }: IconProps) { + return ( + + ); +} + +export function IconWordPress({ className, size = 24 }: IconProps) { + return ( + + ); +} + +export function IconEdit({ className, size = 24 }: IconProps) { + return ( + + ); +} + +export function IconLink({ className, size = 24 }: IconProps) { + return ( + + ); +} + +export function IconPlay({ className, size = 24 }: IconProps) { + return ( + + ); +} diff --git a/packages/playground/website-extras/src/playground-block-demo/components/playground-preview/index.tsx b/packages/playground/website-extras/src/playground-block-demo/components/playground-preview/index.tsx new file mode 100644 index 00000000000..063028cff6d --- /dev/null +++ b/packages/playground/website-extras/src/playground-block-demo/components/playground-preview/index.tsx @@ -0,0 +1,751 @@ +/** + * PlaygroundPreview component. + * + * This is an interactive code editor integrated with WordPress Playground's + * live preview functionality. It supports multi-file editing with syntax + * highlighting, JSX transpilation, and real-time WordPress preview. + * + * Adapted from the WordPress Playground Block plugin to work as a standalone + * React component without WordPress dependencies. + */ + +import { useEffect, useRef, useState, useId } from 'react'; +import ReactCodeMirror from '@uiw/react-codemirror'; +import { keymap, EditorView } from '@codemirror/view'; +import { html } from '@codemirror/lang-html'; +import { css } from '@codemirror/lang-css'; +import { javascript } from '@codemirror/lang-javascript'; +import { json } from '@codemirror/lang-json'; +import { php } from '@codemirror/lang-php'; +import type { LanguageSupport } from '@codemirror/language'; +import { + startPlaygroundWeb, + type PlaygroundClient, + phpVar, +} from '@wp-playground/client'; + +import useEditorFiles, { isErrorLogFile } from './use-editor-files'; +import { writePluginFiles } from './write-plugin-files'; +import { writeThemeFiles } from './write-theme-files'; +import downloadZippedPackage from './download-zipped-package'; +import FileManagementModals, { + type FileManagerRef, +} from './file-management-modals'; +import { + transpilePluginFiles, + type TranspilationFailure, +} from './transpile-plugin-files'; +import { __, _x, sprintf } from '../../i18n'; +import { + base64EncodeBlockAttributes, + stringToBase64, + type Attributes, + type EditorFile, +} from '../../base64'; +import { + IconPlus, + IconDownload, + IconCancel, + IconWordPress, + IconEdit, + IconLink, + IconPlay, +} from './icons'; +import { speak } from '@wordpress/a11y'; + +export type PlaygroundDemoProps = Partial & { + showAddNewFile?: boolean; + showFileControls?: boolean; + inFullPageView?: boolean; + baseAttributesForFullPageView?: Record; + onStateChange?: (state: { + client: PlaygroundClient | null; + postId: number; + files: EditorFile[]; + }) => void; +}; + +const languages: Record = { + css: css(), + html: html(), + js: javascript(), + jsx: javascript({ jsx: true }), + json: json(), + php: php(), +}; + +function getLanguageExtensions(extension: string): LanguageSupport[] { + return extension in languages ? [languages[extension]] : []; +} + +/** + * Playground's `goTo` method doesn't work when the URL is the same as the + * current URL. This function returns a URL that forces a refresh by adding + * or removing a query parameter. + */ +function getRefreshPath(lastPath: string): string { + const url = new URL(lastPath, 'https://playground.wordpress.net'); + if (url.searchParams.has('__playground_refresh')) { + url.searchParams.delete('__playground_refresh'); + } else { + url.searchParams.set('__playground_refresh', '1'); + } + return url.pathname + url.search; +} + +function classNames( + ...args: (string | Record | undefined)[] +): string { + const classes: string[] = []; + for (const arg of args) { + if (typeof arg === 'string') { + classes.push(arg); + } else if (typeof arg === 'object' && arg !== null) { + for (const [key, value] of Object.entries(arg)) { + if (value) classes.push(key); + } + } + } + return classes.join(' '); +} + +export default function PlaygroundPreview({ + blueprint = '', + blueprintUrl = '', + configurationSource = 'block-attributes', + codeEditor = true, + codeEditorMode = 'plugin', + codeEditorSideBySide = true, + codeEditorReadOnly = false, + codeEditorTranspileJsx = false, + codeEditorErrorLog = false, + constants = {}, + logInUser = true, + createNewPost = false, + createNewPostType = 'post', + createNewPostTitle = _x( + 'New post', + 'default title of new post created by blueprint' + ), + createNewPostContent = '', + redirectToPost = false, + redirectToPostType = 'front', + landingPageUrl = '/', + files: filesAttribute = [], + showAddNewFile = false, + showFileControls = false, + requireLivePreviewActivation = true, + inFullPageView = false, + baseAttributesForFullPageView = {}, + onStateChange, +}: PlaygroundDemoProps) { + const { + files, + addFile, + isLoading: isFilesLoading, + updateFile, + removeFile, + activeFile, + activeFileIndex, + setActiveFileIndex, + } = useEditorFiles(filesAttribute || [], { + withErrorLog: codeEditorErrorLog, + getErrors: async () => + (await playgroundClientRef.current?.readFileAsText( + '/internal/stderr' + )) || '', + }); + + const runButtonDescId = useId(); + const activateButtonDescId = useId(); + + const iframeRef = useRef(null); + const beforePreviewRef = useRef(null); + const afterPreviewRef = useRef(null); + const playgroundClientRef = useRef(null); + const fileMgrRef = useRef(null); + const downloadButtonRef = useRef(null); + const codeMirrorRef = useRef<{ view?: EditorView }>(null); + + // Prevent CodeMirror keyboard shortcuts from propagating + useEffect(() => { + if (!codeMirrorRef.current?.view) return; + + const view = codeMirrorRef.current.view; + function stopPropagation(event: KeyboardEvent) { + event.stopPropagation(); + } + view.dom.addEventListener('keydown', stopPropagation); + view.dom.addEventListener('keypress', stopPropagation); + view.dom.addEventListener('keyup', stopPropagation); + return () => { + view.dom.removeEventListener('keydown', stopPropagation); + view.dom.removeEventListener('keyup', stopPropagation); + view.dom.removeEventListener('keypress', stopPropagation); + }; + }, []); + + const [isLivePreviewActivated, setLivePreviewActivated] = useState( + !requireLivePreviewActivation + ); + const [currentPostId, setCurrentPostId] = useState(0); + const [isPlaygroundReady, setIsPlaygroundReady] = useState(false); + + const dismissedExitWithKeyboardTipKey = + 'playground-block-dismiss-exit-editor-tip'; + const [dismissedExitWithKeyboardTip, setDismissedExitWithKeyboardTip] = + useState( + typeof localStorage !== 'undefined' && + localStorage[dismissedExitWithKeyboardTipKey] === 'true' + ); + + function dismissExitWithKeyboardTip() { + if (downloadButtonRef?.current) { + downloadButtonRef.current.focus(); + } + if (typeof localStorage !== 'undefined') { + localStorage[dismissedExitWithKeyboardTipKey] = 'true'; + } + setDismissedExitWithKeyboardTip(true); + speak(__('Notice dismissed.'), 'polite'); + } + + // Notify parent component of state changes + useEffect(() => { + onStateChange?.({ + client: playgroundClientRef.current, + postId: currentPostId, + files, + }); + }, [playgroundClientRef.current, currentPostId, files, onStateChange]); + + const currentFileExtension = activeFile?.name.split('.').pop() || ''; + + // Initialize Playground when live preview is activated + useEffect(() => { + async function initPlayground() { + if (!isLivePreviewActivated) return; + if (!iframeRef.current) return; + + let finalBlueprint: object | undefined = undefined; + try { + if (configurationSource === 'blueprint-json') { + if (blueprint) { + finalBlueprint = JSON.parse(blueprint); + } + } else if (configurationSource === 'blueprint-url') { + if (blueprintUrl) { + finalBlueprint = await fetch(blueprintUrl).then((res) => + res.json() + ); + } + } else { + finalBlueprint = { + preferredVersions: { + wp: 'latest', + php: '7.4', + }, + steps: [ + { + step: 'defineWpConfigConsts', + consts: constants, + }, + logInUser && { + step: 'login', + username: 'admin', + password: 'password', + }, + ].filter(Boolean), + }; + } + } catch (e) { + // eslint-disable-next-line no-console + console.error('Failed to parse blueprint:', e); + } + + const configuration: { + iframe: HTMLIFrameElement; + remoteUrl: string; + blueprint?: object; + } = { + iframe: iframeRef.current, + remoteUrl: 'https://playground.wordpress.net/remote.html', + }; + if (finalBlueprint) { + configuration.blueprint = finalBlueprint; + } + + // eslint-disable-next-line no-console + console.log('Initializing Playground'); + const client = await startPlaygroundWeb(configuration); + await client.isReady(); + playgroundClientRef.current = client; + setIsPlaygroundReady(true); + + // Delay the announcement to let iframe loading announcements finish first + setTimeout( + () => speak(__('WordPress Playground loaded.'), 'polite'), + 500 + ); + + await reinstallEditedCode(); + + if (configurationSource === 'block-attributes') { + let postId = 0; + if (createNewPost) { + const docroot = await client.documentRoot; + const { text: newPostId } = await client.run({ + code: ` ${phpVar(createNewPostTitle)}, + 'post_content' => ${phpVar(createNewPostContent)}, + 'post_status' => 'publish', + 'post_type' => ${phpVar(createNewPostType)}, + ]); + + echo $post_id; + `, + }); + + setCurrentPostId(parseInt(newPostId)); + postId = parseInt(newPostId); + } + const redirectUrl = getLandingPageUrl(postId); + await client.goTo(redirectUrl); + } else if (!finalBlueprint) { + await client.goTo('/'); + } + } + + initPlayground(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [isLivePreviewActivated]); + + function getFullPageUrl(): string { + const fullPageUrl = new URL(window.location.href); + fullPageUrl.search = '?playground-full-page'; + + const fullPageAttributes = { + ...baseAttributesForFullPageView, + requireLivePreviewActivation: false, + files: files.filter((f) => !isErrorLogFile(f)), + }; + + const encodedFullPageAttributes = stringToBase64( + JSON.stringify(base64EncodeBlockAttributes(fullPageAttributes)) + ); + fullPageUrl.searchParams.append( + 'playground-attributes', + encodedFullPageAttributes + ); + + return fullPageUrl.toString(); + } + + function getLandingPageUrl(postId: number = currentPostId): string { + if (createNewPost && redirectToPost) { + if (redirectToPostType === 'front') { + return `/?p=${postId}`; + } else if (redirectToPostType === 'admin') { + return `/wp-admin/post.php?post=${postId}&action=edit`; + } + } + return landingPageUrl; + } + + const [transpilationFailures, setTranspilationFailures] = useState< + TranspilationFailure[] + >([]); + + async function reinstallEditedCode() { + if (!playgroundClientRef.current || !codeEditor) return; + + setTranspilationFailures([]); + + const client = playgroundClientRef.current; + let finalFiles = files; + + if (codeEditorTranspileJsx) { + const { failures, transpiledFiles } = + await transpilePluginFiles(finalFiles); + if (failures.length) { + for (const failure of failures) { + // eslint-disable-next-line no-console + console.error( + `Failed to transpile ${failure.file.name}:`, + failure.error + ); + } + setTranspilationFailures(failures); + return; + } + finalFiles = transpiledFiles; + } + + if (codeEditorMode === 'theme') { + await writeThemeFiles(client, finalFiles); + } else { + await writePluginFiles(client, finalFiles); + } + } + + async function handleReRunCode() { + if (!isLivePreviewActivated) { + setLivePreviewActivated(true); + } else { + await reinstallEditedCode(); + const lastPath = await playgroundClientRef.current!.getCurrentURL(); + await playgroundClientRef.current!.goTo(getRefreshPath(lastPath)); + } + } + + const keymapExtension = keymap.of([ + { + key: 'Mod-s', + run() { + handleReRunCode(); + return true; + }, + }, + ]); + + const mainContainerClass = classNames( + 'wordpress-playground-main-container', + { + 'is-full-page-view': inFullPageView, + } + ); + + const contentContainerClass = classNames( + 'wordpress-playground-content-container', + { + 'is-one-under-another': !codeEditorSideBySide, + 'is-side-by-side': codeEditorSideBySide, + } + ); + + const activeStatusLabel = isPlaygroundReady ? __('Loaded') : __('Loading'); + const inactiveStatusLabel = __('Not Activated'); + const beforePlaygroundPreviewLabel = sprintf( + __('Beginning of Playground Preview - %s'), + isLivePreviewActivated ? activeStatusLabel : inactiveStatusLabel + ); + + return ( +
+
+ {codeEditor && ( +
+ +
+ {isFilesLoading ? ( +
+ {' '} + {__('Loading files...')} +
+ ) : ( + files.map((file, index) => ( + + )) + )} + {showAddNewFile && ( + + )} + +
+ {!dismissedExitWithKeyboardTip && ( + + )} +
+ + updateFile((file) => ({ + ...file, + contents: value, + })) + } + /> +
+
+ {showFileControls ? ( +
+ {activeFile && + !isErrorLogFile(activeFile) && ( + + )} + {!isErrorLogFile(activeFile) && + files.filter( + (file) => !isErrorLogFile(file) + ).length > 1 && ( + + )} +
+ ) : ( +
+ )} + + {requireLivePreviewActivation && + !isLivePreviewActivated && ( + + {__( + 'This button runs the code in the Preview iframe. If the Preview iframe has not yet been activated, this button creates the Preview iframe which contains a full WordPress website and may be a challenge for screen readers.' + )} + + )} +
+
+ )} +
+ {!inFullPageView && ( + <> + + {beforePlaygroundPreviewLabel} + + + + )} + {!isLivePreviewActivated && ( +
+ + + {__( + 'This button creates the Preview iframe containing a full WordPress website which may be a challenge for screen readers.' + )} + +
+ )} + {transpilationFailures.length > 0 && ( +
+

{__('Transpilation Error')}

+

+ {__( + 'There were errors while transpiling the code. Please fix the errors and try again.' + )} +

+
    + {transpilationFailures.map( + ({ file, error }) => ( +
  • + {file.name} +

    {error.message}

    +
  • + ) + )} +
+
+ )} + {isLivePreviewActivated && ( +