mirror of
https://github.com/pyscript/pyscript.git
synced 2025-12-20 10:47:35 -05:00
Compare commits
77 Commits
when-updat
...
2025.10.3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a8684a2168 | ||
|
|
f8cf58d6c4 | ||
|
|
8cd9c4c382 | ||
|
|
1f609233e7 | ||
|
|
66966a732e | ||
|
|
ec090922cb | ||
|
|
f769f215b2 | ||
|
|
ffc78ab6a2 | ||
|
|
b609b605f5 | ||
|
|
100a1e4bc1 | ||
|
|
c848061a44 | ||
|
|
2647e78480 | ||
|
|
482d57c27c | ||
|
|
4ce989acf3 | ||
|
|
1e62d0b1fe | ||
|
|
2d3ad0ab2d | ||
|
|
3657492c52 | ||
|
|
a8b8e1de36 | ||
|
|
726009029a | ||
|
|
8b35304ab4 | ||
|
|
9e4cb44d73 | ||
|
|
4bf3651c9a | ||
|
|
67fa31e4ea | ||
|
|
4937a46731 | ||
|
|
b4e9a3093c | ||
|
|
a129be8136 | ||
|
|
eaa6711756 | ||
|
|
b528ba67a9 | ||
|
|
71ad1a40cb | ||
|
|
e433275938 | ||
|
|
87256a662b | ||
|
|
7336ae545e | ||
|
|
d68260c0c7 | ||
|
|
14cc05fb80 | ||
|
|
42c6cb775e | ||
|
|
b11fb2e893 | ||
|
|
3223a9c7e9 | ||
|
|
139ce9b5fb | ||
|
|
3b1af0688c | ||
|
|
7284f7f15f | ||
|
|
16ebc50481 | ||
|
|
b911ea99fb | ||
|
|
46ca9154c4 | ||
|
|
afd7a8eb00 | ||
|
|
b22f384d73 | ||
|
|
caeab77a8e | ||
|
|
f2bbc6ed5f | ||
|
|
1d666b92a2 | ||
|
|
290eb03388 | ||
|
|
55031f2347 | ||
|
|
8168383653 | ||
|
|
3ff2c171bc | ||
|
|
edbac13713 | ||
|
|
46239caa19 | ||
|
|
0366e48fad | ||
|
|
b13317d32f | ||
|
|
57b1440a10 | ||
|
|
fc53356a1d | ||
|
|
5be99456f0 | ||
|
|
7adedcc704 | ||
|
|
d143b229ed | ||
|
|
0d74a60227 | ||
|
|
ce923a354f | ||
|
|
7e65836423 | ||
|
|
796373cfa6 | ||
|
|
0a1d3bb678 | ||
|
|
4e43d3e92d | ||
|
|
5acc2afaf3 | ||
|
|
56c64cbee7 | ||
|
|
4ff02a24d1 | ||
|
|
a5dc94792b | ||
|
|
0db79e0f02 | ||
|
|
283eabdb30 | ||
|
|
3f19e00410 | ||
|
|
9233d5e45a | ||
|
|
fe580cd90b | ||
|
|
00e6cfed29 |
4
.github/workflows/prepare-release.yml
vendored
4
.github/workflows/prepare-release.yml
vendored
@@ -14,10 +14,10 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v5
|
||||||
|
|
||||||
- name: Install node
|
- name: Install node
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v5
|
||||||
with:
|
with:
|
||||||
node-version: 20.x
|
node-version: 20.x
|
||||||
|
|
||||||
|
|||||||
6
.github/workflows/publish-release.yml
vendored
6
.github/workflows/publish-release.yml
vendored
@@ -16,10 +16,10 @@ jobs:
|
|||||||
contents: read
|
contents: read
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v5
|
||||||
|
|
||||||
- name: Install node
|
- name: Install node
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v5
|
||||||
with:
|
with:
|
||||||
node-version: 20.x
|
node-version: 20.x
|
||||||
|
|
||||||
@@ -66,7 +66,7 @@ jobs:
|
|||||||
run: tar -cvf ../release.tar * && mv ../release.tar .
|
run: tar -cvf ../release.tar * && mv ../release.tar .
|
||||||
|
|
||||||
- name: Configure AWS credentials
|
- name: Configure AWS credentials
|
||||||
uses: aws-actions/configure-aws-credentials@v4
|
uses: aws-actions/configure-aws-credentials@v5
|
||||||
with:
|
with:
|
||||||
aws-region: ${{ secrets.AWS_REGION }}
|
aws-region: ${{ secrets.AWS_REGION }}
|
||||||
role-to-assume: ${{ secrets.AWS_OIDC_RUNNER_ROLE }}
|
role-to-assume: ${{ secrets.AWS_OIDC_RUNNER_ROLE }}
|
||||||
|
|||||||
6
.github/workflows/publish-snapshot.yml
vendored
6
.github/workflows/publish-snapshot.yml
vendored
@@ -20,10 +20,10 @@ jobs:
|
|||||||
id-token: write
|
id-token: write
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v5
|
||||||
|
|
||||||
- name: Install node
|
- name: Install node
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v5
|
||||||
with:
|
with:
|
||||||
node-version: 20.x
|
node-version: 20.x
|
||||||
|
|
||||||
@@ -62,7 +62,7 @@ jobs:
|
|||||||
run: npm run build
|
run: npm run build
|
||||||
|
|
||||||
- name: Configure AWS credentials
|
- name: Configure AWS credentials
|
||||||
uses: aws-actions/configure-aws-credentials@v4
|
uses: aws-actions/configure-aws-credentials@v5
|
||||||
with:
|
with:
|
||||||
aws-region: ${{ secrets.AWS_REGION }}
|
aws-region: ${{ secrets.AWS_REGION }}
|
||||||
role-to-assume: ${{ secrets.AWS_OIDC_RUNNER_ROLE }}
|
role-to-assume: ${{ secrets.AWS_OIDC_RUNNER_ROLE }}
|
||||||
|
|||||||
6
.github/workflows/publish-unstable.yml
vendored
6
.github/workflows/publish-unstable.yml
vendored
@@ -21,10 +21,10 @@ jobs:
|
|||||||
working-directory: ./core
|
working-directory: ./core
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v5
|
||||||
|
|
||||||
- name: Install node
|
- name: Install node
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v5
|
||||||
with:
|
with:
|
||||||
node-version: 20.x
|
node-version: 20.x
|
||||||
|
|
||||||
@@ -67,7 +67,7 @@ jobs:
|
|||||||
run: sed -e 's#_PATH_#./#' -e 's#_DOC_VERSION_#latest#' -e 's#_TAG_VERSION_##' -e 's#_VERSION_#latest#' ./public/index.html > ./core/dist/index.html
|
run: sed -e 's#_PATH_#./#' -e 's#_DOC_VERSION_#latest#' -e 's#_TAG_VERSION_##' -e 's#_VERSION_#latest#' ./public/index.html > ./core/dist/index.html
|
||||||
|
|
||||||
- name: Configure AWS credentials
|
- name: Configure AWS credentials
|
||||||
uses: aws-actions/configure-aws-credentials@v4
|
uses: aws-actions/configure-aws-credentials@v5
|
||||||
with:
|
with:
|
||||||
aws-region: ${{ secrets.AWS_REGION }}
|
aws-region: ${{ secrets.AWS_REGION }}
|
||||||
role-to-assume: ${{ secrets.AWS_OIDC_RUNNER_ROLE }}
|
role-to-assume: ${{ secrets.AWS_OIDC_RUNNER_ROLE }}
|
||||||
|
|||||||
4
.github/workflows/test.yml
vendored
4
.github/workflows/test.yml
vendored
@@ -24,7 +24,7 @@ jobs:
|
|||||||
MINICONDA_VERSION: 4.11.0
|
MINICONDA_VERSION: 4.11.0
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v5
|
||||||
with:
|
with:
|
||||||
fetch-depth: 3
|
fetch-depth: 3
|
||||||
|
|
||||||
@@ -37,7 +37,7 @@ jobs:
|
|||||||
run: git log --graph -3
|
run: git log --graph -3
|
||||||
|
|
||||||
- name: Install node
|
- name: Install node
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v5
|
||||||
with:
|
with:
|
||||||
node-version: 20.x
|
node-version: 20.x
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ ci:
|
|||||||
default_stages: [pre-commit]
|
default_stages: [pre-commit]
|
||||||
repos:
|
repos:
|
||||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||||
rev: v5.0.0
|
rev: v6.0.0
|
||||||
hooks:
|
hooks:
|
||||||
- id: check-builtin-literals
|
- id: check-builtin-literals
|
||||||
- id: check-case-conflict
|
- id: check-case-conflict
|
||||||
@@ -24,23 +24,30 @@ repos:
|
|||||||
exclude: core/dist|\.min\.js$
|
exclude: core/dist|\.min\.js$
|
||||||
- id: trailing-whitespace
|
- id: trailing-whitespace
|
||||||
|
|
||||||
- repo: https://github.com/psf/black
|
- repo: https://github.com/psf/black-pre-commit-mirror
|
||||||
rev: 24.10.0
|
rev: 25.9.0
|
||||||
hooks:
|
hooks:
|
||||||
- id: black
|
- id: black
|
||||||
|
exclude: core/tests
|
||||||
args: ["-l", "88", "--skip-string-normalization"]
|
args: ["-l", "88", "--skip-string-normalization"]
|
||||||
|
|
||||||
- repo: https://github.com/codespell-project/codespell
|
- repo: https://github.com/codespell-project/codespell
|
||||||
rev: v2.3.0
|
rev: v2.4.1
|
||||||
hooks:
|
hooks:
|
||||||
- id: codespell # See 'pyproject.toml' for args
|
- id: codespell # See 'pyproject.toml' for args
|
||||||
exclude: \.js\.map$
|
exclude: fs\.py|\.js\.map$
|
||||||
additional_dependencies:
|
additional_dependencies:
|
||||||
- tomli
|
- tomli
|
||||||
|
|
||||||
|
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||||
|
rev: v0.13.3
|
||||||
|
hooks:
|
||||||
|
- id: ruff
|
||||||
|
exclude: core/tests
|
||||||
|
|
||||||
- repo: https://github.com/hoodmane/pyscript-prettier-precommit
|
- repo: https://github.com/hoodmane/pyscript-prettier-precommit
|
||||||
rev: "v3.0.0-alpha.6"
|
rev: "v3.0.0-alpha.6"
|
||||||
hooks:
|
hooks:
|
||||||
- id: prettier
|
- id: prettier
|
||||||
exclude: core/test|core/dist|core/types|core/src/stdlib/pyscript.js|pyscript\.sw/|core/src/3rd-party
|
exclude: core/tests|core/dist|core/types|core/src/stdlib/pyscript.js|pyscript\.sw/|core/src/3rd-party
|
||||||
args: [--tab-width, "4"]
|
args: [--tab-width, "4"]
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
ISSUE_TEMPLATE
|
ISSUE_TEMPLATE
|
||||||
*.min.*
|
*.min.*
|
||||||
package-lock.json
|
package-lock.json
|
||||||
|
bridge/
|
||||||
|
|||||||
13
Makefile
13
Makefile
@@ -40,9 +40,9 @@ check-python:
|
|||||||
|
|
||||||
# Check the environment, install the dependencies.
|
# Check the environment, install the dependencies.
|
||||||
setup: check-node check-npm check-python
|
setup: check-node check-npm check-python
|
||||||
cd core && npm install && cd ..
|
cd core && npm ci && cd ..
|
||||||
ifeq ($(VIRTUAL_ENV),)
|
ifeq (,$(VIRTUAL_ENV)$(CONDA_PREFIX))
|
||||||
echo "\n\n\033[0;31mCannot install Python dependencies. Your virtualenv is not activated.\033[0m"
|
echo "\n\n\033[0;31mCannot install Python dependencies. Your virtualenv or conda env is not activated.\033[0m"
|
||||||
false
|
false
|
||||||
else
|
else
|
||||||
python -m pip install -r requirements.txt
|
python -m pip install -r requirements.txt
|
||||||
@@ -55,12 +55,11 @@ clean:
|
|||||||
rm -rf .pytest_cache .coverage coverage.xml
|
rm -rf .pytest_cache .coverage coverage.xml
|
||||||
|
|
||||||
# Build PyScript.
|
# Build PyScript.
|
||||||
build:
|
build: precommit-check
|
||||||
cd core && npx playwright install chromium && npm run build
|
cd core && npx playwright install chromium && npm run build
|
||||||
|
|
||||||
# Update the dependencies.
|
# Update the dependencies.
|
||||||
update:
|
update:
|
||||||
cd core && npm update && cd ..
|
|
||||||
python -m pip install -r requirements.txt --upgrade
|
python -m pip install -r requirements.txt --upgrade
|
||||||
|
|
||||||
# Run the precommit checks (run eslint).
|
# Run the precommit checks (run eslint).
|
||||||
@@ -71,6 +70,10 @@ precommit-check:
|
|||||||
test:
|
test:
|
||||||
cd core && npm run test:integration
|
cd core && npm run test:integration
|
||||||
|
|
||||||
|
# Serve the repository with the correct headers.
|
||||||
|
serve:
|
||||||
|
npx mini-coi .
|
||||||
|
|
||||||
# Format the code.
|
# Format the code.
|
||||||
fmt: fmt-py
|
fmt: fmt-py
|
||||||
@echo "Format completed"
|
@echo "Format completed"
|
||||||
|
|||||||
17
README.md
17
README.md
@@ -13,15 +13,15 @@ Using PyScript is as simple as:
|
|||||||
<title>PyScript!</title>
|
<title>PyScript!</title>
|
||||||
<link
|
<link
|
||||||
rel="stylesheet"
|
rel="stylesheet"
|
||||||
href="https://pyscript.net/snapshots/2024.9.2/core.css"
|
href="https://pyscript.net/releases/2025.10.3/core.css"
|
||||||
/>
|
/>
|
||||||
<script
|
<script
|
||||||
type="module"
|
type="module"
|
||||||
src="https://pyscript.net/snapshots/2024.9.2/core.js"
|
src="https://pyscript.net/releases/2025.10.3/core.js"
|
||||||
></script>
|
></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<!-- Use MicroPython to evaluate some Python -->
|
<!-- type mpy (MicroPython) or py (Pyodide) to run some Python -->
|
||||||
<script type="mpy" terminal>
|
<script type="mpy" terminal>
|
||||||
print("Hello, world!")
|
print("Hello, world!")
|
||||||
</script>
|
</script>
|
||||||
@@ -76,10 +76,19 @@ Read the [contributing guide](https://docs.pyscript.net/latest/contributing/)
|
|||||||
to learn about our development process, reporting bugs and improvements,
|
to learn about our development process, reporting bugs and improvements,
|
||||||
creating issues and asking questions.
|
creating issues and asking questions.
|
||||||
|
|
||||||
Check out the [developing process](https://docs.pyscript.net/latest/developers/)
|
Check out the [development process](https://docs.pyscript.net/latest/developers/)
|
||||||
documentation for more information on how to setup your development environment.
|
documentation for more information on how to setup your development environment.
|
||||||
|
|
||||||
## Governance
|
## Governance
|
||||||
|
|
||||||
The [PyScript organization governance](https://github.com/pyscript/governance)
|
The [PyScript organization governance](https://github.com/pyscript/governance)
|
||||||
is documented in a separate repository.
|
is documented in a separate repository.
|
||||||
|
|
||||||
|
## Supporters
|
||||||
|
|
||||||
|
PyScript is an independent open source project.
|
||||||
|
|
||||||
|
However, PyScript was born at [Anaconda Inc](https://anaconda.com/) and its
|
||||||
|
core contributors are currently employed by Anaconda to work on PyScript. We
|
||||||
|
would like to acknowledge and celebrate Anaconda's continued support of this
|
||||||
|
project. Thank you [Anaconda Inc](https://anaconda.com/)!
|
||||||
|
|||||||
59
bridge/README.md
Normal file
59
bridge/README.md
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
# @pyscript/bridge
|
||||||
|
|
||||||
|
Import Python utilities directly in JS
|
||||||
|
|
||||||
|
```js
|
||||||
|
// main thread
|
||||||
|
const { ffi: { func_a, func_b } } = await import('./test.js');
|
||||||
|
|
||||||
|
// test.js
|
||||||
|
import bridge from 'https://esm.run/@pyscript/bridge';
|
||||||
|
export const ffi = bridge(import.meta.url, { type: 'mpy', worker: false });
|
||||||
|
|
||||||
|
// test.py
|
||||||
|
def func_a(value):
|
||||||
|
print(f"hello {value}")
|
||||||
|
|
||||||
|
def func_b():
|
||||||
|
import sys
|
||||||
|
return sys.version
|
||||||
|
```
|
||||||
|
|
||||||
|
### Options
|
||||||
|
|
||||||
|
* **pyscript**: the release version to automatically import if not already available on the page. If no version is provided the *developers' channel* version will be used instead (for developers' purposes only).
|
||||||
|
* **type**: `py` by default to bootstrap *Pyodide*.
|
||||||
|
* **worker**: `true` by default to bootstrap in a *Web Worker*.
|
||||||
|
* **config**: either a *string* or a PyScript compatible config *JS literal* to make it possible to bootstrap files and whatnot. If specified, the `worker` becomes implicitly `true` to avoid multiple configs conflicting on the main thread.
|
||||||
|
* **env**: to share the same environment across multiple modules loaded at different times.
|
||||||
|
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
Run `npx mini-coi .` within this folder to then reach out `http://localhost:8080/test/` that will show:
|
||||||
|
|
||||||
|
```
|
||||||
|
PyScript Bridge
|
||||||
|
------------------
|
||||||
|
no config
|
||||||
|
```
|
||||||
|
|
||||||
|
The [test.js](./test/test.js) files uses the following defaults:
|
||||||
|
|
||||||
|
* `pyscript` as `"2025.8.1"`
|
||||||
|
* `type` as `"mpy"`
|
||||||
|
* `worker` as `false`
|
||||||
|
* `config` as `undefined`
|
||||||
|
* `env` as `undefined`
|
||||||
|
|
||||||
|
To test any variant use query string parameters so that `?type=py` will use `py` instead, `worker` will use a worker and `config` will use a basic *config* that brings in another file from the same folder which exposes the version.
|
||||||
|
|
||||||
|
To recap: `http://localhost:8080/test/?type=py&worker&config` will show this instead:
|
||||||
|
|
||||||
|
```
|
||||||
|
PyScript Bridge
|
||||||
|
------------------
|
||||||
|
3.12.7 (main, May 15 2025, 18:47:24) ...
|
||||||
|
```
|
||||||
|
|
||||||
|
Please note when a *config* is used, the `worker` attribute is always `true`.
|
||||||
163
bridge/index.js
Normal file
163
bridge/index.js
Normal file
@@ -0,0 +1,163 @@
|
|||||||
|
/*! (c) PyScript Development Team */
|
||||||
|
|
||||||
|
const { stringify } = JSON;
|
||||||
|
const { assign, create, entries } = Object;
|
||||||
|
|
||||||
|
const el = (name, props) => assign(document.createElement(name), props);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Transform a list of keys into a Python dictionary.
|
||||||
|
* `['a', 'b']` => `{ "a": a, "b": b }`
|
||||||
|
* @param {Iterable<string>} keys
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
const dictionary = keys => {
|
||||||
|
const fields = [];
|
||||||
|
for (const key of keys)
|
||||||
|
fields.push(`${stringify(key)}: ${key}`);
|
||||||
|
return `{ ${fields.join(',')} }`;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve properly config files relative URLs.
|
||||||
|
* @param {string|Object} config - The configuration to normalize.
|
||||||
|
* @param {string} base - The base URL to resolve relative URLs against.
|
||||||
|
* @returns {string} - The JSON serialized config.
|
||||||
|
*/
|
||||||
|
const normalize = async (config, base) => {
|
||||||
|
if (typeof config === 'string') {
|
||||||
|
base = config;
|
||||||
|
config = await fetch(config).then(res => res.json());
|
||||||
|
}
|
||||||
|
if (typeof config.files === 'object') {
|
||||||
|
const files = {};
|
||||||
|
for (const [key, value] of entries(config.files)) {
|
||||||
|
files[key.startsWith('{') ? key : new URL(key, base)] = value;
|
||||||
|
}
|
||||||
|
config.files = files;
|
||||||
|
}
|
||||||
|
return stringify(config);
|
||||||
|
};
|
||||||
|
|
||||||
|
// this logic is based on a 3 levels cache ...
|
||||||
|
const cache = new Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return a bridge to a Python module via a `.js` file that has a `.py` alter ego.
|
||||||
|
* @param {string} url - The URL of the JS module that has a Python counterpart.
|
||||||
|
* @param {Object} options - The options for the bridge.
|
||||||
|
* @param {string} [options.type='py'] - The `py` or `mpy` interpreter type, `py` by default.
|
||||||
|
* @param {boolean} [options.worker=true] - Whether to use a worker, `true` by default.
|
||||||
|
* @param {string|Object} [options.config=null] - The configuration for the bridge, `null` by default.
|
||||||
|
* @param {string} [options.env=null] - The optional shared environment to use.
|
||||||
|
* @param {string} [options.serviceWorker=null] - The optional service worker to use as fallback.
|
||||||
|
* @returns {Object} - The bridge to the Python module.
|
||||||
|
*/
|
||||||
|
export default (url, {
|
||||||
|
type = 'py',
|
||||||
|
worker = true,
|
||||||
|
config = null,
|
||||||
|
env = null,
|
||||||
|
serviceWorker = null,
|
||||||
|
pyscript = null,
|
||||||
|
} = {}) => {
|
||||||
|
const { protocol, host, pathname } = new URL(url);
|
||||||
|
const py = pathname.replace(/\.m?js(?:\/\+\w+)?$/, '.py');
|
||||||
|
const file = `${protocol}//${host}${py}`;
|
||||||
|
|
||||||
|
// the first cache is about the desired file in the wild ...
|
||||||
|
if (!cache.has(file)) {
|
||||||
|
// the second cache is about all fields one needs to access out there
|
||||||
|
const exports = new Map;
|
||||||
|
let python;
|
||||||
|
|
||||||
|
cache.set(file, new Proxy(create(null), {
|
||||||
|
get(_, field) {
|
||||||
|
if (!exports.has(field)) {
|
||||||
|
// create an async callback once and always return the same later on
|
||||||
|
exports.set(field, async (...args) => {
|
||||||
|
// the third cache is about reaching lazily the code only once
|
||||||
|
// augmenting its content with exports once and drop it on done
|
||||||
|
if (!python) {
|
||||||
|
// do not await or multiple calls will fetch multiple times
|
||||||
|
// just assign the fetch `Promise` once and return it
|
||||||
|
python = fetch(file).then(async response => {
|
||||||
|
const code = await response.text();
|
||||||
|
// create a unique identifier for the Python context
|
||||||
|
const identifier = pathname.replace(/[^a-zA-Z0-9_]/g, '');
|
||||||
|
const name = `__pyscript_${identifier}${Date.now()}`;
|
||||||
|
// create a Python dictionary with all accessed fields
|
||||||
|
const detail = `{"detail":${dictionary(exports.keys())}}`;
|
||||||
|
// create the arguments for the `dispatchEvent` call
|
||||||
|
const eventArgs = `${stringify(name)},${name}to_ts(${detail})`;
|
||||||
|
// bootstrap the script element type and its attributes
|
||||||
|
const script = el('script', { type, textContent: [
|
||||||
|
'\n', code, '\n',
|
||||||
|
// this is to avoid local scope name clashing
|
||||||
|
`from pyscript import window as ${name}`,
|
||||||
|
`from pyscript.ffi import to_js as ${name}to_ts`,
|
||||||
|
`${name}.dispatchEvent(${name}.CustomEvent.new(${eventArgs}))`,
|
||||||
|
// remove these references even if non-clashing to keep
|
||||||
|
// the local scope clean from undesired entries
|
||||||
|
`del ${name}`,
|
||||||
|
`del ${name}to_ts`,
|
||||||
|
].join('\n') });
|
||||||
|
|
||||||
|
// if config is provided it needs to be a worker to avoid
|
||||||
|
// conflicting with main config on the main thread (just like always)
|
||||||
|
script.toggleAttribute('worker', !!config || !!worker);
|
||||||
|
if (config) {
|
||||||
|
const attribute = await normalize(config, file);
|
||||||
|
script.setAttribute('config', attribute);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (env) script.setAttribute('env', env);
|
||||||
|
if (serviceWorker) script.setAttribute('service-worker', serviceWorker);
|
||||||
|
|
||||||
|
// let PyScript resolve and execute this script
|
||||||
|
document.body.appendChild(script);
|
||||||
|
|
||||||
|
// intercept once the unique event identifier with all exports
|
||||||
|
globalThis.addEventListener(
|
||||||
|
name,
|
||||||
|
event => {
|
||||||
|
resolve(event.detail);
|
||||||
|
script.remove();
|
||||||
|
},
|
||||||
|
{ once: true }
|
||||||
|
);
|
||||||
|
|
||||||
|
// return a promise that will resolve only once the event
|
||||||
|
// has been emitted and the interpreter evaluated the code
|
||||||
|
const { promise, resolve } = Promise.withResolvers();
|
||||||
|
|
||||||
|
if (!(Symbol.for('@pyscript/core') in globalThis)) {
|
||||||
|
// bring in PyScript if not available already
|
||||||
|
const cdn = pyscript ?
|
||||||
|
`https://pyscript.net/releases/${pyscript}` :
|
||||||
|
// ⚠️ fallback to developers' channel !!!
|
||||||
|
'https://cdn.jsdelivr.net/npm/@pyscript/core/dist'
|
||||||
|
;
|
||||||
|
document.head.appendChild(
|
||||||
|
el('link', { rel: 'stylesheet', href: `${cdn}/core.css` }),
|
||||||
|
);
|
||||||
|
try { await import(`${cdn}/core.js`) }
|
||||||
|
catch {}
|
||||||
|
}
|
||||||
|
return promise;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// return the `Promise` that will after invoke the exported field
|
||||||
|
return python.then(foreign => foreign[field](...args));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// return the lazily to be resolved once callback to invoke
|
||||||
|
return exports.get(field);
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
return cache.get(file);
|
||||||
|
};
|
||||||
31
bridge/package.json
Normal file
31
bridge/package.json
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
{
|
||||||
|
"name": "@pyscript/bridge",
|
||||||
|
"version": "0.2.2",
|
||||||
|
"description": "A JS based way to use PyScript modules",
|
||||||
|
"type": "module",
|
||||||
|
"module": "./index.js",
|
||||||
|
"unpkg": "./index.js",
|
||||||
|
"jsdelivr": "./jsdelivr.js",
|
||||||
|
"browser": "./index.js",
|
||||||
|
"main": "./index.js",
|
||||||
|
"keywords": [
|
||||||
|
"PyScript",
|
||||||
|
"JS",
|
||||||
|
"Python",
|
||||||
|
"bridge"
|
||||||
|
],
|
||||||
|
"files": [
|
||||||
|
"index.js",
|
||||||
|
"README.md"
|
||||||
|
],
|
||||||
|
"author": "Anaconda Inc.",
|
||||||
|
"license": "APACHE-2.0",
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "git+https://github.com/pyscript/pyscript.git"
|
||||||
|
},
|
||||||
|
"bugs": {
|
||||||
|
"url": "https://github.com/pyscript/pyscript/issues"
|
||||||
|
},
|
||||||
|
"homepage": "https://github.com/pyscript/pyscript#readme"
|
||||||
|
}
|
||||||
31
bridge/test/index.html
Normal file
31
bridge/test/index.html
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>PyScript Bridge</title>
|
||||||
|
<style>body { font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; }</style>
|
||||||
|
<!-- for local testing purpose only-->
|
||||||
|
<script type="importmap">{"imports":{"https://esm.run/@pyscript/bridge":"../index.js"}}</script>
|
||||||
|
<script type="module">
|
||||||
|
const { ffi: { test_func, test_other, version } } = await import('./test.js');
|
||||||
|
|
||||||
|
console.time("⏱️ first invoke");
|
||||||
|
const result = await test_func("PyScript Bridge");
|
||||||
|
console.timeEnd("⏱️ first invoke");
|
||||||
|
|
||||||
|
document.body.append(
|
||||||
|
Object.assign(
|
||||||
|
document.createElement("h3"),
|
||||||
|
{ textContent: result },
|
||||||
|
),
|
||||||
|
document.createElement("hr"),
|
||||||
|
await version(),
|
||||||
|
);
|
||||||
|
|
||||||
|
console.time("⏱️ other invokes");
|
||||||
|
await test_other("🐍");
|
||||||
|
console.timeEnd("⏱️ other invokes");
|
||||||
|
</script>
|
||||||
|
</head>
|
||||||
|
</html>
|
||||||
40
bridge/test/remote/index.html
Normal file
40
bridge/test/remote/index.html
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>PyScript Bridge</title>
|
||||||
|
<script type="importmap">
|
||||||
|
{
|
||||||
|
"imports": {
|
||||||
|
"https://esm.run/@pyscript/bridge": "https://esm.run/@pyscript/bridge@latest",
|
||||||
|
"https://esm.run/@pyscript/bridge/test/test.js": "https://esm.run/@pyscript/bridge@latest/test/test.js"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
<style>body { font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif; }</style>
|
||||||
|
<link rel="stylesheet" href="https://pyscript.net/releases/2025.5.1/core.css" />
|
||||||
|
<script type="module" src="https://pyscript.net/releases/2025.5.1/core.js"></script>
|
||||||
|
<script type="module">
|
||||||
|
const cdn_test = 'https://esm.run/@pyscript/bridge/test/test.js';
|
||||||
|
const { ffi: { test_func, test_other, version } } = await import(cdn_test);
|
||||||
|
|
||||||
|
console.time("⏱️ first invoke");
|
||||||
|
const result = await test_func("PyScript Bridge");
|
||||||
|
console.timeEnd("⏱️ first invoke");
|
||||||
|
|
||||||
|
document.body.append(
|
||||||
|
Object.assign(
|
||||||
|
document.createElement("h3"),
|
||||||
|
{ textContent: result },
|
||||||
|
),
|
||||||
|
document.createElement("hr"),
|
||||||
|
await version(),
|
||||||
|
);
|
||||||
|
|
||||||
|
console.time("⏱️ other invokes");
|
||||||
|
await test_other("🐍");
|
||||||
|
console.timeEnd("⏱️ other invokes");
|
||||||
|
</script>
|
||||||
|
</head>
|
||||||
|
</html>
|
||||||
5
bridge/test/sys_version.py
Normal file
5
bridge/test/sys_version.py
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
def version():
|
||||||
|
return sys.version
|
||||||
18
bridge/test/test.js
Normal file
18
bridge/test/test.js
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import bridge from "https://esm.run/@pyscript/bridge";
|
||||||
|
|
||||||
|
// for local testing purpose only
|
||||||
|
const { searchParams } = new URL(location.href);
|
||||||
|
|
||||||
|
// the named (or default) export for test.py
|
||||||
|
export const ffi = bridge(import.meta.url, {
|
||||||
|
pyscript: "2025.8.1",
|
||||||
|
env: searchParams.get("env"),
|
||||||
|
type: searchParams.get("type") || "mpy",
|
||||||
|
worker: searchParams.has("worker"),
|
||||||
|
config: searchParams.has("config") ?
|
||||||
|
({
|
||||||
|
files: {
|
||||||
|
"./sys_version.py": "./sys_version.py",
|
||||||
|
},
|
||||||
|
}) : undefined,
|
||||||
|
});
|
||||||
22
bridge/test/test.py
Normal file
22
bridge/test/test.py
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
from pyscript import config, RUNNING_IN_WORKER
|
||||||
|
|
||||||
|
type = config["type"]
|
||||||
|
print(f"{type}-script", RUNNING_IN_WORKER and "worker" or "main")
|
||||||
|
|
||||||
|
|
||||||
|
def test_func(message):
|
||||||
|
print("Python", message)
|
||||||
|
return message
|
||||||
|
|
||||||
|
|
||||||
|
def test_other(message):
|
||||||
|
print("Python", message)
|
||||||
|
return message
|
||||||
|
|
||||||
|
|
||||||
|
def version():
|
||||||
|
try:
|
||||||
|
from sys_version import version
|
||||||
|
except ImportError:
|
||||||
|
version = lambda: "no config"
|
||||||
|
return version()
|
||||||
205
core/LICENSE
Normal file
205
core/LICENSE
Normal file
@@ -0,0 +1,205 @@
|
|||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
|
||||||
|
Copyright (c) 2022-present, PyScript Development Team
|
||||||
|
|
||||||
|
Originated at Anaconda, Inc. in 2022
|
||||||
|
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
1166
core/package-lock.json
generated
1166
core/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@pyscript/core",
|
"name": "@pyscript/core",
|
||||||
"version": "0.6.7",
|
"version": "0.7.10",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"description": "PyScript",
|
"description": "PyScript",
|
||||||
"module": "./index.js",
|
"module": "./index.js",
|
||||||
@@ -25,17 +25,24 @@
|
|||||||
"types": "./types/core.d.ts",
|
"types": "./types/core.d.ts",
|
||||||
"import": "./src/core.js"
|
"import": "./src/core.js"
|
||||||
},
|
},
|
||||||
|
"./js": {
|
||||||
|
"types": "./types/core.d.ts",
|
||||||
|
"import": "./dist/core.js"
|
||||||
|
},
|
||||||
"./css": {
|
"./css": {
|
||||||
"import": "./dist/core.css"
|
"import": "./dist/core.css"
|
||||||
},
|
},
|
||||||
"./storage": {
|
"./storage": {
|
||||||
"import": "./dist/storage.js"
|
"import": "./dist/storage.js"
|
||||||
},
|
},
|
||||||
|
"./service-worker": {
|
||||||
|
"import": "./dist/service-worker.js"
|
||||||
|
},
|
||||||
"./package.json": "./package.json"
|
"./package.json": "./package.json"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"server": "echo \"➡️ TESTS @ $(tput bold)http://localhost:8080/tests/$(tput sgr0)\"; npx static-handler --coi .",
|
"server": "echo \"➡️ TESTS @ $(tput bold)http://localhost:8080/tests/$(tput sgr0)\"; npx static-handler --coi .",
|
||||||
"build": "export ESLINT_USE_FLAT_CONFIG=true;npm run build:3rd-party && npm run build:stdlib && npm run build:plugins && npm run build:core && npm run build:tests-index && if [ -z \"$NO_MIN\" ]; then eslint src/ && npm run ts && npm run test:integration; fi",
|
"build": "export ESLINT_USE_FLAT_CONFIG=true;npm run build:3rd-party && npm run build:stdlib && npm run build:plugins && npm run build:core && npm run build:tests-index && if [ -z \"$NO_MIN\" ]; then eslint src/ && npm run test:integration; fi",
|
||||||
"build:core": "rm -rf dist && rollup --config rollup/core.config.js && cp src/3rd-party/*.css dist/",
|
"build:core": "rm -rf dist && rollup --config rollup/core.config.js && cp src/3rd-party/*.css dist/",
|
||||||
"build:flatted": "node rollup/flatted.cjs",
|
"build:flatted": "node rollup/flatted.cjs",
|
||||||
"build:plugins": "node rollup/plugins.cjs",
|
"build:plugins": "node rollup/plugins.cjs",
|
||||||
@@ -43,7 +50,7 @@
|
|||||||
"build:3rd-party": "node rollup/3rd-party.cjs",
|
"build:3rd-party": "node rollup/3rd-party.cjs",
|
||||||
"build:tests-index": "node rollup/build_test_index.cjs",
|
"build:tests-index": "node rollup/build_test_index.cjs",
|
||||||
"clean:3rd-party": "rm src/3rd-party/*.js && rm src/3rd-party/*.css",
|
"clean:3rd-party": "rm src/3rd-party/*.js && rm src/3rd-party/*.css",
|
||||||
"test:integration": "npm run test:ws; static-handler --coi . 2>/dev/null & SH_PID=$!; EXIT_CODE=0; playwright test tests/js_tests.spec.js tests/py_tests.spec.js || EXIT_CODE=$?; kill $SH_PID 2>/dev/null; exit $EXIT_CODE",
|
"test:integration": "npm run test:ws; static-handler --coi . 2>/dev/null & SH_PID=$!; EXIT_CODE=0; (playwright test tests/js_tests.spec.js && playwright test tests/py_tests.main.spec.js && playwright test tests/py_tests.worker.spec.js) || EXIT_CODE=$?; kill $SH_PID 2>/dev/null; exit $EXIT_CODE",
|
||||||
"test:ws": "bun tests/javascript/ws/index.js & playwright test tests/javascript/ws/index.spec.js",
|
"test:ws": "bun tests/javascript/ws/index.js & playwright test tests/javascript/ws/index.spec.js",
|
||||||
"dev": "node dev.cjs",
|
"dev": "node dev.cjs",
|
||||||
"release": "npm run build && npm run zip",
|
"release": "npm run build && npm run zip",
|
||||||
@@ -60,41 +67,41 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ungap/with-resolvers": "^0.1.0",
|
"@ungap/with-resolvers": "^0.1.0",
|
||||||
"@webreflection/idb-map": "^0.3.2",
|
"@webreflection/idb-map": "^0.3.2",
|
||||||
|
"@webreflection/utils": "^0.1.1",
|
||||||
"add-promise-listener": "^0.1.3",
|
"add-promise-listener": "^0.1.3",
|
||||||
"basic-devtools": "^0.1.6",
|
"basic-devtools": "^0.1.6",
|
||||||
"polyscript": "^0.16.3",
|
"polyscript": "^0.19.8",
|
||||||
"sabayon": "^0.5.2",
|
|
||||||
"sticky-module": "^0.1.1",
|
"sticky-module": "^0.1.1",
|
||||||
"to-json-callback": "^0.1.1",
|
"to-json-callback": "^0.1.1",
|
||||||
"type-checked-collections": "^0.1.7"
|
"type-checked-collections": "^0.1.7"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@codemirror/commands": "^6.7.0",
|
"@codemirror/commands": "^6.9.0",
|
||||||
"@codemirror/lang-python": "^6.1.6",
|
"@codemirror/lang-python": "^6.2.1",
|
||||||
"@codemirror/language": "^6.10.3",
|
"@codemirror/language": "^6.11.3",
|
||||||
"@codemirror/state": "^6.4.1",
|
"@codemirror/state": "^6.5.2",
|
||||||
"@codemirror/view": "^6.34.1",
|
"@codemirror/view": "^6.38.6",
|
||||||
"@playwright/test": "1.45.3",
|
"@playwright/test": "^1.56.1",
|
||||||
"@rollup/plugin-commonjs": "^28.0.1",
|
"@rollup/plugin-commonjs": "^28.0.8",
|
||||||
"@rollup/plugin-node-resolve": "^15.3.0",
|
"@rollup/plugin-node-resolve": "^16.0.3",
|
||||||
"@rollup/plugin-terser": "^0.4.4",
|
"@rollup/plugin-terser": "^0.4.4",
|
||||||
"@webreflection/toml-j0.4": "^1.1.3",
|
"@webreflection/toml-j0.4": "^1.1.4",
|
||||||
"@xterm/addon-fit": "^0.10.0",
|
"@xterm/addon-fit": "^0.10.0",
|
||||||
"@xterm/addon-web-links": "^0.11.0",
|
"@xterm/addon-web-links": "^0.11.0",
|
||||||
"bun": "^1.1.30",
|
"@xterm/xterm": "^5.5.0",
|
||||||
"chokidar": "^4.0.1",
|
"bun": "^1.3.1",
|
||||||
|
"chokidar": "^4.0.3",
|
||||||
"codedent": "^0.1.2",
|
"codedent": "^0.1.2",
|
||||||
"codemirror": "^6.0.1",
|
"codemirror": "^6.0.2",
|
||||||
"eslint": "^9.12.0",
|
"eslint": "^9.38.0",
|
||||||
"flatted": "^3.3.1",
|
"flatted": "^3.3.3",
|
||||||
"rollup": "^4.24.0",
|
"rollup": "^4.52.5",
|
||||||
"rollup-plugin-postcss": "^4.0.2",
|
"rollup-plugin-postcss": "^4.0.2",
|
||||||
"rollup-plugin-string": "^3.0.0",
|
"rollup-plugin-string": "^3.0.0",
|
||||||
"static-handler": "^0.5.3",
|
"static-handler": "^0.5.3",
|
||||||
"string-width": "^7.2.0",
|
"string-width": "^8.1.0",
|
||||||
"typescript": "^5.6.3",
|
"typescript": "^5.9.3",
|
||||||
"xterm": "^5.3.0",
|
"xterm-readline": "^1.1.2"
|
||||||
"xterm-readline": "^1.1.1"
|
|
||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ const modules = {
|
|||||||
"toml.js": join(node_modules, "@webreflection", "toml-j0.4", "toml.js"),
|
"toml.js": join(node_modules, "@webreflection", "toml-j0.4", "toml.js"),
|
||||||
|
|
||||||
// xterm
|
// xterm
|
||||||
"xterm.js": resolve("xterm"),
|
"xterm.js": resolve("@xterm/xterm"),
|
||||||
"xterm-readline.js": resolve("xterm-readline"),
|
"xterm-readline.js": resolve("xterm-readline"),
|
||||||
"xterm_addon-fit.js": fetch(`${CDN}/@xterm/addon-fit/+esm`).then((b) =>
|
"xterm_addon-fit.js": fetch(`${CDN}/@xterm/addon-fit/+esm`).then((b) =>
|
||||||
b.text(),
|
b.text(),
|
||||||
@@ -54,9 +54,9 @@ const modules = {
|
|||||||
"xterm_addon-web-links.js": fetch(
|
"xterm_addon-web-links.js": fetch(
|
||||||
`${CDN}/@xterm/addon-web-links/+esm`,
|
`${CDN}/@xterm/addon-web-links/+esm`,
|
||||||
).then((b) => b.text()),
|
).then((b) => b.text()),
|
||||||
"xterm.css": fetch(`${CDN}/xterm@${v("xterm")}/css/xterm.min.css`).then(
|
"xterm.css": fetch(
|
||||||
(b) => b.text(),
|
`${CDN}/@xterm/xterm@${v("@xterm/xterm")}/css/xterm.min.css`,
|
||||||
),
|
).then((b) => b.text()),
|
||||||
|
|
||||||
// codemirror
|
// codemirror
|
||||||
"codemirror.js": reBundle("codemirror"),
|
"codemirror.js": reBundle("codemirror"),
|
||||||
|
|||||||
@@ -53,4 +53,15 @@ export default [
|
|||||||
sourcemap: true,
|
sourcemap: true,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
input: "./src/service-worker.js",
|
||||||
|
plugins: plugins.concat(
|
||||||
|
process.env.NO_MIN
|
||||||
|
? [nodeResolve(), commonjs()]
|
||||||
|
: [nodeResolve(), commonjs(), terser()],
|
||||||
|
),
|
||||||
|
output: {
|
||||||
|
file: "./dist/service-worker.js",
|
||||||
|
},
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|||||||
21
core/src/3rd-party-licenses/codemirror.license.txt
Normal file
21
core/src/3rd-party-licenses/codemirror.license.txt
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (C) 2018-2021 by Marijn Haverbeke <marijnh@gmail.com> and others
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
21
core/src/3rd-party-licenses/codemirror_commands.license.txt
Normal file
21
core/src/3rd-party-licenses/codemirror_commands.license.txt
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (C) 2018-2021 by Marijn Haverbeke <marijn@haverbeke.berlin> and others
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (C) 2018-2021 by Marijn Haverbeke <marijn@haverbeke.berlin> and others
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
21
core/src/3rd-party-licenses/codemirror_language.license.txt
Normal file
21
core/src/3rd-party-licenses/codemirror_language.license.txt
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (C) 2018-2021 by Marijn Haverbeke <marijn@haverbeke.berlin> and others
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
21
core/src/3rd-party-licenses/codemirror_state.license.txt
Normal file
21
core/src/3rd-party-licenses/codemirror_state.license.txt
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (C) 2018-2021 by Marijn Haverbeke <marijn@haverbeke.berlin> and others
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
21
core/src/3rd-party-licenses/codemirror_view.license.txt
Normal file
21
core/src/3rd-party-licenses/codemirror_view.license.txt
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (C) 2018-2021 by Marijn Haverbeke <marijn@haverbeke.berlin> and others
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
21
core/src/3rd-party-licenses/toml.license.txt
Normal file
21
core/src/3rd-party-licenses/toml.license.txt
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
The MIT License (MIT)
|
||||||
|
|
||||||
|
Copyright (c) 2015 Jak Wings
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
25
core/src/3rd-party-licenses/xterm-readline.license.txt
Normal file
25
core/src/3rd-party-licenses/xterm-readline.license.txt
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
Copyright 2021 Erik Bremen
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any
|
||||||
|
person obtaining a copy of this software and associated
|
||||||
|
documentation files (the "Software"), to deal in the
|
||||||
|
Software without restriction, including without
|
||||||
|
limitation the rights to use, copy, modify, merge,
|
||||||
|
publish, distribute, sublicense, and/or sell copies of
|
||||||
|
the Software, and to permit persons to whom the Software
|
||||||
|
is furnished to do so, subject to the following
|
||||||
|
conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice
|
||||||
|
shall be included in all copies or substantial portions
|
||||||
|
of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||||
|
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||||
|
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||||
|
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||||
|
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||||
|
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||||
|
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||||
|
DEALINGS IN THE SOFTWARE.
|
||||||
21
core/src/3rd-party-licenses/xterm.license.txt
Normal file
21
core/src/3rd-party-licenses/xterm.license.txt
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
Copyright (c) 2017-2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)
|
||||||
|
Copyright (c) 2014-2016, SourceLair Private Company (https://www.sourcelair.com)
|
||||||
|
Copyright (c) 2012-2013, Christopher Jeffrey (https://github.com/chjj/)
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
19
core/src/3rd-party-licenses/xterm_addon-fit.license.txt
Normal file
19
core/src/3rd-party-licenses/xterm_addon-fit.license.txt
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
Copyright (c) 2019, The xterm.js authors (https://github.com/xtermjs/xterm.js)
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
Copyright (c) 2017, The xterm.js authors (https://github.com/xtermjs/xterm.js)
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
||||||
4
core/src/3rd-party/README.md
vendored
4
core/src/3rd-party/README.md
vendored
@@ -5,3 +5,7 @@ This folder contains artifacts created via [3rd-party.cjs](../../rollup/3rd-part
|
|||||||
As we would like to offer a way to run PyScript offline, and we already offer a `dist` folder with all the necessary scripts, we have created a foreign dependencies resolver that allow to lazy-load CDN dependencies out of the box.
|
As we would like to offer a way to run PyScript offline, and we already offer a `dist` folder with all the necessary scripts, we have created a foreign dependencies resolver that allow to lazy-load CDN dependencies out of the box.
|
||||||
|
|
||||||
Please **note** these dependencies are **not interpreters**, because interpreters have their own mechanism, folders structure, WASM files, and whatnot, to work locally, but at least XTerm or the TOML parser, among other lazy dependencies, should be available within the dist folder.
|
Please **note** these dependencies are **not interpreters**, because interpreters have their own mechanism, folders structure, WASM files, and whatnot, to work locally, but at least XTerm or the TOML parser, among other lazy dependencies, should be available within the dist folder.
|
||||||
|
|
||||||
|
## Licenses
|
||||||
|
|
||||||
|
All licenses provided by 3rd-party authors can be found in [3rd-party-licenses](../3rd-party-licenses/) folder.
|
||||||
|
|||||||
6
core/src/3rd-party/xterm-readline.js
vendored
6
core/src/3rd-party/xterm-readline.js
vendored
File diff suppressed because one or more lines are too long
6
core/src/3rd-party/xterm.css
vendored
6
core/src/3rd-party/xterm.css
vendored
@@ -1,7 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
* Minified by jsDelivr using clean-css v5.3.2.
|
* Minified by jsDelivr using clean-css v5.3.3.
|
||||||
* Original file: /npm/xterm@5.3.0/css/xterm.css
|
* Original file: /npm/@xterm/xterm@5.5.0/css/xterm.css
|
||||||
*
|
*
|
||||||
* Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
|
* Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
|
||||||
*/
|
*/
|
||||||
.xterm{cursor:text;position:relative;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:0}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;right:0;left:0;top:0;bottom:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm .xterm-scroll-area{visibility:hidden}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm .xterm-cursor-pointer,.xterm.xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility,.xterm .xterm-message{position:absolute;left:0;top:0;bottom:0;right:0;z-index:10;color:transparent;pointer-events:none}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{text-decoration:double underline}.xterm-underline-3{text-decoration:wavy underline}.xterm-underline-4{text-decoration:dotted underline}.xterm-underline-5{text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{text-decoration:overline double underline}.xterm-overline.xterm-underline-3{text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}
|
.xterm{cursor:text;position:relative;user-select:none;-ms-user-select:none;-webkit-user-select:none}.xterm.focus,.xterm:focus{outline:0}.xterm .xterm-helpers{position:absolute;top:0;z-index:5}.xterm .xterm-helper-textarea{padding:0;border:0;margin:0;position:absolute;opacity:0;left:-9999em;top:0;width:0;height:0;z-index:-5;white-space:nowrap;overflow:hidden;resize:none}.xterm .composition-view{background:#000;color:#fff;display:none;position:absolute;white-space:nowrap;z-index:1}.xterm .composition-view.active{display:block}.xterm .xterm-viewport{background-color:#000;overflow-y:scroll;cursor:default;position:absolute;right:0;left:0;top:0;bottom:0}.xterm .xterm-screen{position:relative}.xterm .xterm-screen canvas{position:absolute;left:0;top:0}.xterm .xterm-scroll-area{visibility:hidden}.xterm-char-measure-element{display:inline-block;visibility:hidden;position:absolute;top:0;left:-9999em;line-height:normal}.xterm.enable-mouse-events{cursor:default}.xterm .xterm-cursor-pointer,.xterm.xterm-cursor-pointer{cursor:pointer}.xterm.column-select.focus{cursor:crosshair}.xterm .xterm-accessibility:not(.debug),.xterm .xterm-message{position:absolute;left:0;top:0;bottom:0;right:0;z-index:10;color:transparent;pointer-events:none}.xterm .xterm-accessibility-tree:not(.debug) ::selection{color:transparent}.xterm .xterm-accessibility-tree{user-select:text;white-space:pre}.xterm .live-region{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}.xterm-dim{opacity:1!important}.xterm-underline-1{text-decoration:underline}.xterm-underline-2{text-decoration:double underline}.xterm-underline-3{text-decoration:wavy underline}.xterm-underline-4{text-decoration:dotted underline}.xterm-underline-5{text-decoration:dashed underline}.xterm-overline{text-decoration:overline}.xterm-overline.xterm-underline-1{text-decoration:overline underline}.xterm-overline.xterm-underline-2{text-decoration:overline double underline}.xterm-overline.xterm-underline-3{text-decoration:overline wavy underline}.xterm-overline.xterm-underline-4{text-decoration:overline dotted underline}.xterm-overline.xterm-underline-5{text-decoration:overline dashed underline}.xterm-strikethrough{text-decoration:line-through}.xterm-screen .xterm-decoration-container .xterm-decoration{z-index:6;position:absolute}.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer{z-index:7}.xterm-decoration-overview-ruler{z-index:8;position:absolute;top:0;right:0;pointer-events:none}.xterm-decoration-top{z-index:2;position:relative}
|
||||||
|
|||||||
6
core/src/3rd-party/xterm.js
vendored
6
core/src/3rd-party/xterm.js
vendored
File diff suppressed because one or more lines are too long
2
core/src/3rd-party/xterm_addon-fit.js
vendored
2
core/src/3rd-party/xterm_addon-fit.js
vendored
@@ -1,5 +1,5 @@
|
|||||||
/**
|
/**
|
||||||
* Bundled by jsDelivr using Rollup v2.79.1 and Terser v5.19.2.
|
* Bundled by jsDelivr using Rollup v2.79.2 and Terser v5.39.0.
|
||||||
* Original file: /npm/@xterm/addon-fit@0.10.0/lib/addon-fit.js
|
* Original file: /npm/@xterm/addon-fit@0.10.0/lib/addon-fit.js
|
||||||
*
|
*
|
||||||
* Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
|
* Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
|
||||||
|
|||||||
2
core/src/3rd-party/xterm_addon-web-links.js
vendored
2
core/src/3rd-party/xterm_addon-web-links.js
vendored
@@ -1,5 +1,5 @@
|
|||||||
/**
|
/**
|
||||||
* Bundled by jsDelivr using Rollup v2.79.1 and Terser v5.19.2.
|
* Bundled by jsDelivr using Rollup v2.79.2 and Terser v5.39.0.
|
||||||
* Original file: /npm/@xterm/addon-web-links@0.11.0/lib/addon-web-links.js
|
* Original file: /npm/@xterm/addon-web-links@0.11.0/lib/addon-web-links.js
|
||||||
*
|
*
|
||||||
* Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
|
* Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import withResolvers from "@webreflection/utils/with-resolvers";
|
||||||
import TYPES from "./types.js";
|
import TYPES from "./types.js";
|
||||||
|
|
||||||
const waitForIt = [];
|
const waitForIt = [];
|
||||||
@@ -5,7 +6,7 @@ const waitForIt = [];
|
|||||||
for (const [TYPE] of TYPES) {
|
for (const [TYPE] of TYPES) {
|
||||||
const selectors = [`script[type="${TYPE}"]`, `${TYPE}-script`];
|
const selectors = [`script[type="${TYPE}"]`, `${TYPE}-script`];
|
||||||
for (const element of document.querySelectorAll(selectors.join(","))) {
|
for (const element of document.querySelectorAll(selectors.join(","))) {
|
||||||
const { promise, resolve } = Promise.withResolvers();
|
const { promise, resolve } = withResolvers();
|
||||||
waitForIt.push(promise);
|
waitForIt.push(promise);
|
||||||
element.addEventListener(`${TYPE}:done`, resolve, { once: true });
|
element.addEventListener(`${TYPE}:done`, resolve, { once: true });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ const badURL = (url, expected = "") => {
|
|||||||
* @param {string?} type the optional type to enforce
|
* @param {string?} type the optional type to enforce
|
||||||
* @returns {{json: boolean, toml: boolean, text: string}}
|
* @returns {{json: boolean, toml: boolean, text: string}}
|
||||||
*/
|
*/
|
||||||
const configDetails = async (config, type) => {
|
export const configDetails = async (config, type) => {
|
||||||
let text = config?.trim();
|
let text = config?.trim();
|
||||||
// we only support an object as root config
|
// we only support an object as root config
|
||||||
let url = "",
|
let url = "",
|
||||||
@@ -56,7 +56,7 @@ const syntaxError = (type, url, { message }) => {
|
|||||||
const configs = new Map();
|
const configs = new Map();
|
||||||
|
|
||||||
for (const [TYPE] of TYPES) {
|
for (const [TYPE] of TYPES) {
|
||||||
/** @type {Promise<[...any]>} A Promise wrapping any plugins which should be loaded. */
|
/** @type {() => Promise<[...any]>} A Promise wrapping any plugins which should be loaded. */
|
||||||
let plugins;
|
let plugins;
|
||||||
|
|
||||||
/** @type {any} The PyScript configuration parsed from the JSON or TOML object*. May be any of the return types of JSON.parse() or toml-j0.4's parse() ( {number | string | boolean | null | object | Array} ) */
|
/** @type {any} The PyScript configuration parsed from the JSON or TOML object*. May be any of the return types of JSON.parse() or toml-j0.4's parse() ( {number | string | boolean | null | object | Array} ) */
|
||||||
@@ -70,6 +70,7 @@ for (const [TYPE] of TYPES) {
|
|||||||
|
|
||||||
let config,
|
let config,
|
||||||
type,
|
type,
|
||||||
|
parser,
|
||||||
pyElement,
|
pyElement,
|
||||||
pyConfigs = $$(`${TYPE}-config`),
|
pyConfigs = $$(`${TYPE}-config`),
|
||||||
attrConfigs = $$(
|
attrConfigs = $$(
|
||||||
@@ -92,9 +93,11 @@ for (const [TYPE] of TYPES) {
|
|||||||
[pyElement] = pyConfigs;
|
[pyElement] = pyConfigs;
|
||||||
config = pyElement.getAttribute("src") || pyElement.textContent;
|
config = pyElement.getAttribute("src") || pyElement.textContent;
|
||||||
type = pyElement.getAttribute("type");
|
type = pyElement.getAttribute("type");
|
||||||
|
parser = pyElement.getAttribute("config-parser");
|
||||||
} else if (attrConfigs.length) {
|
} else if (attrConfigs.length) {
|
||||||
[pyElement, ...attrConfigs] = attrConfigs;
|
[pyElement, ...attrConfigs] = attrConfigs;
|
||||||
config = pyElement.getAttribute("config");
|
config = pyElement.getAttribute("config");
|
||||||
|
parser = pyElement.getAttribute("config-parser");
|
||||||
// throw an error if dirrent scripts use different configs
|
// throw an error if dirrent scripts use different configs
|
||||||
if (
|
if (
|
||||||
attrConfigs.some((el) => el.getAttribute("config") !== config)
|
attrConfigs.some((el) => el.getAttribute("config") !== config)
|
||||||
@@ -120,9 +123,12 @@ for (const [TYPE] of TYPES) {
|
|||||||
}
|
}
|
||||||
} else if (toml || type === "toml") {
|
} else if (toml || type === "toml") {
|
||||||
try {
|
try {
|
||||||
const { parse } = await import(
|
const module = parser
|
||||||
|
? await import(parser)
|
||||||
|
: await import(
|
||||||
/* webpackIgnore: true */ "./3rd-party/toml.js"
|
/* webpackIgnore: true */ "./3rd-party/toml.js"
|
||||||
);
|
);
|
||||||
|
const parse = module.parse || module.default;
|
||||||
parsed = parse(text);
|
parsed = parse(text);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
error = syntaxError("TOML", url, e);
|
error = syntaxError("TOML", url, e);
|
||||||
@@ -135,6 +141,7 @@ for (const [TYPE] of TYPES) {
|
|||||||
|
|
||||||
// parse all plugins and optionally ignore only
|
// parse all plugins and optionally ignore only
|
||||||
// those flagged as "undesired" via `!` prefix
|
// those flagged as "undesired" via `!` prefix
|
||||||
|
plugins = async () => {
|
||||||
const toBeAwaited = [];
|
const toBeAwaited = [];
|
||||||
for (const [key, value] of Object.entries(allPlugins)) {
|
for (const [key, value] of Object.entries(allPlugins)) {
|
||||||
if (error) {
|
if (error) {
|
||||||
@@ -150,9 +157,11 @@ for (const [TYPE] of TYPES) {
|
|||||||
toBeAwaited.push(value().then(({ notOnDOM }) => notOnDOM()));
|
toBeAwaited.push(value().then(({ notOnDOM }) => notOnDOM()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return await Promise.all(toBeAwaited);
|
||||||
|
};
|
||||||
|
|
||||||
// assign plugins as Promise.all only if needed
|
if (Number.isSafeInteger(parsed?.experimental_ffi_timeout))
|
||||||
plugins = Promise.all(toBeAwaited);
|
globalThis.reflected_ffi_timeout = parsed?.experimental_ffi_timeout;
|
||||||
|
|
||||||
configs.set(TYPE, { config: parsed, configURL, plugins, error });
|
configs.set(TYPE, { config: parsed, configURL, plugins, error });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,48 +28,34 @@ mpy-config {
|
|||||||
.py-editor-run-button,
|
.py-editor-run-button,
|
||||||
.mpy-editor-run-button {
|
.mpy-editor-run-button {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
|
display: flex;
|
||||||
right: 0.5rem;
|
right: 0.5rem;
|
||||||
bottom: 0.5rem;
|
bottom: 0.5rem;
|
||||||
opacity: 0;
|
opacity: 0;
|
||||||
transition: opacity 0.25s;
|
transition: opacity 0.25s;
|
||||||
z-index: 1;
|
z-index: 1;
|
||||||
|
padding: 0;
|
||||||
}
|
}
|
||||||
.py-editor-box:hover .py-editor-run-button,
|
.py-editor-box:hover .py-editor-run-button,
|
||||||
.mpy-editor-box:hover .mpy-editor-run-button,
|
.mpy-editor-box:hover .mpy-editor-run-button,
|
||||||
.py-editor-run-button:focus,
|
.py-editor-run-button:focus,
|
||||||
.py-editor-run-button:disabled,
|
.py-editor-run-button.running,
|
||||||
.mpy-editor-run-button:focus,
|
.mpy-editor-run-button:focus,
|
||||||
.mpy-editor-run-button:disabled {
|
.mpy-editor-run-button.running {
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@keyframes spinner {
|
py-terminal span,
|
||||||
to {
|
mpy-terminal span {
|
||||||
transform: rotate(360deg);
|
letter-spacing: 0 !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
dialog.pyscript-fs {
|
||||||
|
border-radius: 8px;
|
||||||
|
border-width: 1px;
|
||||||
}
|
}
|
||||||
.py-editor-run-button:disabled > *,
|
|
||||||
.mpy-editor-run-button:disabled > * {
|
dialog.pyscript-fs > div {
|
||||||
display: none; /* hide all the child elements of the run button when it is disabled */
|
display: flex;
|
||||||
}
|
justify-content: space-between;
|
||||||
.py-editor-run-button:disabled,
|
|
||||||
.mpy-editor-run-button:disabled {
|
|
||||||
border-width: 0;
|
|
||||||
}
|
|
||||||
.py-editor-run-button:disabled::before,
|
|
||||||
.mpy-editor-run-button:disabled::before {
|
|
||||||
content: "";
|
|
||||||
box-sizing: border-box;
|
|
||||||
position: absolute;
|
|
||||||
top: 100%;
|
|
||||||
left: 100%;
|
|
||||||
width: 20px;
|
|
||||||
height: 20px;
|
|
||||||
margin-top: -23px; /* hardcoded value to center the spinner on the run button */
|
|
||||||
margin-left: -26px; /* hardcoded value to center the spinner on the run button */
|
|
||||||
border-radius: 50%;
|
|
||||||
border: 2px solid #aaa;
|
|
||||||
border-top-color: #000;
|
|
||||||
background-color: #fff;
|
|
||||||
animation: spinner 0.6s linear infinite;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
/*! (c) PyScript Development Team */
|
/*! (c) PyScript Development Team */
|
||||||
|
|
||||||
|
import "./zero-redirect.js";
|
||||||
import stickyModule from "sticky-module";
|
import stickyModule from "sticky-module";
|
||||||
import "@ungap/with-resolvers";
|
import withResolvers from "@webreflection/utils/with-resolvers";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
INVALID_CONTENT,
|
INVALID_CONTENT,
|
||||||
@@ -33,6 +34,10 @@ import {
|
|||||||
createFunction,
|
createFunction,
|
||||||
inputFailure,
|
inputFailure,
|
||||||
} from "./hooks.js";
|
} from "./hooks.js";
|
||||||
|
import * as fs from "./fs.js";
|
||||||
|
|
||||||
|
import codemirror from "./plugins/codemirror.js";
|
||||||
|
export { codemirror };
|
||||||
|
|
||||||
import { stdlib, optional } from "./stdlib.js";
|
import { stdlib, optional } from "./stdlib.js";
|
||||||
export { stdlib, optional, inputFailure };
|
export { stdlib, optional, inputFailure };
|
||||||
@@ -164,6 +169,8 @@ for (const [TYPE, interpreter] of TYPES) {
|
|||||||
// enrich the Python env with some JS utility for main
|
// enrich the Python env with some JS utility for main
|
||||||
interpreter.registerJsModule("_pyscript", {
|
interpreter.registerJsModule("_pyscript", {
|
||||||
PyWorker,
|
PyWorker,
|
||||||
|
fs,
|
||||||
|
interpreter,
|
||||||
js_import: (...urls) => Promise.all(urls.map((url) => import(url))),
|
js_import: (...urls) => Promise.all(urls.map((url) => import(url))),
|
||||||
get target() {
|
get target() {
|
||||||
return isScript(currentElement)
|
return isScript(currentElement)
|
||||||
@@ -179,7 +186,7 @@ for (const [TYPE, interpreter] of TYPES) {
|
|||||||
// ensure plugins are bootstrapped already before custom type definition
|
// ensure plugins are bootstrapped already before custom type definition
|
||||||
// NOTE: we cannot top-level await in here as plugins import other utilities
|
// NOTE: we cannot top-level await in here as plugins import other utilities
|
||||||
// from core.js itself so that custom definition should not be blocking.
|
// from core.js itself so that custom definition should not be blocking.
|
||||||
plugins.then(() => {
|
plugins().then(() => {
|
||||||
// possible early errors sent by polyscript
|
// possible early errors sent by polyscript
|
||||||
const errors = new Map();
|
const errors = new Map();
|
||||||
|
|
||||||
@@ -321,7 +328,7 @@ for (const [TYPE, interpreter] of TYPES) {
|
|||||||
class extends HTMLElement {
|
class extends HTMLElement {
|
||||||
constructor() {
|
constructor() {
|
||||||
assign(super(), {
|
assign(super(), {
|
||||||
_wrap: Promise.withResolvers(),
|
_wrap: withResolvers(),
|
||||||
srcCode: "",
|
srcCode: "",
|
||||||
executed: false,
|
executed: false,
|
||||||
});
|
});
|
||||||
|
|||||||
82
core/src/fs.js
Normal file
82
core/src/fs.js
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
import IDBMap from "@webreflection/idb-map";
|
||||||
|
import withResolvers from "@webreflection/utils/with-resolvers";
|
||||||
|
import { assign } from "polyscript/exports";
|
||||||
|
import { $$ } from "basic-devtools";
|
||||||
|
|
||||||
|
const stop = (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopImmediatePropagation();
|
||||||
|
};
|
||||||
|
|
||||||
|
// ⚠️ these two constants MUST be passed as `fs`
|
||||||
|
// within the worker onBeforeRunAsync hook!
|
||||||
|
export const NAMESPACE = "@pyscript.fs";
|
||||||
|
export const ERROR = "storage permissions not granted";
|
||||||
|
|
||||||
|
export const idb = new IDBMap(NAMESPACE);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ask a user action via dialog and returns the directory handler once granted.
|
||||||
|
* @param {{id?:string, mode?:"read"|"readwrite", hint?:"desktop"|"documents"|"downloads"|"music"|"pictures"|"videos"}} options
|
||||||
|
* @returns {Promise<FileSystemDirectoryHandle>}
|
||||||
|
*/
|
||||||
|
export const getFileSystemDirectoryHandle = async (options) => {
|
||||||
|
if (!("showDirectoryPicker" in globalThis)) {
|
||||||
|
return Promise.reject(
|
||||||
|
new Error("showDirectoryPicker is not supported"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { promise, resolve, reject } = withResolvers();
|
||||||
|
|
||||||
|
const how = { id: "pyscript", mode: "readwrite", ...options };
|
||||||
|
if (options.hint) how.startIn = options.hint;
|
||||||
|
|
||||||
|
const transient = async () => {
|
||||||
|
try {
|
||||||
|
/* eslint-disable */
|
||||||
|
const handler = await showDirectoryPicker(how);
|
||||||
|
/* eslint-enable */
|
||||||
|
if ((await handler.requestPermission(how)) === "granted") {
|
||||||
|
resolve(handler);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
} catch ({ message }) {
|
||||||
|
console.warn(message);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
// in case the user decided to attach the event itself
|
||||||
|
// as opposite of relying our dialog walkthrough
|
||||||
|
if (navigator.userActivation?.isActive) {
|
||||||
|
if (!(await transient())) reject(new Error(ERROR));
|
||||||
|
} else {
|
||||||
|
const dialog = assign(document.createElement("dialog"), {
|
||||||
|
className: "pyscript-fs",
|
||||||
|
innerHTML: [
|
||||||
|
"<strong>ℹ️ Persistent FileSystem</strong><hr>",
|
||||||
|
"<p><small>PyScript would like to access a local folder.</small></p>",
|
||||||
|
"<div><button title='ok'>✅ Authorize</button>",
|
||||||
|
"<button title='cancel'>❌</button></div>",
|
||||||
|
].join(""),
|
||||||
|
});
|
||||||
|
|
||||||
|
const [ok, cancel] = $$("button", dialog);
|
||||||
|
|
||||||
|
ok.addEventListener("click", async (event) => {
|
||||||
|
stop(event);
|
||||||
|
if (await transient()) dialog.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
cancel.addEventListener("click", async (event) => {
|
||||||
|
stop(event);
|
||||||
|
reject(new Error(ERROR));
|
||||||
|
dialog.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
document.body.appendChild(dialog).showModal();
|
||||||
|
}
|
||||||
|
|
||||||
|
return promise;
|
||||||
|
};
|
||||||
@@ -88,7 +88,19 @@ export const hooks = {
|
|||||||
/** @type {Set<function>} */
|
/** @type {Set<function>} */
|
||||||
onBeforeRun: new SetFunction(),
|
onBeforeRun: new SetFunction(),
|
||||||
/** @type {Set<function>} */
|
/** @type {Set<function>} */
|
||||||
onBeforeRunAsync: new SetFunction(),
|
onBeforeRunAsync: new SetFunction([
|
||||||
|
({ interpreter }) => {
|
||||||
|
interpreter.registerJsModule("_pyscript", {
|
||||||
|
// cannot be imported from fs.js
|
||||||
|
// because this code is stringified
|
||||||
|
fs: {
|
||||||
|
ERROR: "storage permissions not granted",
|
||||||
|
NAMESPACE: "@pyscript.fs",
|
||||||
|
},
|
||||||
|
interpreter,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
]),
|
||||||
/** @type {Set<function>} */
|
/** @type {Set<function>} */
|
||||||
onAfterRun: new SetFunction(),
|
onAfterRun: new SetFunction(),
|
||||||
/** @type {Set<function>} */
|
/** @type {Set<function>} */
|
||||||
|
|||||||
@@ -1,5 +1,10 @@
|
|||||||
// ⚠️ This file is an artifact: DO NOT MODIFY
|
// ⚠️ This file is an artifact: DO NOT MODIFY
|
||||||
export default {
|
export default {
|
||||||
|
codemirror: () =>
|
||||||
|
import(
|
||||||
|
/* webpackIgnore: true */
|
||||||
|
"./plugins/codemirror.js"
|
||||||
|
),
|
||||||
["deprecations-manager"]: () =>
|
["deprecations-manager"]: () =>
|
||||||
import(
|
import(
|
||||||
/* webpackIgnore: true */
|
/* webpackIgnore: true */
|
||||||
@@ -20,6 +25,11 @@ export default {
|
|||||||
/* webpackIgnore: true */
|
/* webpackIgnore: true */
|
||||||
"./plugins/py-editor.js"
|
"./plugins/py-editor.js"
|
||||||
),
|
),
|
||||||
|
["py-game"]: () =>
|
||||||
|
import(
|
||||||
|
/* webpackIgnore: true */
|
||||||
|
"./plugins/py-game.js"
|
||||||
|
),
|
||||||
["py-terminal"]: () =>
|
["py-terminal"]: () =>
|
||||||
import(
|
import(
|
||||||
/* webpackIgnore: true */
|
/* webpackIgnore: true */
|
||||||
|
|||||||
31
core/src/plugins/codemirror.js
Normal file
31
core/src/plugins/codemirror.js
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
// lazy loaded on-demand codemirror related files
|
||||||
|
export default {
|
||||||
|
get core() {
|
||||||
|
return import(/* webpackIgnore: true */ "../3rd-party/codemirror.js");
|
||||||
|
},
|
||||||
|
get state() {
|
||||||
|
return import(
|
||||||
|
/* webpackIgnore: true */ "../3rd-party/codemirror_state.js"
|
||||||
|
);
|
||||||
|
},
|
||||||
|
get python() {
|
||||||
|
return import(
|
||||||
|
/* webpackIgnore: true */ "../3rd-party/codemirror_lang-python.js"
|
||||||
|
);
|
||||||
|
},
|
||||||
|
get language() {
|
||||||
|
return import(
|
||||||
|
/* webpackIgnore: true */ "../3rd-party/codemirror_language.js"
|
||||||
|
);
|
||||||
|
},
|
||||||
|
get view() {
|
||||||
|
return import(
|
||||||
|
/* webpackIgnore: true */ "../3rd-party/codemirror_view.js"
|
||||||
|
);
|
||||||
|
},
|
||||||
|
get commands() {
|
||||||
|
return import(
|
||||||
|
/* webpackIgnore: true */ "../3rd-party/codemirror_commands.js"
|
||||||
|
);
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
// PyScript Derepcations Plugin
|
// PyScript Derepcations Plugin
|
||||||
import { hooks } from "../core.js";
|
|
||||||
import { notify } from "./error.js";
|
import { notify } from "./error.js";
|
||||||
|
import { hooks } from "../core.js";
|
||||||
|
|
||||||
// react lazily on PyScript bootstrap
|
// react lazily on PyScript bootstrap
|
||||||
hooks.main.onReady.add(checkDeprecations);
|
hooks.main.onReady.add(checkDeprecations);
|
||||||
|
|||||||
@@ -5,8 +5,15 @@ const { stringify } = JSON;
|
|||||||
|
|
||||||
const invoke = (name, args) => `${name}(code, ${args.join(", ")})`;
|
const invoke = (name, args) => `${name}(code, ${args.join(", ")})`;
|
||||||
|
|
||||||
const donkey = ({ type = "py", persistent, terminal, config }) => {
|
const donkey = ({
|
||||||
const args = persistent ? ["globals()", "__locals__"] : ["{}", "{}"];
|
type = "py",
|
||||||
|
persistent,
|
||||||
|
terminal,
|
||||||
|
config,
|
||||||
|
serviceWorker,
|
||||||
|
}) => {
|
||||||
|
const globals = terminal ? '{"__terminal__":__terminal__}' : "{}";
|
||||||
|
const args = persistent ? ["globals()", "__locals__"] : [globals, "{}"];
|
||||||
|
|
||||||
const src = URL.createObjectURL(
|
const src = URL.createObjectURL(
|
||||||
new Blob([
|
new Blob([
|
||||||
@@ -45,6 +52,7 @@ const donkey = ({ type = "py", persistent, terminal, config }) => {
|
|||||||
typeof config === "string" ? config : stringify(config),
|
typeof config === "string" ? config : stringify(config),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
if (serviceWorker) script.setAttribute("service-worker", serviceWorker);
|
||||||
|
|
||||||
return addPromiseListener(
|
return addPromiseListener(
|
||||||
document.body.appendChild(script),
|
document.body.appendChild(script),
|
||||||
|
|||||||
@@ -1,15 +1,19 @@
|
|||||||
// PyScript py-editor plugin
|
// PyScript py-editor plugin
|
||||||
|
import withResolvers from "@webreflection/utils/with-resolvers";
|
||||||
import { Hook, XWorker, dedent, defineProperties } from "polyscript/exports";
|
import { Hook, XWorker, dedent, defineProperties } from "polyscript/exports";
|
||||||
import { TYPES, offline_interpreter, relative_url, stdlib } from "../core.js";
|
import { TYPES, offline_interpreter, relative_url, stdlib } from "../core.js";
|
||||||
import { notify } from "./error.js";
|
import { notify } from "./error.js";
|
||||||
|
import codemirror from "./codemirror.js";
|
||||||
|
|
||||||
const RUN_BUTTON = `<svg style="height:20px;width:20px;vertical-align:-.125em;transform-origin:center;overflow:visible;color:green" viewBox="0 0 384 512" aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg"><g transform="translate(192 256)" transform-origin="96 0"><g transform="translate(0,0) scale(1,1)"><path d="M361 215C375.3 223.8 384 239.3 384 256C384 272.7 375.3 288.2 361 296.1L73.03 472.1C58.21 482 39.66 482.4 24.52 473.9C9.377 465.4 0 449.4 0 432V80C0 62.64 9.377 46.63 24.52 38.13C39.66 29.64 58.21 29.99 73.03 39.04L361 215z" fill="currentColor" transform="translate(-192 -256)"></path></g></g></svg>`;
|
const RUN_BUTTON = `<svg style="height:24px;width:24px" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M19,12a1,1,0,0,1-.55.89l-10,5A1,1,0,0,1,8,18a1,1,0,0,1-.53-.15A1,1,0,0,1,7,17V7a1,1,0,0,1,1.45-.89l10,5A1,1,0,0,1,19,12Z" fill="#464646"/></svg>`;
|
||||||
|
const STOP_BUTTON = `<svg style="height:24px;width:24px" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M7 7h10v10H7z" style="fill:#464646;stroke:#464646;stroke-width:1;stroke-linecap:butt;stroke-linejoin:round;stroke-dasharray:none;paint-order:normal"/></svg>`;
|
||||||
|
|
||||||
let id = 0;
|
let id = 0;
|
||||||
const getID = (type) => `${type}-editor-${id++}`;
|
const getID = (type) => `${type}-editor-${id++}`;
|
||||||
|
|
||||||
const envs = new Map();
|
const envs = new Map();
|
||||||
const configs = new Map();
|
const configs = new Map();
|
||||||
|
const editors = new WeakMap();
|
||||||
|
|
||||||
const hooks = {
|
const hooks = {
|
||||||
worker: {
|
worker: {
|
||||||
@@ -29,12 +33,18 @@ const validate = (config, result) => {
|
|||||||
return result;
|
return result;
|
||||||
};
|
};
|
||||||
|
|
||||||
async function execute({ currentTarget }) {
|
const getRelatedScript = (target, type) => {
|
||||||
|
const editor = target.closest(`.${type}-editor-box`);
|
||||||
|
return editor?.parentNode?.previousElementSibling;
|
||||||
|
};
|
||||||
|
|
||||||
|
async function execute({ currentTarget, script }) {
|
||||||
const { env, pySrc, outDiv } = this;
|
const { env, pySrc, outDiv } = this;
|
||||||
const hasRunButton = !!currentTarget;
|
const hasRunButton = !!currentTarget;
|
||||||
|
|
||||||
if (hasRunButton) {
|
if (hasRunButton) {
|
||||||
currentTarget.disabled = true;
|
currentTarget.classList.add("running");
|
||||||
|
currentTarget.innerHTML = STOP_BUTTON;
|
||||||
outDiv.innerHTML = "";
|
outDiv.innerHTML = "";
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,17 +91,15 @@ async function execute({ currentTarget }) {
|
|||||||
// creation and destruction of editors on the fly
|
// creation and destruction of editors on the fly
|
||||||
if (hasRunButton) {
|
if (hasRunButton) {
|
||||||
for (const type of TYPES.keys()) {
|
for (const type of TYPES.keys()) {
|
||||||
const editor = currentTarget.closest(`.${type}-editor-box`);
|
script = getRelatedScript(currentTarget, type);
|
||||||
const script = editor?.parentNode?.previousElementSibling;
|
if (script) break;
|
||||||
if (script) {
|
|
||||||
defineProperties(script, { xworker: { value: xworker } });
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
defineProperties(script, { xworker: { value: xworker } });
|
||||||
|
|
||||||
const { sync } = xworker;
|
const { sync } = xworker;
|
||||||
const { promise, resolve } = Promise.withResolvers();
|
const { promise, resolve } = withResolvers();
|
||||||
envs.set(env, promise);
|
envs.set(env, promise);
|
||||||
sync.revoke = () => {
|
sync.revoke = () => {
|
||||||
URL.revokeObjectURL(srcLink);
|
URL.revokeObjectURL(srcLink);
|
||||||
@@ -115,7 +123,18 @@ async function execute({ currentTarget }) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const enable = () => {
|
const enable = () => {
|
||||||
if (hasRunButton) currentTarget.disabled = false;
|
if (hasRunButton) {
|
||||||
|
currentTarget.classList.remove("running");
|
||||||
|
currentTarget.innerHTML = RUN_BUTTON;
|
||||||
|
const { previousElementSibling } =
|
||||||
|
currentTarget.closest("[data-env]").parentElement;
|
||||||
|
previousElementSibling?.dispatchEvent(
|
||||||
|
new Event("py-editor:done", {
|
||||||
|
bubbles: true,
|
||||||
|
cancelable: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
const { sync } = xworker;
|
const { sync } = xworker;
|
||||||
sync.write = (str) => {
|
sync.write = (str) => {
|
||||||
@@ -137,12 +156,54 @@ async function execute({ currentTarget }) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const replaceScript = (script, type) => {
|
||||||
|
script.xworker?.terminate();
|
||||||
|
const clone = script.cloneNode(true);
|
||||||
|
clone.type = `${type}-editor`;
|
||||||
|
const editor = editors.get(script);
|
||||||
|
if (editor) {
|
||||||
|
const content = editor.state.doc.toString();
|
||||||
|
clone.textContent = content;
|
||||||
|
editors.delete(script);
|
||||||
|
script.nextElementSibling.remove();
|
||||||
|
}
|
||||||
|
script.replaceWith(clone);
|
||||||
|
};
|
||||||
|
|
||||||
const makeRunButton = (handler, type) => {
|
const makeRunButton = (handler, type) => {
|
||||||
const runButton = document.createElement("button");
|
const runButton = document.createElement("button");
|
||||||
runButton.className = `absolute ${type}-editor-run-button`;
|
runButton.className = `absolute ${type}-editor-run-button`;
|
||||||
runButton.innerHTML = RUN_BUTTON;
|
runButton.innerHTML = RUN_BUTTON;
|
||||||
runButton.setAttribute("aria-label", "Python Script Run Button");
|
runButton.setAttribute("aria-label", "Python Script Run Button");
|
||||||
runButton.addEventListener("click", async (event) => {
|
runButton.addEventListener("click", async (event) => {
|
||||||
|
if (
|
||||||
|
runButton.classList.contains("running") &&
|
||||||
|
confirm("Stop evaluating this code?")
|
||||||
|
) {
|
||||||
|
const script = getRelatedScript(runButton, type);
|
||||||
|
if (script) {
|
||||||
|
const env = script.getAttribute("env");
|
||||||
|
// remove the bootstrapped env which could be one or shared
|
||||||
|
if (env) {
|
||||||
|
for (const [key, value] of TYPES) {
|
||||||
|
if (key === type) {
|
||||||
|
configs.delete(`${value}-${env}`);
|
||||||
|
envs.delete(`${value}-${env}`);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// lonley script without setup node should be replaced
|
||||||
|
if (script.xworker) replaceScript(script, type);
|
||||||
|
// all scripts sharing the same env should be replaced
|
||||||
|
else {
|
||||||
|
const sel = `script[type^="${type}-editor"][env="${env}"]`;
|
||||||
|
for (const script of document.querySelectorAll(sel))
|
||||||
|
replaceScript(script, type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
runButton.blur();
|
runButton.blur();
|
||||||
await handler.handleEvent(event);
|
await handler.handleEvent(event);
|
||||||
});
|
});
|
||||||
@@ -194,14 +255,12 @@ const init = async (script, type, interpreter) => {
|
|||||||
{ keymap },
|
{ keymap },
|
||||||
{ defaultKeymap, indentWithTab },
|
{ defaultKeymap, indentWithTab },
|
||||||
] = await Promise.all([
|
] = await Promise.all([
|
||||||
import(/* webpackIgnore: true */ "../3rd-party/codemirror.js"),
|
codemirror.core,
|
||||||
import(/* webpackIgnore: true */ "../3rd-party/codemirror_state.js"),
|
codemirror.state,
|
||||||
import(
|
codemirror.python,
|
||||||
/* webpackIgnore: true */ "../3rd-party/codemirror_lang-python.js"
|
codemirror.language,
|
||||||
),
|
codemirror.view,
|
||||||
import(/* webpackIgnore: true */ "../3rd-party/codemirror_language.js"),
|
codemirror.commands,
|
||||||
import(/* webpackIgnore: true */ "../3rd-party/codemirror_view.js"),
|
|
||||||
import(/* webpackIgnore: true */ "../3rd-party/codemirror_commands.js"),
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
let isSetup = script.hasAttribute("setup");
|
let isSetup = script.hasAttribute("setup");
|
||||||
@@ -329,7 +388,7 @@ const init = async (script, type, interpreter) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (isSetup) {
|
if (isSetup) {
|
||||||
await context.handleEvent({ currentTarget: null });
|
await context.handleEvent({ currentTarget: null, script });
|
||||||
notifyEditor();
|
notifyEditor();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -367,16 +426,17 @@ const init = async (script, type, interpreter) => {
|
|||||||
// preserve user indentation, if any
|
// preserve user indentation, if any
|
||||||
const indentation = /^([ \t]+)/m.test(doc) ? RegExp.$1 : " ";
|
const indentation = /^([ \t]+)/m.test(doc) ? RegExp.$1 : " ";
|
||||||
|
|
||||||
const listener = () => runButton.click();
|
const listener = () => !runButton.click();
|
||||||
const editor = new EditorView({
|
const editor = new EditorView({
|
||||||
extensions: [
|
extensions: [
|
||||||
indentUnit.of(indentation),
|
indentUnit.of(indentation),
|
||||||
new Compartment().of(python()),
|
new Compartment().of(python()),
|
||||||
keymap.of([
|
keymap.of([
|
||||||
...defaultKeymap,
|
|
||||||
{ key: "Ctrl-Enter", run: listener, preventDefault: true },
|
{ key: "Ctrl-Enter", run: listener, preventDefault: true },
|
||||||
{ key: "Cmd-Enter", run: listener, preventDefault: true },
|
{ key: "Cmd-Enter", run: listener, preventDefault: true },
|
||||||
{ key: "Shift-Enter", run: listener, preventDefault: true },
|
{ key: "Shift-Enter", run: listener, preventDefault: true },
|
||||||
|
// Consider removing defaultKeymap as likely redundant with basicSetup
|
||||||
|
...defaultKeymap,
|
||||||
// @see https://codemirror.net/examples/tab/
|
// @see https://codemirror.net/examples/tab/
|
||||||
indentWithTab,
|
indentWithTab,
|
||||||
]),
|
]),
|
||||||
@@ -388,6 +448,7 @@ const init = async (script, type, interpreter) => {
|
|||||||
doc,
|
doc,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
editors.set(script, editor);
|
||||||
editor.focus();
|
editor.focus();
|
||||||
notifyEditor();
|
notifyEditor();
|
||||||
};
|
};
|
||||||
|
|||||||
112
core/src/plugins/py-game.js
Normal file
112
core/src/plugins/py-game.js
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
import {
|
||||||
|
dedent,
|
||||||
|
define,
|
||||||
|
createProgress,
|
||||||
|
loadProgress,
|
||||||
|
} from "polyscript/exports";
|
||||||
|
|
||||||
|
import { stdlib } from "../core.js";
|
||||||
|
import { configDetails } from "../config.js";
|
||||||
|
import { getText } from "../fetch.js";
|
||||||
|
|
||||||
|
const progress = createProgress("py-game");
|
||||||
|
|
||||||
|
const inputPatch = `
|
||||||
|
import builtins
|
||||||
|
def input(prompt=""):
|
||||||
|
import js
|
||||||
|
return js.prompt(prompt)
|
||||||
|
|
||||||
|
builtins.input = input
|
||||||
|
del builtins
|
||||||
|
del input
|
||||||
|
`;
|
||||||
|
|
||||||
|
let toBeWarned = true;
|
||||||
|
|
||||||
|
const hooks = {
|
||||||
|
main: {
|
||||||
|
onReady: async (wrap, script) => {
|
||||||
|
if (toBeWarned) {
|
||||||
|
toBeWarned = false;
|
||||||
|
console.warn("⚠️ EXPERIMENTAL `py-game` FEATURE");
|
||||||
|
}
|
||||||
|
|
||||||
|
let config = {};
|
||||||
|
if (script.hasAttribute("config")) {
|
||||||
|
const value = script.getAttribute("config");
|
||||||
|
const { json, toml, text, url } = await configDetails(value);
|
||||||
|
if (json) config = JSON.parse(text);
|
||||||
|
else if (toml) {
|
||||||
|
const { parse } = await import(
|
||||||
|
/* webpackIgnore: true */ "../3rd-party/toml.js"
|
||||||
|
);
|
||||||
|
config = parse(text);
|
||||||
|
}
|
||||||
|
if (config.packages) {
|
||||||
|
await wrap.interpreter.loadPackage("micropip");
|
||||||
|
const micropip = wrap.interpreter.pyimport("micropip");
|
||||||
|
await micropip.install(config.packages, {
|
||||||
|
keep_going: true,
|
||||||
|
});
|
||||||
|
micropip.destroy();
|
||||||
|
}
|
||||||
|
await loadProgress(
|
||||||
|
"py-game",
|
||||||
|
progress,
|
||||||
|
wrap.interpreter,
|
||||||
|
config,
|
||||||
|
url ? new URL(url, location.href).href : location.href,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
wrap.interpreter.registerJsModule("_pyscript", {
|
||||||
|
PyWorker() {
|
||||||
|
throw new Error(
|
||||||
|
"Unable to use PyWorker in py-game scripts",
|
||||||
|
);
|
||||||
|
},
|
||||||
|
js_import: (...urls) =>
|
||||||
|
Promise.all(urls.map((url) => import(url))),
|
||||||
|
get target() {
|
||||||
|
return script.id;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await wrap.interpreter.runPythonAsync(stdlib);
|
||||||
|
wrap.interpreter.runPython(inputPatch);
|
||||||
|
|
||||||
|
let code = dedent(script.textContent);
|
||||||
|
if (script.src) code = await fetch(script.src).then(getText);
|
||||||
|
|
||||||
|
const target = script.getAttribute("target") || "canvas";
|
||||||
|
const canvas = document.getElementById(target);
|
||||||
|
wrap.interpreter.canvas.setCanvas2D(canvas);
|
||||||
|
|
||||||
|
// allow 3rd party to hook themselves right before
|
||||||
|
// the code gets executed
|
||||||
|
const event = new CustomEvent("py-game", {
|
||||||
|
bubbles: true,
|
||||||
|
cancelable: true,
|
||||||
|
detail: {
|
||||||
|
canvas,
|
||||||
|
code,
|
||||||
|
config,
|
||||||
|
wrap,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
script.dispatchEvent(event);
|
||||||
|
// run only if the default was not prevented
|
||||||
|
if (!event.defaultPrevented)
|
||||||
|
await wrap.interpreter.runPythonAsync(code);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
define("py-game", {
|
||||||
|
config: { packages: ["pygame-ce"] },
|
||||||
|
configURL: new URL("./config.txt", location.href).href,
|
||||||
|
interpreter: "pyodide",
|
||||||
|
env: "py-game",
|
||||||
|
hooks,
|
||||||
|
});
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
// PyScript pyodide terminal plugin
|
// PyScript pyodide terminal plugin
|
||||||
import { hooks, inputFailure } from "../../core.js";
|
import withResolvers from "@webreflection/utils/with-resolvers";
|
||||||
import { defineProperties } from "polyscript/exports";
|
import { defineProperties } from "polyscript/exports";
|
||||||
|
import { hooks, inputFailure } from "../../core.js";
|
||||||
|
|
||||||
const bootstrapped = new WeakSet();
|
const bootstrapped = new WeakSet();
|
||||||
|
|
||||||
@@ -34,6 +35,8 @@ const workerReady = ({ interpreter, io, run, type }, { sync }) => {
|
|||||||
pyterminal_write(String(error.message || error));
|
pyterminal_write(String(error.message || error));
|
||||||
};
|
};
|
||||||
|
|
||||||
|
sync.pyterminal_stream_write = () => {};
|
||||||
|
|
||||||
// tiny shim of the code module with only interact
|
// tiny shim of the code module with only interact
|
||||||
// to bootstrap a REPL like environment
|
// to bootstrap a REPL like environment
|
||||||
interpreter.registerJsModule("code", {
|
interpreter.registerJsModule("code", {
|
||||||
@@ -71,6 +74,7 @@ export default async (element) => {
|
|||||||
disableStdin: false,
|
disableStdin: false,
|
||||||
cursorBlink: true,
|
cursorBlink: true,
|
||||||
cursorStyle: "block",
|
cursorStyle: "block",
|
||||||
|
lineHeight: 1.2,
|
||||||
};
|
};
|
||||||
|
|
||||||
let stream;
|
let stream;
|
||||||
@@ -143,7 +147,7 @@ export default async (element) => {
|
|||||||
// frees the worker on \r
|
// frees the worker on \r
|
||||||
sync.pyterminal_read = (buffer) => {
|
sync.pyterminal_read = (buffer) => {
|
||||||
terminal.write(buffer);
|
terminal.write(buffer);
|
||||||
promisedChunks = Promise.withResolvers();
|
promisedChunks = withResolvers();
|
||||||
return promisedChunks.promise;
|
return promisedChunks.promise;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// PyScript py-terminal plugin
|
// PyScript py-terminal plugin
|
||||||
import { hooks } from "../../core.js";
|
|
||||||
import { defineProperties } from "polyscript/exports";
|
import { defineProperties } from "polyscript/exports";
|
||||||
|
import { hooks } from "../../core.js";
|
||||||
|
|
||||||
const bootstrapped = new WeakSet();
|
const bootstrapped = new WeakSet();
|
||||||
|
|
||||||
@@ -126,6 +126,7 @@ export default async (element) => {
|
|||||||
disableStdin: false,
|
disableStdin: false,
|
||||||
cursorBlink: true,
|
cursorBlink: true,
|
||||||
cursorStyle: "block",
|
cursorStyle: "block",
|
||||||
|
lineHeight: 1.2,
|
||||||
});
|
});
|
||||||
|
|
||||||
xworker.sync.is_pyterminal = () => true;
|
xworker.sync.is_pyterminal = () => true;
|
||||||
@@ -136,6 +137,18 @@ export default async (element) => {
|
|||||||
// setup remote thread JS/Python code for whenever the
|
// setup remote thread JS/Python code for whenever the
|
||||||
// worker is ready to become a terminal
|
// worker is ready to become a terminal
|
||||||
hooks.worker.onReady.add(workerReady);
|
hooks.worker.onReady.add(workerReady);
|
||||||
|
|
||||||
|
// @see https://github.com/pyscript/pyscript/issues/2246
|
||||||
|
const patchInput = [
|
||||||
|
"import builtins as _b",
|
||||||
|
"from pyscript import sync as _s",
|
||||||
|
"_b.input = _s.pyterminal_read",
|
||||||
|
"del _b",
|
||||||
|
"del _s",
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
|
hooks.worker.codeBeforeRun.add(patchInput);
|
||||||
|
hooks.worker.codeBeforeRunAsync.add(patchInput);
|
||||||
} else {
|
} else {
|
||||||
// in the main case, just bootstrap XTerm without
|
// in the main case, just bootstrap XTerm without
|
||||||
// allowing any input as that's not possible / awkward
|
// allowing any input as that's not possible / awkward
|
||||||
|
|||||||
1
core/src/service-worker.js
Normal file
1
core/src/service-worker.js
Normal file
@@ -0,0 +1 @@
|
|||||||
|
import "polyscript/service-worker";
|
||||||
File diff suppressed because one or more lines are too long
@@ -30,8 +30,6 @@
|
|||||||
# as it works transparently in both the main thread and worker cases.
|
# as it works transparently in both the main thread and worker cases.
|
||||||
|
|
||||||
from polyscript import lazy_py_modules as py_import
|
from polyscript import lazy_py_modules as py_import
|
||||||
from pyscript.display import HTML, display
|
|
||||||
from pyscript.fetch import fetch
|
|
||||||
from pyscript.magic_js import (
|
from pyscript.magic_js import (
|
||||||
RUNNING_IN_WORKER,
|
RUNNING_IN_WORKER,
|
||||||
PyWorker,
|
PyWorker,
|
||||||
@@ -43,19 +41,11 @@ from pyscript.magic_js import (
|
|||||||
sync,
|
sync,
|
||||||
window,
|
window,
|
||||||
)
|
)
|
||||||
|
from pyscript.display import HTML, display
|
||||||
|
from pyscript.fetch import fetch
|
||||||
from pyscript.storage import Storage, storage
|
from pyscript.storage import Storage, storage
|
||||||
from pyscript.websocket import WebSocket
|
from pyscript.websocket import WebSocket
|
||||||
|
from pyscript.events import when, Event
|
||||||
|
|
||||||
if not RUNNING_IN_WORKER:
|
if not RUNNING_IN_WORKER:
|
||||||
from pyscript.workers import create_named_worker, workers
|
from pyscript.workers import create_named_worker, workers
|
||||||
|
|
||||||
try:
|
|
||||||
from pyscript.event_handling import when
|
|
||||||
except:
|
|
||||||
# TODO: should we remove this? Or at the very least, we should capture
|
|
||||||
# the traceback otherwise it's very hard to debug
|
|
||||||
from pyscript.util import NotSupported
|
|
||||||
|
|
||||||
when = NotSupported(
|
|
||||||
"pyscript.when", "pyscript.when currently not available with this interpreter"
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import io
|
|||||||
import re
|
import re
|
||||||
|
|
||||||
from pyscript.magic_js import current_target, document, window
|
from pyscript.magic_js import current_target, document, window
|
||||||
|
from pyscript.ffi import is_none
|
||||||
|
|
||||||
_MIME_METHODS = {
|
_MIME_METHODS = {
|
||||||
"savefig": "image/png",
|
"savefig": "image/png",
|
||||||
@@ -73,14 +74,14 @@ def _eval_formatter(obj, print_method):
|
|||||||
"""
|
"""
|
||||||
if print_method == "__repr__":
|
if print_method == "__repr__":
|
||||||
return repr(obj)
|
return repr(obj)
|
||||||
elif hasattr(obj, print_method):
|
if hasattr(obj, print_method):
|
||||||
if print_method == "savefig":
|
if print_method == "savefig":
|
||||||
buf = io.BytesIO()
|
buf = io.BytesIO()
|
||||||
obj.savefig(buf, format="png")
|
obj.savefig(buf, format="png")
|
||||||
buf.seek(0)
|
buf.seek(0)
|
||||||
return base64.b64encode(buf.read()).decode("utf-8")
|
return base64.b64encode(buf.read()).decode("utf-8")
|
||||||
return getattr(obj, print_method)()
|
return getattr(obj, print_method)()
|
||||||
elif print_method == "_repr_mimebundle_":
|
if print_method == "_repr_mimebundle_":
|
||||||
return {}, {}
|
return {}, {}
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -105,13 +106,13 @@ def _format_mime(obj):
|
|||||||
else:
|
else:
|
||||||
output = _eval_formatter(obj, method)
|
output = _eval_formatter(obj, method)
|
||||||
|
|
||||||
if output is None:
|
if is_none(output):
|
||||||
continue
|
continue
|
||||||
elif mime_type not in _MIME_RENDERERS:
|
if mime_type not in _MIME_RENDERERS:
|
||||||
not_available.append(mime_type)
|
not_available.append(mime_type)
|
||||||
continue
|
continue
|
||||||
break
|
break
|
||||||
if output is None:
|
if is_none(output):
|
||||||
if not_available:
|
if not_available:
|
||||||
window.console.warn(
|
window.console.warn(
|
||||||
f"Rendered object requested unavailable MIME renderers: {not_available}"
|
f"Rendered object requested unavailable MIME renderers: {not_available}"
|
||||||
@@ -135,7 +136,7 @@ def _write(element, value, append=False):
|
|||||||
element.append(out_element)
|
element.append(out_element)
|
||||||
else:
|
else:
|
||||||
out_element = element.lastElementChild
|
out_element = element.lastElementChild
|
||||||
if out_element is None:
|
if is_none(out_element):
|
||||||
out_element = element
|
out_element = element
|
||||||
|
|
||||||
if mime_type in ("application/javascript", "text/html"):
|
if mime_type in ("application/javascript", "text/html"):
|
||||||
@@ -146,12 +147,14 @@ def _write(element, value, append=False):
|
|||||||
|
|
||||||
|
|
||||||
def display(*values, target=None, append=True):
|
def display(*values, target=None, append=True):
|
||||||
if target is None:
|
if is_none(target):
|
||||||
target = current_target()
|
target = current_target()
|
||||||
elif not isinstance(target, str):
|
elif not isinstance(target, str):
|
||||||
raise TypeError(f"target must be str or None, not {target.__class__.__name__}")
|
msg = f"target must be str or None, not {target.__class__.__name__}"
|
||||||
|
raise TypeError(msg)
|
||||||
elif target == "":
|
elif target == "":
|
||||||
raise ValueError("Cannot have an empty target")
|
msg = "Cannot have an empty target"
|
||||||
|
raise ValueError(msg)
|
||||||
elif target.startswith("#"):
|
elif target.startswith("#"):
|
||||||
# note: here target is str and not None!
|
# note: here target is str and not None!
|
||||||
# align with @when behavior
|
# align with @when behavior
|
||||||
@@ -160,10 +163,9 @@ def display(*values, target=None, append=True):
|
|||||||
element = document.getElementById(target)
|
element = document.getElementById(target)
|
||||||
|
|
||||||
# If target cannot be found on the page, a ValueError is raised
|
# If target cannot be found on the page, a ValueError is raised
|
||||||
if element is None:
|
if is_none(element):
|
||||||
raise ValueError(
|
msg = f"Invalid selector with id={target}. Cannot be found in the page."
|
||||||
f"Invalid selector with id={target}. Cannot be found in the page."
|
raise ValueError(msg)
|
||||||
)
|
|
||||||
|
|
||||||
# if element is a <script type="py">, it has a 'target' attribute which
|
# if element is a <script type="py">, it has a 'target' attribute which
|
||||||
# points to the visual element holding the displayed values. In that case,
|
# points to the visual element holding the displayed values. In that case,
|
||||||
|
|||||||
@@ -1,76 +0,0 @@
|
|||||||
import inspect
|
|
||||||
|
|
||||||
try:
|
|
||||||
from pyodide.ffi.wrappers import add_event_listener
|
|
||||||
|
|
||||||
except ImportError:
|
|
||||||
|
|
||||||
def add_event_listener(el, event_type, func):
|
|
||||||
el.addEventListener(event_type, func)
|
|
||||||
|
|
||||||
|
|
||||||
from pyscript.magic_js import document
|
|
||||||
|
|
||||||
|
|
||||||
def when(event_type=None, selector=None):
|
|
||||||
"""
|
|
||||||
Decorates a function and passes py-* events to the decorated function
|
|
||||||
The events might or not be an argument of the decorated function
|
|
||||||
"""
|
|
||||||
|
|
||||||
def decorator(func):
|
|
||||||
|
|
||||||
from pyscript.web import Element, ElementCollection
|
|
||||||
|
|
||||||
if isinstance(selector, str):
|
|
||||||
elements = document.querySelectorAll(selector)
|
|
||||||
# TODO: This is a hack that will be removed when pyscript becomes a package
|
|
||||||
# and we can better manage the imports without circular dependencies
|
|
||||||
elif isinstance(selector, Element):
|
|
||||||
elements = [selector._dom_element]
|
|
||||||
elif isinstance(selector, ElementCollection):
|
|
||||||
elements = [el._dom_element for el in selector]
|
|
||||||
else:
|
|
||||||
if isinstance(selector, list):
|
|
||||||
elements = selector
|
|
||||||
else:
|
|
||||||
elements = [selector]
|
|
||||||
|
|
||||||
try:
|
|
||||||
sig = inspect.signature(func)
|
|
||||||
# Function doesn't receive events
|
|
||||||
if not sig.parameters:
|
|
||||||
|
|
||||||
# Function is async: must be awaited
|
|
||||||
if inspect.iscoroutinefunction(func):
|
|
||||||
|
|
||||||
async def wrapper(*args, **kwargs):
|
|
||||||
await func()
|
|
||||||
|
|
||||||
else:
|
|
||||||
|
|
||||||
def wrapper(*args, **kwargs):
|
|
||||||
func()
|
|
||||||
|
|
||||||
else:
|
|
||||||
wrapper = func
|
|
||||||
|
|
||||||
except AttributeError:
|
|
||||||
# TODO: this is very ugly hack to get micropython working because inspect.signature
|
|
||||||
# doesn't exist, but we need to actually properly replace inspect.signature.
|
|
||||||
# It may be actually better to not try any magic for now and raise the error
|
|
||||||
def wrapper(*args, **kwargs):
|
|
||||||
try:
|
|
||||||
return func(*args, **kwargs)
|
|
||||||
except TypeError as e:
|
|
||||||
if "takes" in str(e) and "positional arguments" in str(e):
|
|
||||||
return func()
|
|
||||||
|
|
||||||
raise
|
|
||||||
|
|
||||||
for el in elements:
|
|
||||||
add_event_listener(el, event_type, wrapper)
|
|
||||||
|
|
||||||
return func
|
|
||||||
|
|
||||||
return decorator
|
|
||||||
134
core/src/stdlib/pyscript/events.py
Normal file
134
core/src/stdlib/pyscript/events.py
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
import asyncio
|
||||||
|
import inspect
|
||||||
|
import sys
|
||||||
|
|
||||||
|
from functools import wraps
|
||||||
|
from pyscript.magic_js import document
|
||||||
|
from pyscript.ffi import create_proxy
|
||||||
|
from pyscript.util import is_awaitable
|
||||||
|
from pyscript import config
|
||||||
|
|
||||||
|
|
||||||
|
class Event:
|
||||||
|
"""
|
||||||
|
Represents something that may happen at some point in the future.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self._listeners = []
|
||||||
|
|
||||||
|
def trigger(self, result):
|
||||||
|
"""
|
||||||
|
Trigger the event with a result to pass into the handlers.
|
||||||
|
"""
|
||||||
|
for listener in self._listeners:
|
||||||
|
if is_awaitable(listener):
|
||||||
|
# Use create task to avoid making this an async function.
|
||||||
|
asyncio.create_task(listener(result))
|
||||||
|
else:
|
||||||
|
listener(result)
|
||||||
|
|
||||||
|
def add_listener(self, listener):
|
||||||
|
"""
|
||||||
|
Add a callable/awaitable to listen to when this event is triggered.
|
||||||
|
"""
|
||||||
|
if is_awaitable(listener) or callable(listener):
|
||||||
|
if listener not in self._listeners:
|
||||||
|
self._listeners.append(listener)
|
||||||
|
else:
|
||||||
|
msg = "Listener must be callable or awaitable."
|
||||||
|
raise ValueError(msg)
|
||||||
|
|
||||||
|
def remove_listener(self, *args):
|
||||||
|
"""
|
||||||
|
Clear the specified handler functions in *args. If no handlers
|
||||||
|
provided, clear all handlers.
|
||||||
|
"""
|
||||||
|
if args:
|
||||||
|
for listener in args:
|
||||||
|
self._listeners.remove(listener)
|
||||||
|
else:
|
||||||
|
self._listeners = []
|
||||||
|
|
||||||
|
|
||||||
|
def when(target, *args, **kwargs):
|
||||||
|
"""
|
||||||
|
Add an event listener to the target element(s) for the specified event type.
|
||||||
|
|
||||||
|
The target can be a string representing the event type, or an Event object.
|
||||||
|
If the target is an Event object, the event listener will be added to that
|
||||||
|
object. If the target is a string, the event listener will be added to the
|
||||||
|
element(s) that match the (second) selector argument.
|
||||||
|
|
||||||
|
If a (third) handler argument is provided, it will be called when the event
|
||||||
|
is triggered; thus allowing this to be used as both a function and a
|
||||||
|
decorator.
|
||||||
|
"""
|
||||||
|
# If "when" is called as a function, try to grab the handler from the
|
||||||
|
# arguments. If there's no handler, this must be a decorator based call.
|
||||||
|
handler = None
|
||||||
|
if args and (callable(args[0]) or is_awaitable(args[0])):
|
||||||
|
handler = args[0]
|
||||||
|
elif callable(kwargs.get("handler")) or is_awaitable(kwargs.get("handler")):
|
||||||
|
handler = kwargs.pop("handler")
|
||||||
|
# If the target is a string, it is the "older" use of `when` where it
|
||||||
|
# represents the name of a DOM event.
|
||||||
|
if isinstance(target, str):
|
||||||
|
# Extract the selector from the arguments or keyword arguments.
|
||||||
|
selector = args[0] if args else kwargs.pop("selector")
|
||||||
|
if not selector:
|
||||||
|
msg = "No selector provided."
|
||||||
|
raise ValueError(msg)
|
||||||
|
# Grab the DOM elements to which the target event will be attached.
|
||||||
|
from pyscript.web import Element, ElementCollection
|
||||||
|
|
||||||
|
if isinstance(selector, str):
|
||||||
|
elements = document.querySelectorAll(selector)
|
||||||
|
elif isinstance(selector, Element):
|
||||||
|
elements = [selector._dom_element]
|
||||||
|
elif isinstance(selector, ElementCollection):
|
||||||
|
elements = [el._dom_element for el in selector]
|
||||||
|
else:
|
||||||
|
elements = selector if isinstance(selector, list) else [selector]
|
||||||
|
|
||||||
|
def decorator(func):
|
||||||
|
sig = inspect.signature(func)
|
||||||
|
if sig.parameters:
|
||||||
|
if is_awaitable(func):
|
||||||
|
|
||||||
|
async def wrapper(event):
|
||||||
|
return await func(event)
|
||||||
|
|
||||||
|
else:
|
||||||
|
wrapper = func
|
||||||
|
else:
|
||||||
|
# Function doesn't receive events.
|
||||||
|
if is_awaitable(func):
|
||||||
|
|
||||||
|
async def wrapper(*args, **kwargs):
|
||||||
|
return await func()
|
||||||
|
|
||||||
|
else:
|
||||||
|
|
||||||
|
def wrapper(*args, **kwargs):
|
||||||
|
return func()
|
||||||
|
|
||||||
|
wrapper = wraps(func)(wrapper)
|
||||||
|
if isinstance(target, Event):
|
||||||
|
# The target is a single Event object.
|
||||||
|
target.add_listener(wrapper)
|
||||||
|
elif isinstance(target, list) and all(isinstance(t, Event) for t in target):
|
||||||
|
# The target is a list of Event objects.
|
||||||
|
for evt in target:
|
||||||
|
evt.add_listener(wrapper)
|
||||||
|
else:
|
||||||
|
# The target is a string representing an event type, and so a
|
||||||
|
# DOM element or collection of elements is found in "elements".
|
||||||
|
for el in elements:
|
||||||
|
el.addEventListener(target, create_proxy(wrapper))
|
||||||
|
return wrapper
|
||||||
|
|
||||||
|
# If "when" was called as a decorator, return the decorator function,
|
||||||
|
# otherwise just call the internal decorator function with the supplied
|
||||||
|
# handler.
|
||||||
|
return decorator(handler) if handler else decorator
|
||||||
@@ -2,8 +2,10 @@ try:
|
|||||||
import js
|
import js
|
||||||
from pyodide.ffi import create_proxy as _cp
|
from pyodide.ffi import create_proxy as _cp
|
||||||
from pyodide.ffi import to_js as _py_tjs
|
from pyodide.ffi import to_js as _py_tjs
|
||||||
|
from pyodide.ffi import jsnull
|
||||||
|
|
||||||
from_entries = js.Object.fromEntries
|
from_entries = js.Object.fromEntries
|
||||||
|
is_none = lambda value: value is None or value is jsnull
|
||||||
|
|
||||||
def _tjs(value, **kw):
|
def _tjs(value, **kw):
|
||||||
if not hasattr(kw, "dict_converter"):
|
if not hasattr(kw, "dict_converter"):
|
||||||
@@ -13,6 +15,34 @@ try:
|
|||||||
except:
|
except:
|
||||||
from jsffi import create_proxy as _cp
|
from jsffi import create_proxy as _cp
|
||||||
from jsffi import to_js as _tjs
|
from jsffi import to_js as _tjs
|
||||||
|
import js
|
||||||
|
|
||||||
|
jsnull = js.Object.getPrototypeOf(js.Object.prototype)
|
||||||
|
is_none = lambda value: value is None or value is jsnull
|
||||||
|
|
||||||
create_proxy = _cp
|
create_proxy = _cp
|
||||||
to_js = _tjs
|
to_js = _tjs
|
||||||
|
|
||||||
|
try:
|
||||||
|
from polyscript import ffi as _ffi
|
||||||
|
|
||||||
|
direct = _ffi.direct
|
||||||
|
gather = _ffi.gather
|
||||||
|
query = _ffi.query
|
||||||
|
|
||||||
|
def assign(source, *args):
|
||||||
|
for arg in args:
|
||||||
|
_ffi.assign(source, to_js(arg))
|
||||||
|
return source
|
||||||
|
|
||||||
|
except:
|
||||||
|
import js
|
||||||
|
|
||||||
|
_assign = js.Object.assign
|
||||||
|
|
||||||
|
direct = lambda source: source
|
||||||
|
|
||||||
|
def assign(source, *args):
|
||||||
|
for arg in args:
|
||||||
|
_assign(source, to_js(arg))
|
||||||
|
return source
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ def _object_keys(value):
|
|||||||
|
|
||||||
|
|
||||||
def _is_array(value):
|
def _is_array(value):
|
||||||
return isinstance(value, list) or isinstance(value, tuple)
|
return isinstance(value, (list, tuple))
|
||||||
|
|
||||||
|
|
||||||
def _is_object(value):
|
def _is_object(value):
|
||||||
@@ -60,10 +60,10 @@ def _loop(keys, input, known, output):
|
|||||||
|
|
||||||
|
|
||||||
def _ref(key, value, input, known, output):
|
def _ref(key, value, input, known, output):
|
||||||
if _is_array(value) and not value in known:
|
if _is_array(value) and value not in known:
|
||||||
known.append(value)
|
known.append(value)
|
||||||
value = _loop(_array_keys(value), input, known, value)
|
value = _loop(_array_keys(value), input, known, value)
|
||||||
elif _is_object(value) and not value in known:
|
elif _is_object(value) and value not in known:
|
||||||
known.append(value)
|
known.append(value)
|
||||||
value = _loop(_object_keys(value), input, known, value)
|
value = _loop(_object_keys(value), input, known, value)
|
||||||
|
|
||||||
|
|||||||
102
core/src/stdlib/pyscript/fs.py
Normal file
102
core/src/stdlib/pyscript/fs.py
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
mounted = {}
|
||||||
|
|
||||||
|
|
||||||
|
async def get_handler(details):
|
||||||
|
handler = details.handler
|
||||||
|
options = details.options
|
||||||
|
permission = await handler.queryPermission(options)
|
||||||
|
return handler if permission == "granted" else None
|
||||||
|
|
||||||
|
|
||||||
|
async def mount(path, mode="readwrite", root="", id="pyscript"):
|
||||||
|
import js
|
||||||
|
from _pyscript import fs, interpreter
|
||||||
|
from pyscript.ffi import to_js
|
||||||
|
from pyscript.magic_js import (
|
||||||
|
RUNNING_IN_WORKER,
|
||||||
|
sync,
|
||||||
|
)
|
||||||
|
|
||||||
|
js.console.warn("experimental pyscript.fs ⚠️")
|
||||||
|
|
||||||
|
details = None
|
||||||
|
handler = None
|
||||||
|
|
||||||
|
uid = f"{path}@{id}"
|
||||||
|
|
||||||
|
options = {"id": id, "mode": mode}
|
||||||
|
if root != "":
|
||||||
|
options["startIn"] = root
|
||||||
|
|
||||||
|
if RUNNING_IN_WORKER:
|
||||||
|
fsh = sync.storeFSHandler(uid, to_js(options))
|
||||||
|
|
||||||
|
# allow both async and/or SharedArrayBuffer use case
|
||||||
|
if isinstance(fsh, bool):
|
||||||
|
success = fsh
|
||||||
|
else:
|
||||||
|
success = await fsh
|
||||||
|
|
||||||
|
if success:
|
||||||
|
from polyscript import IDBMap
|
||||||
|
from pyscript import window
|
||||||
|
|
||||||
|
idbm = IDBMap.new(fs.NAMESPACE)
|
||||||
|
details = await idbm.get(uid)
|
||||||
|
handler = await get_handler(details)
|
||||||
|
if handler is None:
|
||||||
|
# force await in either async or sync scenario
|
||||||
|
await js.Promise.resolve(sync.getFSHandler(details.options))
|
||||||
|
handler = details.handler
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise RuntimeError(fs.ERROR)
|
||||||
|
|
||||||
|
else:
|
||||||
|
success = await fs.idb.has(uid)
|
||||||
|
|
||||||
|
if success:
|
||||||
|
details = await fs.idb.get(uid)
|
||||||
|
handler = await get_handler(details)
|
||||||
|
if handler is None:
|
||||||
|
handler = await fs.getFileSystemDirectoryHandle(details.options)
|
||||||
|
else:
|
||||||
|
js_options = to_js(options)
|
||||||
|
handler = await fs.getFileSystemDirectoryHandle(js_options)
|
||||||
|
details = {"handler": handler, "options": js_options}
|
||||||
|
await fs.idb.set(uid, to_js(details))
|
||||||
|
|
||||||
|
mounted[path] = await interpreter.mountNativeFS(path, handler)
|
||||||
|
|
||||||
|
|
||||||
|
async def revoke(path, id="pyscript"):
|
||||||
|
from _pyscript import fs, interpreter
|
||||||
|
from pyscript.magic_js import (
|
||||||
|
RUNNING_IN_WORKER,
|
||||||
|
sync,
|
||||||
|
)
|
||||||
|
|
||||||
|
uid = f"{path}@{id}"
|
||||||
|
|
||||||
|
if RUNNING_IN_WORKER:
|
||||||
|
had = sync.deleteFSHandler(uid)
|
||||||
|
else:
|
||||||
|
had = await fs.idb.has(uid)
|
||||||
|
if had:
|
||||||
|
had = await fs.idb.delete(uid)
|
||||||
|
|
||||||
|
if had:
|
||||||
|
interpreter._module.FS.unmount(path)
|
||||||
|
|
||||||
|
return had
|
||||||
|
|
||||||
|
|
||||||
|
async def sync(path):
|
||||||
|
await mounted[path].syncfs()
|
||||||
|
|
||||||
|
|
||||||
|
async def unmount(path):
|
||||||
|
from _pyscript import interpreter
|
||||||
|
|
||||||
|
await sync(path)
|
||||||
|
interpreter._module.FS.unmount(path)
|
||||||
@@ -25,6 +25,7 @@ class JSModule:
|
|||||||
# avoid pyodide looking for non existent fields
|
# avoid pyodide looking for non existent fields
|
||||||
if not field.startswith("_"):
|
if not field.startswith("_"):
|
||||||
return getattr(getattr(js_modules, self.name), field)
|
return getattr(getattr(js_modules, self.name), field)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
# generate N modules in the system that will proxy the real value
|
# generate N modules in the system that will proxy the real value
|
||||||
@@ -66,7 +67,11 @@ if RUNNING_IN_WORKER:
|
|||||||
|
|
||||||
else:
|
else:
|
||||||
import _pyscript
|
import _pyscript
|
||||||
from _pyscript import PyWorker, js_import
|
from _pyscript import PyWorker as _PyWorker, js_import
|
||||||
|
from pyscript.ffi import to_js
|
||||||
|
|
||||||
|
def PyWorker(url, **kw):
|
||||||
|
return _PyWorker(url, to_js(kw))
|
||||||
|
|
||||||
window = globalThis
|
window = globalThis
|
||||||
document = globalThis.document
|
document = globalThis.document
|
||||||
|
|||||||
@@ -31,26 +31,22 @@ class Device:
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
async def load(cls, audio=False, video=True):
|
async def load(cls, audio=False, video=True):
|
||||||
"""Load the device stream."""
|
"""
|
||||||
options = window.Object.new()
|
Load the device stream.
|
||||||
options.audio = audio
|
"""
|
||||||
|
options = {}
|
||||||
|
options["audio"] = audio
|
||||||
if isinstance(video, bool):
|
if isinstance(video, bool):
|
||||||
options.video = video
|
options["video"] = video
|
||||||
else:
|
else:
|
||||||
# TODO: Think this can be simplified but need to check it on the pyodide side
|
options["video"] = {}
|
||||||
|
|
||||||
# TODO: this is pyodide specific. shouldn't be!
|
|
||||||
options.video = window.Object.new()
|
|
||||||
for k in video:
|
for k in video:
|
||||||
setattr(options.video, k, to_js(video[k]))
|
options["video"][k] = video[k]
|
||||||
|
return await window.navigator.mediaDevices.getUserMedia(to_js(options))
|
||||||
stream = await window.navigator.mediaDevices.getUserMedia(options)
|
|
||||||
return stream
|
|
||||||
|
|
||||||
async def get_stream(self):
|
async def get_stream(self):
|
||||||
key = self.kind.replace("input", "").replace("output", "")
|
key = self.kind.replace("input", "").replace("output", "")
|
||||||
options = {key: {"deviceId": {"exact": self.id}}}
|
options = {key: {"deviceId": {"exact": self.id}}}
|
||||||
|
|
||||||
return await self.load(**options)
|
return await self.load(**options)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,19 +1,21 @@
|
|||||||
from polyscript import storage as _storage
|
from polyscript import storage as _storage
|
||||||
from pyscript.flatted import parse as _parse
|
from pyscript.flatted import parse as _parse
|
||||||
from pyscript.flatted import stringify as _stringify
|
from pyscript.flatted import stringify as _stringify
|
||||||
|
from pyscript.ffi import is_none
|
||||||
|
|
||||||
|
|
||||||
# convert a Python value into an IndexedDB compatible entry
|
# convert a Python value into an IndexedDB compatible entry
|
||||||
def _to_idb(value):
|
def _to_idb(value):
|
||||||
if value is None:
|
if is_none(value):
|
||||||
return _stringify(["null", 0])
|
return _stringify(["null", 0])
|
||||||
if isinstance(value, (bool, float, int, str, list, dict, tuple)):
|
if isinstance(value, (bool, float, int, str, list, dict, tuple)):
|
||||||
return _stringify(["generic", value])
|
return _stringify(["generic", value])
|
||||||
if isinstance(value, bytearray):
|
if isinstance(value, bytearray):
|
||||||
return _stringify(["bytearray", [v for v in value]])
|
return _stringify(["bytearray", list(value)])
|
||||||
if isinstance(value, memoryview):
|
if isinstance(value, memoryview):
|
||||||
return _stringify(["memoryview", [v for v in value]])
|
return _stringify(["memoryview", list(value)])
|
||||||
raise TypeError(f"Unexpected value: {value}")
|
msg = f"Unexpected value: {value}"
|
||||||
|
raise TypeError(msg)
|
||||||
|
|
||||||
|
|
||||||
# convert an IndexedDB compatible entry into a Python value
|
# convert an IndexedDB compatible entry into a Python value
|
||||||
@@ -56,5 +58,6 @@ class Storage(dict):
|
|||||||
|
|
||||||
async def storage(name="", storage_class=Storage):
|
async def storage(name="", storage_class=Storage):
|
||||||
if not name:
|
if not name:
|
||||||
raise ValueError("The storage name must be defined")
|
msg = "The storage name must be defined"
|
||||||
|
raise ValueError(msg)
|
||||||
return storage_class(await _storage(f"@pyscript/{name}"))
|
return storage_class(await _storage(f"@pyscript/{name}"))
|
||||||
|
|||||||
@@ -1,11 +1,17 @@
|
|||||||
import js
|
import js
|
||||||
|
import sys
|
||||||
|
import inspect
|
||||||
|
|
||||||
|
|
||||||
def as_bytearray(buffer):
|
def as_bytearray(buffer):
|
||||||
|
"""
|
||||||
|
Given a JavaScript ArrayBuffer, convert it to a Python bytearray in a
|
||||||
|
MicroPython friendly manner.
|
||||||
|
"""
|
||||||
ui8a = js.Uint8Array.new(buffer)
|
ui8a = js.Uint8Array.new(buffer)
|
||||||
size = ui8a.length
|
size = ui8a.length
|
||||||
ba = bytearray(size)
|
ba = bytearray(size)
|
||||||
for i in range(0, size):
|
for i in range(size):
|
||||||
ba[i] = ui8a[i]
|
ba[i] = ui8a[i]
|
||||||
return ba
|
return ba
|
||||||
|
|
||||||
@@ -31,3 +37,22 @@ class NotSupported:
|
|||||||
|
|
||||||
def __call__(self, *args):
|
def __call__(self, *args):
|
||||||
raise TypeError(self.error)
|
raise TypeError(self.error)
|
||||||
|
|
||||||
|
|
||||||
|
def is_awaitable(obj):
|
||||||
|
"""
|
||||||
|
Returns a boolean indication if the passed in obj is an awaitable
|
||||||
|
function. (MicroPython treats awaitables as generator functions, and if
|
||||||
|
the object is a closure containing an async function we need to work
|
||||||
|
carefully.)
|
||||||
|
"""
|
||||||
|
from pyscript import config
|
||||||
|
|
||||||
|
if config["type"] == "mpy": # Is MicroPython?
|
||||||
|
# MicroPython doesn't appear to have a way to determine if a closure is
|
||||||
|
# an async function except via the repr. This is a bit hacky.
|
||||||
|
if "<closure <generator>" in repr(obj):
|
||||||
|
return True
|
||||||
|
return inspect.isgeneratorfunction(obj)
|
||||||
|
|
||||||
|
return inspect.iscoroutinefunction(obj)
|
||||||
|
|||||||
@@ -2,7 +2,11 @@
|
|||||||
|
|
||||||
# `when` is not used in this module. It is imported here save the user an additional
|
# `when` is not used in this module. It is imported here save the user an additional
|
||||||
# import (i.e. they can get what they need from `pyscript.web`).
|
# import (i.e. they can get what they need from `pyscript.web`).
|
||||||
from pyscript import document, when # NOQA
|
|
||||||
|
# from __future__ import annotations # CAUTION: This is not supported in MicroPython.
|
||||||
|
|
||||||
|
from pyscript import document, when, Event # noqa: F401
|
||||||
|
from pyscript.ffi import create_proxy, is_none
|
||||||
|
|
||||||
|
|
||||||
def wrap_dom_element(dom_element):
|
def wrap_dom_element(dom_element):
|
||||||
@@ -64,10 +68,24 @@ class Element:
|
|||||||
If `dom_element` is None we are being called to *create* a new element.
|
If `dom_element` is None we are being called to *create* a new element.
|
||||||
Otherwise, we are being called to *wrap* an existing DOM element.
|
Otherwise, we are being called to *wrap* an existing DOM element.
|
||||||
"""
|
"""
|
||||||
self._dom_element = dom_element or document.createElement(
|
self._dom_element = (
|
||||||
type(self).get_tag_name()
|
document.createElement(type(self).get_tag_name())
|
||||||
|
if is_none(dom_element)
|
||||||
|
else dom_element
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# HTML on_events attached to the element become pyscript.Event instances.
|
||||||
|
self._on_events = {}
|
||||||
|
|
||||||
|
# Handle kwargs for handling named events with a default handler function.
|
||||||
|
properties = {}
|
||||||
|
for name, handler in kwargs.items():
|
||||||
|
if name.startswith("on_"):
|
||||||
|
ev = self.get_event(name) # Create the default Event instance.
|
||||||
|
ev.add_listener(handler)
|
||||||
|
else:
|
||||||
|
properties[name] = handler
|
||||||
|
|
||||||
# A set-like interface to the element's `classList`.
|
# A set-like interface to the element's `classList`.
|
||||||
self._classes = Classes(self)
|
self._classes = Classes(self)
|
||||||
|
|
||||||
@@ -75,7 +93,7 @@ class Element:
|
|||||||
self._style = Style(self)
|
self._style = Style(self)
|
||||||
|
|
||||||
# Set any specified classes, styles, and DOM properties.
|
# Set any specified classes, styles, and DOM properties.
|
||||||
self.update(classes=classes, style=style, **kwargs)
|
self.update(classes=classes, style=style, **properties)
|
||||||
|
|
||||||
def __eq__(self, obj):
|
def __eq__(self, obj):
|
||||||
"""Check for equality by comparing the underlying DOM element."""
|
"""Check for equality by comparing the underlying DOM element."""
|
||||||
@@ -87,19 +105,32 @@ class Element:
|
|||||||
If `key` is an integer or a slice we use it to index/slice the element's
|
If `key` is an integer or a slice we use it to index/slice the element's
|
||||||
children. Otherwise, we use `key` as a query selector.
|
children. Otherwise, we use `key` as a query selector.
|
||||||
"""
|
"""
|
||||||
if isinstance(key, int) or isinstance(key, slice):
|
if isinstance(key, (int, slice)):
|
||||||
return self.children[key]
|
return self.children[key]
|
||||||
|
|
||||||
return self.find(key)
|
return self.find(key)
|
||||||
|
|
||||||
def __getattr__(self, name):
|
def __getattr__(self, name):
|
||||||
|
"""
|
||||||
|
Get an attribute from the element.
|
||||||
|
|
||||||
|
If the attribute is an event (e.g. "on_click"), we wrap it in an `Event`
|
||||||
|
instance and return that. Otherwise, we return the attribute from the
|
||||||
|
underlying DOM element.
|
||||||
|
"""
|
||||||
|
if name.startswith("on_"):
|
||||||
|
return self.get_event(name)
|
||||||
# This allows us to get attributes on the underlying DOM element that clash
|
# This allows us to get attributes on the underlying DOM element that clash
|
||||||
# with Python keywords or built-ins (e.g. the output element has an
|
# with Python keywords or built-ins (e.g. the output element has an
|
||||||
# attribute `for` which is a Python keyword, so you can access it on the
|
# attribute `for` which is a Python keyword, so you can access it on the
|
||||||
# Element instance via `for_`).
|
# Element instance via `for_`).
|
||||||
if name.endswith("_"):
|
if name.endswith("_"):
|
||||||
name = name[:-1]
|
name = name[:-1] # noqa: FURB188 No str.removesuffix() in MicroPython.
|
||||||
|
if name == "for":
|
||||||
|
# The `for` attribute is a special case as it is a keyword in both
|
||||||
|
# Python and JavaScript.
|
||||||
|
# We need to get it from the underlying DOM element as `htmlFor`.
|
||||||
|
name = "htmlFor"
|
||||||
return getattr(self._dom_element, name)
|
return getattr(self._dom_element, name)
|
||||||
|
|
||||||
def __setattr__(self, name, value):
|
def __setattr__(self, name, value):
|
||||||
@@ -117,10 +148,42 @@ class Element:
|
|||||||
# attribute `for` which is a Python keyword, so you can access it on the
|
# attribute `for` which is a Python keyword, so you can access it on the
|
||||||
# Element instance via `for_`).
|
# Element instance via `for_`).
|
||||||
if name.endswith("_"):
|
if name.endswith("_"):
|
||||||
name = name[:-1]
|
name = name[:-1] # noqa: FURB188 No str.removesuffix() in MicroPython.
|
||||||
|
if name == "for":
|
||||||
|
# The `for` attribute is a special case as it is a keyword in both
|
||||||
|
# Python and JavaScript.
|
||||||
|
# We need to set it on the underlying DOM element as `htmlFor`.
|
||||||
|
name = "htmlFor"
|
||||||
|
|
||||||
|
if name.startswith("on_"):
|
||||||
|
# Ensure on-events are cached in the _on_events dict if the
|
||||||
|
# user is setting them directly.
|
||||||
|
self._on_events[name] = value
|
||||||
|
|
||||||
setattr(self._dom_element, name, value)
|
setattr(self._dom_element, name, value)
|
||||||
|
|
||||||
|
def get_event(self, name):
|
||||||
|
"""
|
||||||
|
Get an `Event` instance for the specified event name.
|
||||||
|
"""
|
||||||
|
if not name.startswith("on_"):
|
||||||
|
msg = "Event names must start with 'on_'."
|
||||||
|
raise ValueError(msg)
|
||||||
|
event_name = name[3:] # Remove the "on_" prefix.
|
||||||
|
if not hasattr(self._dom_element, event_name):
|
||||||
|
msg = f"Element has no '{event_name}' event."
|
||||||
|
raise ValueError(msg)
|
||||||
|
if name in self._on_events:
|
||||||
|
return self._on_events[name]
|
||||||
|
# Such an on-event exists in the DOM element, but we haven't yet
|
||||||
|
# wrapped it in an Event instance. Let's do that now. When the
|
||||||
|
# underlying DOM element's event is triggered, the Event instance
|
||||||
|
# will be triggered too.
|
||||||
|
ev = Event()
|
||||||
|
self._on_events[name] = ev
|
||||||
|
self._dom_element.addEventListener(event_name, create_proxy(ev.trigger))
|
||||||
|
return ev
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def children(self):
|
def children(self):
|
||||||
"""Return the element's children as an `ElementCollection`."""
|
"""Return the element's children as an `ElementCollection`."""
|
||||||
@@ -134,7 +197,7 @@ class Element:
|
|||||||
@property
|
@property
|
||||||
def parent(self):
|
def parent(self):
|
||||||
"""Return the element's `parent `Element`."""
|
"""Return the element's `parent `Element`."""
|
||||||
if self._dom_element.parentElement is None:
|
if is_none(self._dom_element.parentElement):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
return Element.wrap_dom_element(self._dom_element.parentElement)
|
return Element.wrap_dom_element(self._dom_element.parentElement)
|
||||||
@@ -157,7 +220,7 @@ class Element:
|
|||||||
# We check for list/tuple here and NOT for any iterable as it will match
|
# We check for list/tuple here and NOT for any iterable as it will match
|
||||||
# a JS Nodelist which is handled explicitly below.
|
# a JS Nodelist which is handled explicitly below.
|
||||||
# NodeList.
|
# NodeList.
|
||||||
elif isinstance(item, list) or isinstance(item, tuple):
|
elif isinstance(item, (list, tuple)):
|
||||||
for child in item:
|
for child in item:
|
||||||
self.append(child)
|
self.append(child)
|
||||||
|
|
||||||
@@ -181,10 +244,11 @@ class Element:
|
|||||||
|
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
# Nope! This is not an element or a NodeList.
|
# Nope! This is not an element or a NodeList.
|
||||||
raise TypeError(
|
msg = (
|
||||||
f'Element "{item}" is a proxy object, "'
|
f'Element "{item}" is a proxy object, "'
|
||||||
f"but not a valid element or a NodeList."
|
f"but not a valid element or a NodeList."
|
||||||
)
|
)
|
||||||
|
raise TypeError(msg)
|
||||||
|
|
||||||
def clone(self, clone_id=None):
|
def clone(self, clone_id=None):
|
||||||
"""Make a clone of the element (clones the underlying DOM object too)."""
|
"""Make a clone of the element (clones the underlying DOM object too)."""
|
||||||
@@ -355,8 +419,7 @@ class Options:
|
|||||||
|
|
||||||
new_option = option(**kwargs)
|
new_option = option(**kwargs)
|
||||||
|
|
||||||
if before:
|
if before and isinstance(before, Element):
|
||||||
if isinstance(before, Element):
|
|
||||||
before = before._dom_element
|
before = before._dom_element
|
||||||
|
|
||||||
self._element._dom_element.add(new_option._dom_element, before)
|
self._element._dom_element.add(new_option._dom_element, before)
|
||||||
@@ -417,7 +480,7 @@ class ContainerElement(Element):
|
|||||||
)
|
)
|
||||||
|
|
||||||
for child in list(args) + (children or []):
|
for child in list(args) + (children or []):
|
||||||
if isinstance(child, Element) or isinstance(child, ElementCollection):
|
if isinstance(child, (Element, ElementCollection)):
|
||||||
self.append(child)
|
self.append(child)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
@@ -447,14 +510,13 @@ class ClassesCollection:
|
|||||||
)
|
)
|
||||||
|
|
||||||
def __iter__(self):
|
def __iter__(self):
|
||||||
for class_name in self._all_class_names():
|
yield from self._all_class_names()
|
||||||
yield class_name
|
|
||||||
|
|
||||||
def __len__(self):
|
def __len__(self):
|
||||||
return len(self._all_class_names())
|
return len(self._all_class_names())
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return f"ClassesCollection({repr(self._collection)})"
|
return f"ClassesCollection({self._collection!r})"
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return " ".join(self._all_class_names())
|
return " ".join(self._all_class_names())
|
||||||
@@ -507,7 +569,7 @@ class StyleCollection:
|
|||||||
element.style[key] = value
|
element.style[key] = value
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return f"StyleCollection({repr(self._collection)})"
|
return f"StyleCollection({self._collection!r})"
|
||||||
|
|
||||||
def remove(self, key):
|
def remove(self, key):
|
||||||
"""Remove a CSS property from the elements in the collection."""
|
"""Remove a CSS property from the elements in the collection."""
|
||||||
@@ -542,7 +604,7 @@ class ElementCollection:
|
|||||||
if isinstance(key, int):
|
if isinstance(key, int):
|
||||||
return self._elements[key]
|
return self._elements[key]
|
||||||
|
|
||||||
elif isinstance(key, slice):
|
if isinstance(key, slice):
|
||||||
return ElementCollection(self._elements[key])
|
return ElementCollection(self._elements[key])
|
||||||
|
|
||||||
return self.find(key)
|
return self.find(key)
|
||||||
@@ -1074,12 +1136,13 @@ class video(ContainerElement):
|
|||||||
width = width if width is not None else self.videoWidth
|
width = width if width is not None else self.videoWidth
|
||||||
height = height if height is not None else self.videoHeight
|
height = height if height is not None else self.videoHeight
|
||||||
|
|
||||||
if to is None:
|
if is_none(to):
|
||||||
to = canvas(width=width, height=height)
|
to = canvas(width=width, height=height)
|
||||||
|
|
||||||
elif isinstance(to, Element):
|
elif isinstance(to, Element):
|
||||||
if to.tag != "canvas":
|
if to.tag != "canvas":
|
||||||
raise TypeError("Element to snap to must be a canvas.")
|
msg = "Element to snap to must be a canvas."
|
||||||
|
raise TypeError(msg)
|
||||||
|
|
||||||
elif getattr(to, "tagName", "") == "CANVAS":
|
elif getattr(to, "tagName", "") == "CANVAS":
|
||||||
to = canvas(dom_element=to)
|
to = canvas(dom_element=to)
|
||||||
@@ -1088,10 +1151,12 @@ class video(ContainerElement):
|
|||||||
elif isinstance(to, str):
|
elif isinstance(to, str):
|
||||||
nodelist = document.querySelectorAll(to) # NOQA
|
nodelist = document.querySelectorAll(to) # NOQA
|
||||||
if nodelist.length == 0:
|
if nodelist.length == 0:
|
||||||
raise TypeError("No element with selector {to} to snap to.")
|
msg = "No element with selector {to} to snap to."
|
||||||
|
raise TypeError(msg)
|
||||||
|
|
||||||
if nodelist[0].tagName != "CANVAS":
|
if nodelist[0].tagName != "CANVAS":
|
||||||
raise TypeError("Element to snap to must be a canvas.")
|
msg = "Element to snap to must be a canvas."
|
||||||
|
raise TypeError(msg)
|
||||||
|
|
||||||
to = canvas(dom_element=nodelist[0])
|
to = canvas(dom_element=nodelist[0])
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import js
|
import js
|
||||||
from pyscript.ffi import create_proxy
|
from pyscript.ffi import create_proxy
|
||||||
from pyscript.util import as_bytearray
|
from pyscript.util import as_bytearray, is_awaitable
|
||||||
|
|
||||||
code = "code"
|
code = "code"
|
||||||
protocols = "protocols"
|
protocols = "protocols"
|
||||||
@@ -8,6 +8,23 @@ reason = "reason"
|
|||||||
methods = ["onclose", "onerror", "onmessage", "onopen"]
|
methods = ["onclose", "onerror", "onmessage", "onopen"]
|
||||||
|
|
||||||
|
|
||||||
|
def add_listener(socket, onevent, listener):
|
||||||
|
p = create_proxy(listener)
|
||||||
|
|
||||||
|
if is_awaitable(listener):
|
||||||
|
|
||||||
|
async def wrapper(e):
|
||||||
|
await p(EventMessage(e))
|
||||||
|
|
||||||
|
m = wrapper
|
||||||
|
|
||||||
|
else:
|
||||||
|
m = lambda e: p(EventMessage(e))
|
||||||
|
|
||||||
|
# Pyodide fails at setting socket[onevent] directly
|
||||||
|
setattr(socket, onevent, m)
|
||||||
|
|
||||||
|
|
||||||
class EventMessage:
|
class EventMessage:
|
||||||
def __init__(self, event):
|
def __init__(self, event):
|
||||||
self._event = event
|
self._event = event
|
||||||
@@ -24,7 +41,7 @@ class EventMessage:
|
|||||||
return value
|
return value
|
||||||
|
|
||||||
|
|
||||||
class WebSocket(object):
|
class WebSocket:
|
||||||
CONNECTING = 0
|
CONNECTING = 0
|
||||||
OPEN = 1
|
OPEN = 1
|
||||||
CLOSING = 2
|
CLOSING = 2
|
||||||
@@ -36,20 +53,20 @@ class WebSocket(object):
|
|||||||
socket = js.WebSocket.new(url, kw[protocols])
|
socket = js.WebSocket.new(url, kw[protocols])
|
||||||
else:
|
else:
|
||||||
socket = js.WebSocket.new(url)
|
socket = js.WebSocket.new(url)
|
||||||
|
|
||||||
|
socket.binaryType = "arraybuffer"
|
||||||
object.__setattr__(self, "_ws", socket)
|
object.__setattr__(self, "_ws", socket)
|
||||||
|
|
||||||
for t in methods:
|
for t in methods:
|
||||||
if t in kw:
|
if t in kw:
|
||||||
# Pyodide fails at setting socket[t] directly
|
add_listener(socket, t, kw[t])
|
||||||
setattr(socket, t, create_proxy(kw[t]))
|
|
||||||
|
|
||||||
def __getattr__(self, attr):
|
def __getattr__(self, attr):
|
||||||
return getattr(self._ws, attr)
|
return getattr(self._ws, attr)
|
||||||
|
|
||||||
def __setattr__(self, attr, value):
|
def __setattr__(self, attr, value):
|
||||||
if attr in methods:
|
if attr in methods:
|
||||||
m = lambda e: value(EventMessage(e))
|
add_listener(self._ws, attr, value)
|
||||||
setattr(self._ws, attr, create_proxy(m))
|
|
||||||
else:
|
else:
|
||||||
setattr(self._ws, attr, value)
|
setattr(self._ws, attr, value)
|
||||||
|
|
||||||
|
|||||||
@@ -25,10 +25,12 @@ async def create_named_worker(src="", name="", config=None, type="py"):
|
|||||||
from json import dumps
|
from json import dumps
|
||||||
|
|
||||||
if not src:
|
if not src:
|
||||||
raise ValueError("Named workers require src")
|
msg = "Named workers require src"
|
||||||
|
raise ValueError(msg)
|
||||||
|
|
||||||
if not name:
|
if not name:
|
||||||
raise ValueError("Named workers require a name")
|
msg = "Named workers require a name"
|
||||||
|
raise ValueError(msg)
|
||||||
|
|
||||||
s = _js.document.createElement("script")
|
s = _js.document.createElement("script")
|
||||||
s.type = type
|
s.type = type
|
||||||
@@ -37,7 +39,7 @@ async def create_named_worker(src="", name="", config=None, type="py"):
|
|||||||
_set(s, "name", name)
|
_set(s, "name", name)
|
||||||
|
|
||||||
if config:
|
if config:
|
||||||
_set(s, "config", isinstance(config, str) and config or dumps(config))
|
_set(s, "config", (isinstance(config, str) and config) or dumps(config))
|
||||||
|
|
||||||
_js.document.body.append(s)
|
_js.document.body.append(s)
|
||||||
return await workers[name]
|
return await workers[name]
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
import { ArrayBuffer, TypedArray } from "sabayon/shared";
|
|
||||||
import IDBMapSync from "@webreflection/idb-map/sync";
|
import IDBMapSync from "@webreflection/idb-map/sync";
|
||||||
import { parse, stringify } from "flatted";
|
import { parse, stringify } from "flatted";
|
||||||
|
|
||||||
|
const { isView } = ArrayBuffer;
|
||||||
|
|
||||||
const to_idb = (value) => {
|
const to_idb = (value) => {
|
||||||
if (value == null) return stringify(["null", 0]);
|
if (value == null) return stringify(["null", 0]);
|
||||||
/* eslint-disable no-fallthrough */
|
/* eslint-disable no-fallthrough */
|
||||||
switch (typeof value) {
|
switch (typeof value) {
|
||||||
case "object": {
|
case "object": {
|
||||||
if (value instanceof TypedArray)
|
if (isView(value)) return stringify(["memoryview", [...value]]);
|
||||||
return stringify(["memoryview", [...value]]);
|
|
||||||
if (value instanceof ArrayBuffer)
|
if (value instanceof ArrayBuffer)
|
||||||
return stringify(["bytearray", [...new Uint8Array(value)]]);
|
return stringify(["bytearray", [...new Uint8Array(value)]]);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { idb, getFileSystemDirectoryHandle } from "./fs.js";
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
// allow pyterminal checks to bootstrap
|
// allow pyterminal checks to bootstrap
|
||||||
is_pyterminal: () => false,
|
is_pyterminal: () => false,
|
||||||
@@ -9,4 +11,34 @@ export default {
|
|||||||
sleep(seconds) {
|
sleep(seconds) {
|
||||||
return new Promise(($) => setTimeout($, seconds * 1000));
|
return new Promise(($) => setTimeout($, seconds * 1000));
|
||||||
},
|
},
|
||||||
|
|
||||||
|
getFSHandler: (options) => getFileSystemDirectoryHandle(options),
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ask a user action via dialog and returns the directory handler once granted.
|
||||||
|
* @param {string} uid
|
||||||
|
* @param {{id?:string, mode?:"read"|"readwrite", hint?:"desktop"|"documents"|"downloads"|"music"|"pictures"|"videos"}} options
|
||||||
|
* @returns {Promise<boolean>}
|
||||||
|
*/
|
||||||
|
async storeFSHandler(uid, options = {}) {
|
||||||
|
if (await idb.has(uid)) return true;
|
||||||
|
return getFileSystemDirectoryHandle(options).then(
|
||||||
|
async (handler) => {
|
||||||
|
await idb.set(uid, { handler, options });
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
() => false,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Explicitly remove the unique identifier for the FS handler.
|
||||||
|
* @param {string} uid
|
||||||
|
* @returns {Promise<boolean>}
|
||||||
|
*/
|
||||||
|
async deleteFSHandler(uid) {
|
||||||
|
const had = await idb.has(uid);
|
||||||
|
if (had) await idb.delete(uid);
|
||||||
|
return had;
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
7
core/src/zero-redirect.js
Normal file
7
core/src/zero-redirect.js
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
/* eslint no-unused-vars: 0 */
|
||||||
|
try {
|
||||||
|
crypto.randomUUID();
|
||||||
|
} catch (_) {
|
||||||
|
if (location.href.startsWith("http://0.0.0.0"))
|
||||||
|
location.href = location.href.replace("0.0.0.0", "localhost");
|
||||||
|
}
|
||||||
File diff suppressed because one or more lines are too long
1
core/tests/javascript/config-parser/file.py
Normal file
1
core/tests/javascript/config-parser/file.py
Normal file
@@ -0,0 +1 @@
|
|||||||
|
print("OK")
|
||||||
21
core/tests/javascript/config-parser/index.html
Normal file
21
core/tests/javascript/config-parser/index.html
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<link rel="stylesheet" href="../../../dist/core.css">
|
||||||
|
<script type="module" src="../../../dist/core.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<py-config config-parser="https://esm.run/basic-toml">
|
||||||
|
[files]
|
||||||
|
'file.py' = ""
|
||||||
|
</py-config>
|
||||||
|
<script type="py">
|
||||||
|
import file
|
||||||
|
from pyscript import document
|
||||||
|
document.documentElement.classList.add("done")
|
||||||
|
document.body.append("OK")
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
39
core/tests/javascript/media.html
Normal file
39
core/tests/javascript/media.html
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<title>Pyodide Media Module Test</title>
|
||||||
|
<link rel="stylesheet" href="../../dist/core.css">
|
||||||
|
<script type="module" src="../../dist/core.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Pyodide Media Module Test</h1>
|
||||||
|
<div id="test-results">Running tests...</div>
|
||||||
|
|
||||||
|
<script type="py" terminal>
|
||||||
|
from pyscript import window, document
|
||||||
|
from pyscript import media
|
||||||
|
|
||||||
|
async def run_tests():
|
||||||
|
# Test basic module structure
|
||||||
|
assert hasattr(media, "Device"), "media module should have Device class"
|
||||||
|
assert hasattr(media, "list_devices"), "media module should have list_devices function"
|
||||||
|
|
||||||
|
# Test device enumeration
|
||||||
|
devices = await media.list_devices()
|
||||||
|
assert isinstance(devices, list), "list_devices should return a list"
|
||||||
|
|
||||||
|
# If we have devices, test properties of one
|
||||||
|
if devices:
|
||||||
|
device = devices[0]
|
||||||
|
assert hasattr(device, "id"), "Device should have id property"
|
||||||
|
assert hasattr(device, "group"), "Device should have group property"
|
||||||
|
assert hasattr(device, "kind"), "Device should have kind property"
|
||||||
|
assert hasattr(device, "label"), "Device should have label property"
|
||||||
|
|
||||||
|
document.getElementById('test-results').innerText = "Success!"
|
||||||
|
document.documentElement.classList.add('media-ok')
|
||||||
|
|
||||||
|
await run_tests()
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import numpy
|
import numpy as np
|
||||||
import matplotlib
|
import matplotlib as mpl
|
||||||
|
|
||||||
# just do something with the packages
|
# just do something with the packages
|
||||||
print(len(dir(numpy)))
|
print(len(dir(np)))
|
||||||
print(len(dir(matplotlib)))
|
print(len(dir(mpl)))
|
||||||
|
|||||||
17
core/tests/javascript/pyodide-lockfile/index.html
Normal file
17
core/tests/javascript/pyodide-lockfile/index.html
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<link rel="stylesheet" href="../../../dist/core.css">
|
||||||
|
<script type="module" src="../../../dist/core.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<script type="py" config='{"packages":["jsonpointer==3.0.0"]}'>
|
||||||
|
import jsonpointer
|
||||||
|
from pyscript import document
|
||||||
|
document.documentElement.classList.add("done")
|
||||||
|
document.body.append("OK")
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -2,7 +2,7 @@ from pyscript import document
|
|||||||
|
|
||||||
classList = document.documentElement.classList
|
classList = document.documentElement.classList
|
||||||
|
|
||||||
if not __terminal__:
|
if not __terminal__: # noqa: F821 __terminal__ is defined in core/src/plugins/donkey.js
|
||||||
classList.add("error")
|
classList.add("error")
|
||||||
else:
|
else:
|
||||||
classList.add("ok")
|
classList.add("ok")
|
||||||
|
|||||||
36
core/tests/javascript/worker-symbols.html
Normal file
36
core/tests/javascript/worker-symbols.html
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>PyScript VS Symbols</title>
|
||||||
|
<script>
|
||||||
|
globalThis.hasSymbol = (symbol, ref) => symbol in ref;
|
||||||
|
globalThis.getSymbol = (symbol, ref) => ref[symbol];
|
||||||
|
|
||||||
|
// some 3rd party JS library might use symbols to brand-check
|
||||||
|
// so it's not about symbols traveling from MicroPython
|
||||||
|
// it's about MicroPython proxies traps not understanding symbols
|
||||||
|
globalThis.hasIterator = ref => Symbol.iterator in ref;
|
||||||
|
</script>
|
||||||
|
<link rel="stylesheet" href="../../dist/core.css">
|
||||||
|
<script type="module" src="../../dist/core.js"></script>
|
||||||
|
<script type="mpy">
|
||||||
|
import js
|
||||||
|
|
||||||
|
symbol = js.Symbol.iterator
|
||||||
|
|
||||||
|
if js.getSymbol(symbol, []) and js.hasSymbol(symbol, []) and js.hasIterator([]):
|
||||||
|
js.document.documentElement.classList.add("main")
|
||||||
|
</script>
|
||||||
|
<script type="mpy" worker>
|
||||||
|
from pyscript import window
|
||||||
|
import js
|
||||||
|
|
||||||
|
symbol = js.Symbol.iterator
|
||||||
|
|
||||||
|
if window.getSymbol(symbol, []) and window.hasSymbol(symbol, []) and window.hasIterator([]):
|
||||||
|
window.document.documentElement.classList.add("worker")
|
||||||
|
</script>
|
||||||
|
</head>
|
||||||
|
</html>
|
||||||
@@ -4,4 +4,4 @@ def runtime_version():
|
|||||||
return sys.version
|
return sys.version
|
||||||
|
|
||||||
|
|
||||||
__export__ = ['runtime_version']
|
__export__ = ["runtime_version"]
|
||||||
|
|||||||
@@ -14,7 +14,7 @@
|
|||||||
print(event.type)
|
print(event.type)
|
||||||
ws.send("hello")
|
ws.send("hello")
|
||||||
|
|
||||||
def onmessage(event):
|
async def onmessage(event):
|
||||||
print(event.type, event.data)
|
print(event.type, event.data)
|
||||||
ws.close()
|
ws.close()
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,13 @@ import { test, expect } from '@playwright/test';
|
|||||||
|
|
||||||
test.setTimeout(120 * 1000);
|
test.setTimeout(120 * 1000);
|
||||||
|
|
||||||
|
test('config-parser custom TOML', async ({ page }) => {
|
||||||
|
await page.goto('http://localhost:8080/tests/javascript/config-parser/index.html');
|
||||||
|
await page.waitForSelector('html.done');
|
||||||
|
const body = await page.evaluate(() => document.body.innerText);
|
||||||
|
await expect(body.trim()).toBe('OK');
|
||||||
|
});
|
||||||
|
|
||||||
test('MicroPython display', async ({ page }) => {
|
test('MicroPython display', async ({ page }) => {
|
||||||
await page.goto('http://localhost:8080/tests/javascript/mpy.html');
|
await page.goto('http://localhost:8080/tests/javascript/mpy.html');
|
||||||
await page.waitForSelector('html.done.worker');
|
await page.waitForSelector('html.done.worker');
|
||||||
@@ -59,6 +66,11 @@ test('MicroPython + configURL', async ({ page }) => {
|
|||||||
await page.waitForSelector('html.main.worker');
|
await page.waitForSelector('html.main.worker');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('MicroPython + Symbols', async ({ page }) => {
|
||||||
|
await page.goto('http://localhost:8080/tests/javascript/worker-symbols.html');
|
||||||
|
await page.waitForSelector('html.main.worker');
|
||||||
|
});
|
||||||
|
|
||||||
test('Pyodide + terminal on Main', async ({ page }) => {
|
test('Pyodide + terminal on Main', async ({ page }) => {
|
||||||
await page.goto('http://localhost:8080/tests/javascript/py-terminal-main.html');
|
await page.goto('http://localhost:8080/tests/javascript/py-terminal-main.html');
|
||||||
await page.waitForSelector('html.ok');
|
await page.waitForSelector('html.ok');
|
||||||
@@ -139,6 +151,25 @@ test('Pyodide lockFileURL vs CDN', async ({ page }) => {
|
|||||||
await expect(body).toBe('OK');
|
await expect(body).toBe('OK');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('Pyodide pinned lockFileURL', async ({ page }) => {
|
||||||
|
const logs = [];
|
||||||
|
page.on('console', msg => {
|
||||||
|
const text = msg.text();
|
||||||
|
if (!text.startsWith('['))
|
||||||
|
logs.push(text);
|
||||||
|
});
|
||||||
|
await page.goto('http://localhost:8080/tests/javascript/pyodide-lockfile/');
|
||||||
|
await page.waitForSelector('html.done');
|
||||||
|
let body = await page.evaluate(() => document.body.lastChild.textContent);
|
||||||
|
await expect(body).toBe('OK');
|
||||||
|
await expect(!!logs.splice(0).length).toBe(true);
|
||||||
|
await page.reload();
|
||||||
|
await page.waitForSelector('html.done');
|
||||||
|
body = await page.evaluate(() => document.body.lastChild.textContent);
|
||||||
|
await expect(body).toBe('OK');
|
||||||
|
await expect(logs.splice(0).length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
test('MicroPython buffered error', async ({ page }) => {
|
test('MicroPython buffered error', async ({ page }) => {
|
||||||
await page.goto('http://localhost:8080/tests/javascript/mpy-error.html');
|
await page.goto('http://localhost:8080/tests/javascript/mpy-error.html');
|
||||||
await page.waitForSelector('html.ok');
|
await page.waitForSelector('html.ok');
|
||||||
@@ -152,3 +183,24 @@ test('MicroPython buffered NO error', async ({ page }) => {
|
|||||||
const body = await page.evaluate(() => document.body.textContent.trim());
|
const body = await page.evaluate(() => document.body.textContent.trim());
|
||||||
await expect(body).toBe('');
|
await expect(body).toBe('');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('Pyodide media module', async ({ page }) => {
|
||||||
|
await page.context().grantPermissions(['camera', 'microphone']);
|
||||||
|
await page.context().addInitScript(() => {
|
||||||
|
const originalEnumerateDevices = navigator.mediaDevices.enumerateDevices;
|
||||||
|
navigator.mediaDevices.enumerateDevices = async function() {
|
||||||
|
const realDevices = await originalEnumerateDevices.call(this);
|
||||||
|
if (!realDevices || realDevices.length === 0) {
|
||||||
|
return [
|
||||||
|
{ deviceId: 'camera1', groupId: 'group1', kind: 'videoinput', label: 'Simulated Camera' },
|
||||||
|
{ deviceId: 'mic1', groupId: 'group2', kind: 'audioinput', label: 'Simulated Microphone' }
|
||||||
|
];
|
||||||
|
}
|
||||||
|
return realDevices;
|
||||||
|
};
|
||||||
|
});
|
||||||
|
await page.goto('http://localhost:8080/tests/javascript/media.html');
|
||||||
|
await page.waitForSelector('html.media-ok', { timeout: 10000 });
|
||||||
|
const isSuccess = await page.evaluate(() => document.documentElement.classList.contains('media-ok'));
|
||||||
|
expect(isSuccess).toBe(true);
|
||||||
|
});
|
||||||
|
|||||||
13
core/tests/manual/emoji.html
Normal file
13
core/tests/manual/emoji.html
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1.0">
|
||||||
|
<link rel="stylesheet" href="../../dist/core.css">
|
||||||
|
<script type="module" src="../../dist/core.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<script type="mpy" src="emoji.py" terminal worker></script>
|
||||||
|
<script type="py" src="emoji.py" terminal worker></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
17
core/tests/manual/emoji.py
Normal file
17
core/tests/manual/emoji.py
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import sys
|
||||||
|
|
||||||
|
print(sys.version)
|
||||||
|
RED = chr(0x1F534) # LARGE RED CIRCLE
|
||||||
|
GREEN = chr(0x1F7E2) # LARGE GREEN CIRCLE
|
||||||
|
MOUSE = chr(0x1F42D) # MOUSE FACE
|
||||||
|
EARTH = chr(0x1F30E) # EARTH GLOBE AMERICAS
|
||||||
|
FACE = chr(0x1F610) # NEUTRAL FACE
|
||||||
|
BASMALA = chr(0xFDFD) # ARABIC LIGATURE BISMILLAH AR-RAHMAN AR-RAHEEM
|
||||||
|
|
||||||
|
print("[", RED, "]")
|
||||||
|
print("[", MOUSE, "]")
|
||||||
|
print("[", EARTH, "]")
|
||||||
|
print("[", FACE, "]")
|
||||||
|
print("[", FACE * 3, "]")
|
||||||
|
print("[", BASMALA, "]")
|
||||||
|
print("[", BASMALA + GREEN, "]")
|
||||||
21
core/tests/manual/ffi_timeout/index.html
Normal file
21
core/tests/manual/ffi_timeout/index.html
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<link rel="stylesheet" href="../../../dist/core.css">
|
||||||
|
<script>
|
||||||
|
window.Worker = class extends Worker {
|
||||||
|
constructor(url, ...rest) {
|
||||||
|
console.log(rest[0]);
|
||||||
|
return super(url, ...rest);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
window.start = Date.now();
|
||||||
|
</script>
|
||||||
|
<script type="module" src="../../../dist/core.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<script type="py" config="./index.toml" src="index.py" worker></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
3
core/tests/manual/ffi_timeout/index.py
Normal file
3
core/tests/manual/ffi_timeout/index.py
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
from pyscript import document, window
|
||||||
|
|
||||||
|
document.body.append(window.Date.now() - window.start)
|
||||||
2
core/tests/manual/ffi_timeout/index.toml
Normal file
2
core/tests/manual/ffi_timeout/index.toml
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
experimental_ffi_timeout = 0
|
||||||
|
package_cache = "passthrough"
|
||||||
12
core/tests/manual/fs/index.html
Normal file
12
core/tests/manual/fs/index.html
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<link rel="stylesheet" href="../../../dist/core.css">
|
||||||
|
<script type="module" src="../../../dist/core.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<script type="mpy" src="index.py"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
48
core/tests/manual/fs/index.py
Normal file
48
core/tests/manual/fs/index.py
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
import os
|
||||||
|
from pyscript import RUNNING_IN_WORKER, fs
|
||||||
|
|
||||||
|
|
||||||
|
TEST = "implicit"
|
||||||
|
|
||||||
|
if TEST == "implicit":
|
||||||
|
await fs.mount("/persistent")
|
||||||
|
|
||||||
|
print(
|
||||||
|
(RUNNING_IN_WORKER and "Worker") or "Main",
|
||||||
|
os.listdir("/persistent"),
|
||||||
|
)
|
||||||
|
|
||||||
|
from random import random
|
||||||
|
|
||||||
|
with open("/persistent/random.txt", "w") as f:
|
||||||
|
f.write(str(random()))
|
||||||
|
|
||||||
|
await fs.sync("/persistent")
|
||||||
|
|
||||||
|
# await fs.revoke("/persistent")
|
||||||
|
|
||||||
|
elif not RUNNING_IN_WORKER:
|
||||||
|
from pyscript import document
|
||||||
|
|
||||||
|
button = document.createElement("button")
|
||||||
|
button.textContent = "mount"
|
||||||
|
document.body.append(button)
|
||||||
|
|
||||||
|
async def mount(event):
|
||||||
|
try:
|
||||||
|
await fs.mount("/persistent")
|
||||||
|
print(os.listdir("/persistent"))
|
||||||
|
button.textContent = "unmount"
|
||||||
|
button.onclick = unmount
|
||||||
|
|
||||||
|
except:
|
||||||
|
import js
|
||||||
|
|
||||||
|
js.alert("unable to grant access")
|
||||||
|
|
||||||
|
async def unmount(event):
|
||||||
|
await fs.revoke("/persistent")
|
||||||
|
button.textContent = "mount"
|
||||||
|
button.onclick = mount
|
||||||
|
|
||||||
|
button.onclick = mount
|
||||||
30
core/tests/manual/game/aliens.css
Normal file
30
core/tests/manual/game/aliens.css
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
/* (c) https://github.com/ryanking13/pyodide-pygame-demo/blob/main/examples/aliens.html */
|
||||||
|
body {
|
||||||
|
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||||
|
margin: 0;
|
||||||
|
padding: 20px;
|
||||||
|
background-color: #f4f4f4;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
.demo {
|
||||||
|
background-color: #fff;
|
||||||
|
margin: 20px auto;
|
||||||
|
max-width: 1000px;
|
||||||
|
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||||
|
border-radius: 8px;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.demo-header {
|
||||||
|
background-color: #007bff;
|
||||||
|
color: #fff;
|
||||||
|
padding: 15px 20px;
|
||||||
|
font-size: 20px;
|
||||||
|
}
|
||||||
|
.demo-content {
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#canvas {
|
||||||
|
margin: 0 auto;
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
395
core/tests/manual/game/aliens.py
Normal file
395
core/tests/manual/game/aliens.py
Normal file
@@ -0,0 +1,395 @@
|
|||||||
|
"""(c) https://github.com/ryanking13/pyodide-pygame-demo/blob/main/examples/aliens.html
|
||||||
|
pygame.examples.aliens
|
||||||
|
|
||||||
|
Shows a mini game where you have to defend against aliens.
|
||||||
|
|
||||||
|
What does it show you about pygame?
|
||||||
|
|
||||||
|
* pygame.sprite, the difference between Sprite and Group.
|
||||||
|
* dirty rectangle optimization for processing for speed.
|
||||||
|
* music with pygame.mixer.music, including fadeout
|
||||||
|
* sound effects with pygame.Sound
|
||||||
|
* event processing, keyboard handling, QUIT handling.
|
||||||
|
* a main loop frame limited with a game clock from the pygame.time module
|
||||||
|
* fullscreen switching.
|
||||||
|
|
||||||
|
|
||||||
|
Controls
|
||||||
|
--------
|
||||||
|
|
||||||
|
* Left and right arrows to move.
|
||||||
|
* Space bar to shoot.
|
||||||
|
* f key to toggle between fullscreen.
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import random
|
||||||
|
import os
|
||||||
|
import pathlib
|
||||||
|
|
||||||
|
import pyscript
|
||||||
|
|
||||||
|
# import basic pygame modules
|
||||||
|
import pygame
|
||||||
|
|
||||||
|
# see if we can load more than standard BMP
|
||||||
|
if not pygame.image.get_extended():
|
||||||
|
msg = "Sorry, extended image module required"
|
||||||
|
raise SystemExit(msg)
|
||||||
|
|
||||||
|
|
||||||
|
# game constants
|
||||||
|
MAX_SHOTS = 2 # most player bullets onscreen
|
||||||
|
ALIEN_ODDS = 22 # chances a new alien appears
|
||||||
|
BOMB_ODDS = 60 # chances a new bomb will drop
|
||||||
|
ALIEN_RELOAD = 12 # frames between new aliens
|
||||||
|
SCREENRECT = pygame.Rect(0, 0, 640, 480)
|
||||||
|
SCORE = 0
|
||||||
|
|
||||||
|
|
||||||
|
main_dir = str(pathlib.Path(pygame.__file__).parent / "examples")
|
||||||
|
|
||||||
|
|
||||||
|
def load_image(file):
|
||||||
|
"""loads an image, prepares it for play"""
|
||||||
|
file = os.path.join(main_dir, "data", file)
|
||||||
|
try:
|
||||||
|
surface = pygame.image.load(file)
|
||||||
|
except pygame.error:
|
||||||
|
msg = f'Could not load image "{file}" {pygame.get_error()}'
|
||||||
|
raise SystemExit(msg)
|
||||||
|
return surface.convert()
|
||||||
|
|
||||||
|
|
||||||
|
def load_sound(file):
|
||||||
|
"""because pygame can be be compiled without mixer."""
|
||||||
|
if not pygame.mixer:
|
||||||
|
return None
|
||||||
|
file = os.path.join(main_dir, "data", file)
|
||||||
|
try:
|
||||||
|
return pygame.mixer.Sound(file)
|
||||||
|
except pygame.error:
|
||||||
|
print(f"Warning, unable to load, {file}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# Each type of game object gets an init and an update function.
|
||||||
|
# The update function is called once per frame, and it is when each object should
|
||||||
|
# change its current position and state.
|
||||||
|
#
|
||||||
|
# The Player object actually gets a "move" function instead of update,
|
||||||
|
# since it is passed extra information about the keyboard.
|
||||||
|
|
||||||
|
|
||||||
|
class Player(pygame.sprite.Sprite):
|
||||||
|
"""Representing the player as a moon buggy type car."""
|
||||||
|
|
||||||
|
speed = 10
|
||||||
|
bounce = 24
|
||||||
|
gun_offset = -11
|
||||||
|
images = []
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
pygame.sprite.Sprite.__init__(self, self.containers)
|
||||||
|
self.image = self.images[0]
|
||||||
|
self.rect = self.image.get_rect(midbottom=SCREENRECT.midbottom)
|
||||||
|
self.reloading = False
|
||||||
|
self.origtop = self.rect.top
|
||||||
|
self.facing = -1
|
||||||
|
|
||||||
|
def move(self, direction):
|
||||||
|
if direction:
|
||||||
|
self.facing = direction
|
||||||
|
self.rect.move_ip(direction * self.speed, 0)
|
||||||
|
self.rect = self.rect.clamp(SCREENRECT)
|
||||||
|
if direction < 0:
|
||||||
|
self.image = self.images[0]
|
||||||
|
elif direction > 0:
|
||||||
|
self.image = self.images[1]
|
||||||
|
self.rect.top = self.origtop - (self.rect.left // self.bounce % 2)
|
||||||
|
|
||||||
|
def gunpos(self):
|
||||||
|
pos = self.facing * self.gun_offset + self.rect.centerx
|
||||||
|
return pos, self.rect.top
|
||||||
|
|
||||||
|
|
||||||
|
class Alien(pygame.sprite.Sprite):
|
||||||
|
"""An alien space ship. That slowly moves down the screen."""
|
||||||
|
|
||||||
|
speed = 13
|
||||||
|
animcycle = 12
|
||||||
|
images = []
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
pygame.sprite.Sprite.__init__(self, self.containers)
|
||||||
|
self.image = self.images[0]
|
||||||
|
self.rect = self.image.get_rect()
|
||||||
|
self.facing = random.choice((-1, 1)) * Alien.speed
|
||||||
|
self.frame = 0
|
||||||
|
if self.facing < 0:
|
||||||
|
self.rect.right = SCREENRECT.right
|
||||||
|
|
||||||
|
def update(self):
|
||||||
|
self.rect.move_ip(self.facing, 0)
|
||||||
|
if not SCREENRECT.contains(self.rect):
|
||||||
|
self.facing = -self.facing
|
||||||
|
self.rect.top = self.rect.bottom + 1
|
||||||
|
self.rect = self.rect.clamp(SCREENRECT)
|
||||||
|
self.frame = self.frame + 1
|
||||||
|
self.image = self.images[self.frame // self.animcycle % 3]
|
||||||
|
|
||||||
|
|
||||||
|
class Explosion(pygame.sprite.Sprite):
|
||||||
|
"""An explosion. Hopefully the Alien and not the player!"""
|
||||||
|
|
||||||
|
defaultlife = 12
|
||||||
|
animcycle = 3
|
||||||
|
images = []
|
||||||
|
|
||||||
|
def __init__(self, actor):
|
||||||
|
pygame.sprite.Sprite.__init__(self, self.containers)
|
||||||
|
self.image = self.images[0]
|
||||||
|
self.rect = self.image.get_rect(center=actor.rect.center)
|
||||||
|
self.life = self.defaultlife
|
||||||
|
|
||||||
|
def update(self):
|
||||||
|
"""called every time around the game loop.
|
||||||
|
|
||||||
|
Show the explosion surface for 'defaultlife'.
|
||||||
|
Every game tick(update), we decrease the 'life'.
|
||||||
|
|
||||||
|
Also we animate the explosion.
|
||||||
|
"""
|
||||||
|
self.life = self.life - 1
|
||||||
|
self.image = self.images[self.life // self.animcycle % 2]
|
||||||
|
if self.life <= 0:
|
||||||
|
self.kill()
|
||||||
|
|
||||||
|
|
||||||
|
class Shot(pygame.sprite.Sprite):
|
||||||
|
"""a bullet the Player sprite fires."""
|
||||||
|
|
||||||
|
speed = -11
|
||||||
|
images = []
|
||||||
|
|
||||||
|
def __init__(self, pos):
|
||||||
|
pygame.sprite.Sprite.__init__(self, self.containers)
|
||||||
|
self.image = self.images[0]
|
||||||
|
self.rect = self.image.get_rect(midbottom=pos)
|
||||||
|
|
||||||
|
def update(self):
|
||||||
|
"""called every time around the game loop.
|
||||||
|
|
||||||
|
Every tick we move the shot upwards.
|
||||||
|
"""
|
||||||
|
self.rect.move_ip(0, self.speed)
|
||||||
|
if self.rect.top <= 0:
|
||||||
|
self.kill()
|
||||||
|
|
||||||
|
|
||||||
|
class Bomb(pygame.sprite.Sprite):
|
||||||
|
"""A bomb the aliens drop."""
|
||||||
|
|
||||||
|
speed = 9
|
||||||
|
images = []
|
||||||
|
|
||||||
|
def __init__(self, alien):
|
||||||
|
pygame.sprite.Sprite.__init__(self, self.containers)
|
||||||
|
self.image = self.images[0]
|
||||||
|
self.rect = self.image.get_rect(midbottom=alien.rect.move(0, 5).midbottom)
|
||||||
|
|
||||||
|
def update(self):
|
||||||
|
"""called every time around the game loop.
|
||||||
|
|
||||||
|
Every frame we move the sprite 'rect' down.
|
||||||
|
When it reaches the bottom we:
|
||||||
|
|
||||||
|
- make an explosion.
|
||||||
|
- remove the Bomb.
|
||||||
|
"""
|
||||||
|
self.rect.move_ip(0, self.speed)
|
||||||
|
if self.rect.bottom >= 470:
|
||||||
|
Explosion(self)
|
||||||
|
self.kill()
|
||||||
|
|
||||||
|
|
||||||
|
class Score(pygame.sprite.Sprite):
|
||||||
|
"""to keep track of the score."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
pygame.sprite.Sprite.__init__(self)
|
||||||
|
self.font = pygame.Font(None, 20)
|
||||||
|
self.font.set_italic(1)
|
||||||
|
self.color = "white"
|
||||||
|
self.lastscore = -1
|
||||||
|
self.update()
|
||||||
|
self.rect = self.image.get_rect().move(10, 450)
|
||||||
|
|
||||||
|
def update(self):
|
||||||
|
"""We only update the score in update() when it has changed."""
|
||||||
|
if self.lastscore != SCORE:
|
||||||
|
self.lastscore = SCORE
|
||||||
|
msg = "Score: %d" % SCORE
|
||||||
|
self.image = self.font.render(msg, 0, self.color)
|
||||||
|
|
||||||
|
|
||||||
|
async def main(winstyle=0):
|
||||||
|
# Initialize pygame
|
||||||
|
pygame.mixer.pre_init(44100, 32, 2, 1024)
|
||||||
|
pygame.init()
|
||||||
|
if pygame.mixer and not pygame.mixer.get_init():
|
||||||
|
print("Warning, no sound")
|
||||||
|
pygame.mixer = None
|
||||||
|
|
||||||
|
fullscreen = False
|
||||||
|
# Set the display mode
|
||||||
|
winstyle = 0 # |FULLSCREEN
|
||||||
|
screen = pygame.display.set_mode(SCREENRECT.size, winstyle)
|
||||||
|
|
||||||
|
# Load images, assign to sprite classes
|
||||||
|
# (do this before the classes are used, after screen setup)
|
||||||
|
img = load_image("player1.gif")
|
||||||
|
Player.images = [img, pygame.transform.flip(img, 1, 0)]
|
||||||
|
img = load_image("explosion1.gif")
|
||||||
|
Explosion.images = [img, pygame.transform.flip(img, 1, 1)]
|
||||||
|
Alien.images = [load_image(im) for im in ("alien1.gif", "alien2.gif", "alien3.gif")]
|
||||||
|
Bomb.images = [load_image("bomb.gif")]
|
||||||
|
Shot.images = [load_image("shot.gif")]
|
||||||
|
|
||||||
|
# decorate the game window
|
||||||
|
icon = pygame.transform.scale(Alien.images[0], (32, 32))
|
||||||
|
pygame.display.set_icon(icon)
|
||||||
|
pygame.display.set_caption("Pygame Aliens")
|
||||||
|
pygame.mouse.set_visible(0)
|
||||||
|
|
||||||
|
# create the background, tile the bgd image
|
||||||
|
bgdtile = load_image("background.gif")
|
||||||
|
background = pygame.Surface(SCREENRECT.size)
|
||||||
|
for x in range(0, SCREENRECT.width, bgdtile.get_width()):
|
||||||
|
background.blit(bgdtile, (x, 0))
|
||||||
|
screen.blit(background, (0, 0))
|
||||||
|
pygame.display.flip()
|
||||||
|
|
||||||
|
# load the sound effects
|
||||||
|
boom_sound = load_sound("boom.wav")
|
||||||
|
shoot_sound = load_sound("car_door.wav")
|
||||||
|
if pygame.mixer:
|
||||||
|
music = os.path.join(main_dir, "data", "house_lo.wav")
|
||||||
|
pygame.mixer.music.load(music)
|
||||||
|
pygame.mixer.music.play(-1)
|
||||||
|
|
||||||
|
# Initialize Game Groups
|
||||||
|
aliens = pygame.sprite.Group()
|
||||||
|
shots = pygame.sprite.Group()
|
||||||
|
bombs = pygame.sprite.Group()
|
||||||
|
all = pygame.sprite.RenderUpdates()
|
||||||
|
lastalien = pygame.sprite.GroupSingle()
|
||||||
|
|
||||||
|
# assign default groups to each sprite class
|
||||||
|
Player.containers = all
|
||||||
|
Alien.containers = aliens, all, lastalien
|
||||||
|
Shot.containers = shots, all
|
||||||
|
Bomb.containers = bombs, all
|
||||||
|
Explosion.containers = all
|
||||||
|
Score.containers = all
|
||||||
|
|
||||||
|
# Create Some Starting Values
|
||||||
|
global score
|
||||||
|
alienreload = ALIEN_RELOAD
|
||||||
|
_clock = pygame.Clock()
|
||||||
|
|
||||||
|
# initialize our starting sprites
|
||||||
|
global SCORE
|
||||||
|
player = Player()
|
||||||
|
Alien() # note, this 'lives' because it goes into a sprite group
|
||||||
|
if pygame.font:
|
||||||
|
all.add(Score())
|
||||||
|
|
||||||
|
# Run our main loop whilst the player is alive.
|
||||||
|
while player.alive():
|
||||||
|
# get input
|
||||||
|
for event in pygame.event.get():
|
||||||
|
if event.type == pygame.QUIT:
|
||||||
|
return
|
||||||
|
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
|
||||||
|
return
|
||||||
|
if event.type == pygame.KEYDOWN and event.key == pygame.K_f:
|
||||||
|
if not fullscreen:
|
||||||
|
print("Changing to FULLSCREEN")
|
||||||
|
screen_backup = screen.copy()
|
||||||
|
screen = pygame.display.set_mode(SCREENRECT.size, winstyle | pygame.FULLSCREEN)
|
||||||
|
screen.blit(screen_backup, (0, 0))
|
||||||
|
else:
|
||||||
|
print("Changing to windowed mode")
|
||||||
|
screen_backup = screen.copy()
|
||||||
|
screen = pygame.display.set_mode(SCREENRECT.size, winstyle)
|
||||||
|
screen.blit(screen_backup, (0, 0))
|
||||||
|
pygame.display.flip()
|
||||||
|
fullscreen = not fullscreen
|
||||||
|
|
||||||
|
keystate = pygame.key.get_pressed()
|
||||||
|
|
||||||
|
# clear/erase the last drawn sprites
|
||||||
|
all.clear(screen, background)
|
||||||
|
|
||||||
|
# update all the sprites
|
||||||
|
all.update()
|
||||||
|
|
||||||
|
# handle player input
|
||||||
|
direction = keystate[pygame.K_RIGHT] - keystate[pygame.K_LEFT]
|
||||||
|
player.move(direction)
|
||||||
|
firing = keystate[pygame.K_SPACE]
|
||||||
|
if not player.reloading and firing and len(shots) < MAX_SHOTS:
|
||||||
|
Shot(player.gunpos())
|
||||||
|
if pygame.mixer:
|
||||||
|
shoot_sound.play()
|
||||||
|
player.reloading = firing
|
||||||
|
|
||||||
|
# Create new alien
|
||||||
|
if alienreload:
|
||||||
|
alienreload = alienreload - 1
|
||||||
|
elif not int(random.random() * ALIEN_ODDS):
|
||||||
|
Alien()
|
||||||
|
alienreload = ALIEN_RELOAD
|
||||||
|
|
||||||
|
# Drop bombs
|
||||||
|
if lastalien and not int(random.random() * BOMB_ODDS):
|
||||||
|
Bomb(lastalien.sprite)
|
||||||
|
|
||||||
|
# Detect collisions between aliens and players.
|
||||||
|
for alien in pygame.sprite.spritecollide(player, aliens, 1):
|
||||||
|
if pygame.mixer:
|
||||||
|
boom_sound.play()
|
||||||
|
Explosion(alien)
|
||||||
|
Explosion(player)
|
||||||
|
SCORE = SCORE + 1
|
||||||
|
player.kill()
|
||||||
|
|
||||||
|
# See if shots hit the aliens.
|
||||||
|
for alien in pygame.sprite.groupcollide(aliens, shots, 1, 1):
|
||||||
|
if pygame.mixer:
|
||||||
|
boom_sound.play()
|
||||||
|
Explosion(alien)
|
||||||
|
SCORE = SCORE + 1
|
||||||
|
|
||||||
|
# See if alien bombs hit the player.
|
||||||
|
for bomb in pygame.sprite.spritecollide(player, bombs, 1):
|
||||||
|
if pygame.mixer:
|
||||||
|
boom_sound.play()
|
||||||
|
Explosion(player)
|
||||||
|
Explosion(bomb)
|
||||||
|
player.kill()
|
||||||
|
|
||||||
|
# draw the scene
|
||||||
|
dirty = all.draw(screen)
|
||||||
|
pygame.display.update(dirty)
|
||||||
|
|
||||||
|
# cap the framerate at 40fps. Also called 40HZ or 40 times per second.
|
||||||
|
await asyncio.sleep(0.025)
|
||||||
|
|
||||||
|
if pygame.mixer:
|
||||||
|
pygame.mixer.music.fadeout(1000)
|
||||||
|
|
||||||
|
|
||||||
|
main()
|
||||||
0
core/tests/manual/game/config.toml
Normal file
0
core/tests/manual/game/config.toml
Normal file
19
core/tests/manual/game/index.html
Normal file
19
core/tests/manual/game/index.html
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<link rel="stylesheet" href="aliens.css" />
|
||||||
|
<link rel="stylesheet" href="../../../dist/core.css" />
|
||||||
|
<script type="module" src="../../../dist/core.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<script type="py-game" src="aliens.py" config="./config.toml"></script>
|
||||||
|
<div class="demo">
|
||||||
|
<div class="demo-header">pygame.examples.aliens</div>
|
||||||
|
<div class="demo-content">
|
||||||
|
<canvas id="canvas"></canvas>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
13
core/tests/manual/issue-2228/index.html
Normal file
13
core/tests/manual/issue-2228/index.html
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1.0">
|
||||||
|
<script type="module" src="../../../dist/core.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<script type="py" config='{"packages":["jsonpointer==3.0.0"]}'>
|
||||||
|
print('Hello World')
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
11
core/tests/manual/issue-2246/index.html
Normal file
11
core/tests/manual/issue-2246/index.html
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1.0">
|
||||||
|
<script type="module" src="../../../dist/core.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<script type="py" src="./main.py" terminal worker></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
1
core/tests/manual/issue-2246/main.py
Normal file
1
core/tests/manual/issue-2246/main.py
Normal file
@@ -0,0 +1 @@
|
|||||||
|
print(input("What food would you like me to get from the shop? "))
|
||||||
BIN
core/tests/manual/issue-2302/assets/genuary25-18.m4a
Normal file
BIN
core/tests/manual/issue-2302/assets/genuary25-18.m4a
Normal file
Binary file not shown.
20
core/tests/manual/issue-2302/glue/multipyjs.py
Normal file
20
core/tests/manual/issue-2302/glue/multipyjs.py
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
from pyscript import config
|
||||||
|
|
||||||
|
MICROPYTHON = config["type"] == "mpy"
|
||||||
|
|
||||||
|
if MICROPYTHON:
|
||||||
|
def new(obj, *args, **kwargs):
|
||||||
|
return obj.new(*args, kwargs) if kwargs else obj.new(*args)
|
||||||
|
def call(obj, *args, **kwargs):
|
||||||
|
return obj(*args, kwargs) if kwargs else obj(*args)
|
||||||
|
else:
|
||||||
|
def new(obj, *args, **kwargs):
|
||||||
|
return obj.new(*args, **kwargs)
|
||||||
|
def call(obj, *args, **kwargs):
|
||||||
|
return obj(*args, **kwargs)
|
||||||
|
|
||||||
|
if not MICROPYTHON:
|
||||||
|
import pyodide_js
|
||||||
|
pyodide_js.setDebug(True)
|
||||||
|
|
||||||
|
from pyscript.ffi import to_js, create_proxy
|
||||||
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user