Skip to content

Commit

Permalink
Merge pull request #451 from live-codes/php-wasm
Browse files Browse the repository at this point in the history
php-wasm
  • Loading branch information
hatemhosny authored Oct 14, 2023
2 parents 1db73be + 7a23ce8 commit 21102d6
Show file tree
Hide file tree
Showing 18 changed files with 347 additions and 16 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ A [feature-rich](https://livecodes.io/docs/features/), open-source, **client-sid
[![LiveCodes: app version](https://img.shields.io/github/v/release/live-codes/livecodes?label=app)](https://livecodes.io)
[![LiveCodes: npm version](https://img.shields.io/npm/v/livecodes)](https://www.npmjs.com/package/livecodes)
[![LiveCodes: npm downloads](https://img.shields.io/npm/dw/livecodes)](https://www.npmjs.com/package/livecodes)
[![LiveCodes: languages](https://img.shields.io/badge/languages-86-blue)](https://livecodes.io/docs/languages/)
[![LiveCodes: languages](https://img.shields.io/badge/languages-87-blue)](https://livecodes.io/docs/languages/)
[![Codacy Badge](https://app.codacy.com/project/badge/Grade/3d39f15618e048db9d13c2a0e8002b33)](https://www.codacy.com/gh/live-codes/livecodes/dashboard?utm_source=github.com&utm_medium=referral&utm_content=live-codes/livecodes&utm_campaign=Badge_Grade)
[![license - MIT](https://img.shields.io/github/license/live-codes/livecodes)](https://github.com/live-codes/livecodes/blob/develop/LICENSE)
[![LiveCodes: GitHub repo](https://img.shields.io/github/stars/live-codes/livecodes?style=social)](https://github.com/live-codes/livecodes)
Expand Down
87 changes: 87 additions & 0 deletions docs/docs/languages/php-wasm.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# PHP (Wasm)

import LiveCodes from '../../src/components/LiveCodes.tsx';

PHP in Browser, powered by WebAssembly (using [php-wasm](https://github.com/seanmorris/php-wasm)).

`php-wasm` runs PHP in the browser using WebAssembly. This matches the behavior of the official PHP interpreter and allows using PHP's standard library. However, it requires relatively large download and has limited capabilities for client-side DOM manipulation.

:::info Note

If you need a lighter-weight interpreter with more capable client-side DOM manipulation in PHP and do not need to use PHP's standard library, you may want to use the [PHP interpreter written in JavaScript](./php.md).

:::

## Usage

### Standard Library

The PHP standard library is supported.

```php
<?php
phpinfo();
```

<!-- prettier-ignore -->
export const infoConfig = {script: {language: "php-wasm", content: `<?php\n\nphpinfo();`}, activeEditor: "script", mode: "result"};

<LiveCodes config={infoConfig} height="80vh"></LiveCodes>

### JavaScript Interoperability

[JavaScript Interoperability](https://github.com/seanmorris/php-wasm#accessing-the-dom) is achieved via the [VRZNO](https://github.com/seanmorris/vrzno) php extension.

Example:

<!-- prettier-ignore -->
export const jsOpParams = { phpwasm: `<?php\n\n// read from DOM\n$oldTitle = vrzno_eval('document.querySelector("#title").innerText');\necho $oldTitle;\n\n$newTitle = 'Changed@' . date('h:i:s');\n\n// set DOM properties\nvrzno_eval('document.querySelector("#title").innerText = "' . $newTitle . '"' );\n\n// run console.log\nvrzno_eval('console.log("Hello, World!")');\n`, html: `<h1 id="title">Hello, PHP!</h1>\n`, console: 'open' };

<LiveCodes params={jsOpParams} height="80vh"></LiveCodes>

Check the [starter template](#example-usage) for another example.

## Language Info

### Name

`php-wasm`

### Extension

`.wasm.php`

### Alias

`phpwasm`

### Editor

`script`

## Compiler

[php-wasm](https://github.com/seanmorris/php-wasm)

### Version

`php-wasm` v0.0.7, running PHP v8.2.4

## Code Formatting

Using [prettier](https://prettier.io/) and [Prettier PHP Plugin](https://github.com/prettier/plugin-php).

## Example Usage

<LiveCodes template="php-wasm" height="80vh"></LiveCodes>

## Starter Template

https://livecodes.io/?template=php-wasm

## Links

- [PHP](https://php.net/)
- [PHP documentation](https://www.php.net/manual/en/)
- [php-wasm](https://github.com/seanmorris/php-wasm)
- [PHP using Uniter](./php.md) in LiveCodes
59 changes: 58 additions & 1 deletion docs/docs/languages/php.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,60 @@
# PHP

TODO...
import LiveCodes from '../../src/components/LiveCodes.tsx';

PHP running client-side in the browser using [Uniter](https://phptojs.com/).

Uniter is a light-weight PHP-to-JavaScript transpiler and runtime with JavaScript interoperability and client-side DOM manipulation. However, only a small subset of PHP's standard library is supported.

:::info Note

If you need better standard library support, you may want to use [`php-wasm`](./php-wasm.md).

`php-wasm` runs PHP in the browser using WebAssembly. This matches the behavior of the official PHP interpreter and allows using PHP's standard library. However, it requires relatively large download and has limited capabilities for client-side DOM manipulation.

:::

## Usage

### JavaScript Interoperability

Example:

<LiveCodes template="php" height="80vh"></LiveCodes>

## Language Info

### Name

`php`

### Extension

`.php`

### Editor

`script`

## Compiler

[Uniter](https://phptojs.com/)

### Version

Uniter v2.18.0

## Code Formatting

Using [prettier](https://prettier.io/) and [Prettier PHP Plugin](https://github.com/prettier/plugin-php).

## Starter Template

https://livecodes.io/?template=php

## Links

- [PHP](https://php.net/)
- [PHP documentation](https://www.php.net/manual/en/)
- [Uniter](https://phptojs.com/)
- [PHP using `php-wasm`](./php-wasm.md) in LiveCodes
1 change: 1 addition & 0 deletions docs/src/components/LanguageSliders.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ export default function Sliders() {
{ name: 'ruby-wasm', title: 'Ruby (Wasm)' },
{ name: 'go', title: 'Go' },
{ name: 'php', title: 'PHP' },
{ name: 'php-wasm', title: 'PHP (Wasm)' },
{ name: 'cpp', title: 'C++' },
{ name: 'cpp-wasm', title: 'C++ (Wasm)' },
{ name: 'perl', title: 'Perl' },
Expand Down
38 changes: 36 additions & 2 deletions e2e/specs/starter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ test.describe('Starter Templates from UI', () => {

await app.click('[aria-label="Menu"]');
await app.click('text=New');
await app.click('text=Ruby (wasm) Starter');
await app.click('text=Ruby (Wasm) Starter');

await waitForEditorFocus(app);
await waitForResultUpdate();
Expand All @@ -248,7 +248,7 @@ test.describe('Starter Templates from UI', () => {

await app.click('[aria-label="Menu"]');
await app.click('text=New');
await app.click('text=Lua (wasm) Starter');
await app.click('text=Lua (Wasm) Starter');

await waitForEditorFocus(app);
await waitForResultUpdate();
Expand All @@ -265,6 +265,25 @@ test.describe('Starter Templates from UI', () => {
expect(counterText).toBe('You clicked 3 times.');
});

test('php-wasm Starter', async ({ page, getTestUrl, editor }) => {
test.slow();

await page.goto(getTestUrl());

const { app, getResult, waitForResultUpdate } = await getLoadedApp(page);

await app.click('[aria-label="Menu"]');
await app.click('text=New');
await app.click('text=PHP (Wasm) Starter');

await waitForEditorFocus(app);
await waitForResultUpdate();
await app.waitForTimeout(3_000);

const titleText = await getResult().innerText('h1');
expect(titleText).toBe('Hello, PHP!');
});

test('Go Starter', async ({ page, getTestUrl, editor }) => {
test.slow();

Expand Down Expand Up @@ -760,6 +779,21 @@ test.describe('Starter Templates from URL', () => {
expect(counterText).toBe('You clicked 3 times.');
});

test('php-wasm Starter (in URL)', async ({ page, getTestUrl, editor }) => {
test.slow();

await page.goto(getTestUrl({ template: 'php-wasm' }));

const { app, getResult, waitForResultUpdate } = await getLoadedApp(page);

await waitForEditorFocus(app);
await waitForResultUpdate();
await app.waitForTimeout(3_000);

const titleText = await getResult().innerText('h1');
expect(titleText).toBe('Hello, PHP!');
});

test('Go Starter (in URL)', async ({ page, getTestUrl, editor }) => {
test.slow();

Expand Down
1 change: 1 addition & 0 deletions scripts/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,7 @@ const iifeBuild = () =>
'languages/mustache/lang-mustache-compiler.ts',
'languages/nunjucks/lang-nunjucks-compiler.ts',
'languages/perl/lang-perl-script.ts',
'languages/php-wasm/lang-php-wasm-script.ts',
'languages/prolog/lang-prolog-script.ts',
'languages/pug/lang-pug-compiler.ts',
'languages/python-wasm/lang-python-wasm-script.ts',
Expand Down
11 changes: 6 additions & 5 deletions src/livecodes/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -667,13 +667,14 @@ const configureEditorTools = (language: Language) => {

const phpHelper = ({ editor, code }: { editor?: CodeEditor; code?: string }) => {
const addToken = (code: string) => (code.trim().startsWith('<?php') ? code : '<?php\n' + code);
if (code) {
if (code?.trim()) {
return addToken(code);
}
if (editor?.getLanguage() === 'php') {
if (editor?.getLanguage().startsWith('php')) {
editor.setValue(addToken(editor.getValue()));
editor.setPosition({ lineNumber: 2, column: 0 });
}
return;
return '<?php\n';
};

const applyLanguageConfigs = async (language: Language) => {
Expand Down Expand Up @@ -759,8 +760,8 @@ const updateCompiledCode = () => {
Object.keys(cache).forEach((editorId) => {
if (editorId !== getConfig().activeEditor) return;
let compiledCode = cache[editorId].modified || cache[editorId].compiled || '';
if (editorId === 'script' && getConfig().script.language === 'php') {
compiledCode = phpHelper({ code: compiledCode }) || '<?php\n';
if (editorId === 'script' && getConfig().script.language.startsWith('php')) {
compiledCode = phpHelper({ code: compiledCode });
}
toolsPane?.compiled?.update(
compiledLanguages[editorId].language,
Expand Down
25 changes: 25 additions & 0 deletions src/livecodes/html/language-info.html
Original file line number Diff line number Diff line change
Expand Up @@ -825,6 +825,31 @@ <h3>PHP</h3>
<li><a href="?template=php" target="_parent" data-template="php">Load starter template</a></li>
</ul>
</section>
<section data-lang="php-wasm">
<h3>PHP (Wasm)</h3>
<div>PHP in Browser, powered by WebAssembly, using php-wasm.</div>
<ul>
<li><a href="https://www.php.net/" target="_blank" rel="noopener">PHP official website</a></li>
<li>
<a href="https://www.php.net/manual/en/" target="_blank" rel="noopener">PHP documentation</a>
</li>
<li>
<a href="https://github.com/seanmorris/php-wasm" target="_blank" rel="noopener"
>php-wasm GitHub repo</a
>
</li>
<li>
<a href="https://learnxinyminutes.com/docs/php/" target="_blank" rel="noopener"
>Learn X in Y minutes, where X=PHP</a
>
</li>
<li>
<a href="?template=php-wasm" target="_parent" data-template="php-wasm"
>Load starter template</a
>
</li>
</ul>
</section>
<section data-lang="prolog">
<h3>Tau Prolog</h3>
<div>An open source Prolog interpreter in JavaScript.</div>
Expand Down
2 changes: 2 additions & 0 deletions src/livecodes/languages/languages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ import { eta } from './eta';
import { clojurescript } from './clojurescript';
import { rubyWasm } from './ruby-wasm';
import { luaWasm } from './lua-wasm';
import { phpWasm } from './php-wasm';

export const languages: LanguageSpecs[] = [
html,
Expand Down Expand Up @@ -128,6 +129,7 @@ export const languages: LanguageSpecs[] = [
rubyWasm,
go,
php,
phpWasm,
cpp,
cppWasm,
perl,
Expand Down
1 change: 1 addition & 0 deletions src/livecodes/languages/php-wasm/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './lang-php-wasm';
43 changes: 43 additions & 0 deletions src/livecodes/languages/php-wasm/lang-php-wasm-script.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// based on https://github.com/seanmorris/php-wasm/blob/master/source/PhpWeb.js

declare const phpWasm: any;
const php = new phpWasm.PHP();

php.addEventListener('ready', () => {
// set to browser timezone (by default it is set to 'UTC')
const timeZone = window.Intl?.DateTimeFormat?.().resolvedOptions().timeZone || 'UTC';
php.run(`<?php date_default_timezone_set('${timeZone}');`);
});

const runPhpScript = (element: HTMLElement) => {
const inlineCode = element?.innerText?.trim();
if (!inlineCode) return;

const output = document.createElement('div');
element.parentNode?.insertBefore(output, element.nextSibling);
let buffer = '';

php.addEventListener('output', (event: CustomEvent) => (buffer += event.detail));

php.addEventListener('ready', () => {
php.run(inlineCode).then(() => {
output.innerHTML = buffer;
});
});

php.addEventListener('error', (event: CustomEvent) => {
event.detail.forEach((error: string) => {
error = error.trim();
// eslint-disable-next-line no-console
if (error) console.log(error);
});
});
};

addEventListener('load', () => {
const phpSelector = 'script[type="text/php-wasm"]';
const phpNodes = document.querySelectorAll<HTMLElement>(phpSelector);
for (const phpNode of phpNodes) {
runPhpScript(phpNode);
}
});
24 changes: 24 additions & 0 deletions src/livecodes/languages/php-wasm/lang-php-wasm.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import type { LanguageSpecs } from '../../models';
import { parserPlugins } from '../prettier';
import { vendorsBaseUrl } from '../../vendors';

export const phpWasm: LanguageSpecs = {
name: 'php-wasm',
title: 'PHP (Wasm)',
parser: {
name: 'php',
pluginUrls: [parserPlugins.php],
},
compiler: {
factory: () => async (code) => code,
scripts: ({ baseUrl }) => [
vendorsBaseUrl + 'php-wasm/php-wasm.js',
baseUrl + '{{hash:lang-php-wasm-script.js}}',
],
scriptType: 'text/php-wasm',
compiledCodeLanguage: 'php',
},
extensions: ['wasm.php', 'phpwasm'],
editor: 'script',
editorLanguage: 'php',
};
Loading

0 comments on commit 21102d6

Please sign in to comment.