@pyscript/core 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/core.css +1 -1
- package/dist/core.js +2 -2
- package/dist/core.js.map +1 -1
- package/package.json +1 -1
- package/src/config.js +61 -54
- package/src/core.css +3 -1
- package/src/core.js +176 -149
- package/src/stdlib/pyscript/__init__.py +10 -1
- package/src/stdlib/pyscript/util.py +3 -4
- package/src/stdlib/pyscript.js +2 -2
- package/src/types.js +4 -0
- package/types/config.d.ts +2 -4
- package/types/core.d.ts +2 -1
- package/types/types.d.ts +2 -0
package/package.json
CHANGED
package/src/config.js
CHANGED
@@ -5,6 +5,7 @@
|
|
5
5
|
*/
|
6
6
|
import { $ } from "basic-devtools";
|
7
7
|
|
8
|
+
import TYPES from "./types.js";
|
8
9
|
import allPlugins from "./plugins.js";
|
9
10
|
import { robustFetch as fetch, getText } from "./fetch.js";
|
10
11
|
import { ErrorCode } from "./exceptions.js";
|
@@ -45,66 +46,72 @@ const syntaxError = (type, url, { message }) => {
|
|
45
46
|
return new SyntaxError(`${str}\n${message}`);
|
46
47
|
};
|
47
48
|
|
48
|
-
|
49
|
-
let config, plugins, parsed, error, type;
|
50
|
-
let pyConfig = $("py-config");
|
51
|
-
if (pyConfig) {
|
52
|
-
config = pyConfig.getAttribute("src") || pyConfig.textContent;
|
53
|
-
type = pyConfig.getAttribute("type");
|
54
|
-
} else {
|
55
|
-
pyConfig = $(
|
56
|
-
[
|
57
|
-
'script[type="py"][config]:not([worker])',
|
58
|
-
"py-script[config]:not([worker])",
|
59
|
-
].join(","),
|
60
|
-
);
|
61
|
-
if (pyConfig) config = pyConfig.getAttribute("config");
|
62
|
-
}
|
49
|
+
const configs = new Map();
|
63
50
|
|
64
|
-
|
65
|
-
|
66
|
-
|
67
|
-
|
68
|
-
|
69
|
-
|
70
|
-
|
71
|
-
|
72
|
-
|
73
|
-
|
74
|
-
|
75
|
-
|
76
|
-
|
77
|
-
|
78
|
-
|
79
|
-
|
80
|
-
|
81
|
-
|
82
|
-
|
83
|
-
|
51
|
+
for (const [TYPE] of TYPES) {
|
52
|
+
// find the shared config for all py-script elements
|
53
|
+
let config, plugins, parsed, error, type;
|
54
|
+
let pyConfig = $(`${TYPE}-config`);
|
55
|
+
if (pyConfig) {
|
56
|
+
config = pyConfig.getAttribute("src") || pyConfig.textContent;
|
57
|
+
type = pyConfig.getAttribute("type");
|
58
|
+
} else {
|
59
|
+
pyConfig = $(
|
60
|
+
[
|
61
|
+
`script[type="${TYPE}"][config]:not([worker])`,
|
62
|
+
`${TYPE}-script[config]:not([worker])`,
|
63
|
+
].join(","),
|
64
|
+
);
|
65
|
+
if (pyConfig) config = pyConfig.getAttribute("config");
|
66
|
+
}
|
67
|
+
|
68
|
+
// catch possible fetch errors
|
69
|
+
if (config) {
|
70
|
+
try {
|
71
|
+
const { json, toml, text, url } = await configDetails(config);
|
72
|
+
config = text;
|
73
|
+
if (json || type === "json") {
|
74
|
+
try {
|
75
|
+
parsed = JSON.parse(text);
|
76
|
+
} catch (e) {
|
77
|
+
error = syntaxError("JSON", url, e);
|
78
|
+
}
|
79
|
+
} else if (toml || type === "toml") {
|
80
|
+
try {
|
81
|
+
const { parse } = await import(
|
82
|
+
/* webpackIgnore: true */
|
83
|
+
"https://cdn.jsdelivr.net/npm/@webreflection/toml-j0.4/toml.js"
|
84
|
+
);
|
85
|
+
parsed = parse(text);
|
86
|
+
} catch (e) {
|
87
|
+
error = syntaxError("TOML", url, e);
|
88
|
+
}
|
84
89
|
}
|
90
|
+
} catch (e) {
|
91
|
+
error = e;
|
85
92
|
}
|
86
|
-
} catch (e) {
|
87
|
-
error = e;
|
88
93
|
}
|
89
|
-
}
|
90
94
|
|
91
|
-
// parse all plugins and optionally ignore only
|
92
|
-
// those flagged as "undesired" via `!` prefix
|
93
|
-
const toBeAwaited = [];
|
94
|
-
for (const [key, value] of Object.entries(allPlugins)) {
|
95
|
-
|
96
|
-
|
97
|
-
|
98
|
-
|
99
|
-
|
100
|
-
|
95
|
+
// parse all plugins and optionally ignore only
|
96
|
+
// those flagged as "undesired" via `!` prefix
|
97
|
+
const toBeAwaited = [];
|
98
|
+
for (const [key, value] of Object.entries(allPlugins)) {
|
99
|
+
if (error) {
|
100
|
+
if (key === "error") {
|
101
|
+
// show on page the config is broken, meaning that
|
102
|
+
// it was not possible to disable error plugin neither
|
103
|
+
// as that part wasn't correctly parsed anyway
|
104
|
+
value().then(({ notify }) => notify(error.message));
|
105
|
+
}
|
106
|
+
} else if (!parsed?.plugins?.includes(`!${key}`)) {
|
107
|
+
toBeAwaited.push(value());
|
101
108
|
}
|
102
|
-
} else if (!parsed?.plugins?.includes(`!${key}`)) {
|
103
|
-
toBeAwaited.push(value());
|
104
109
|
}
|
105
|
-
}
|
106
110
|
|
107
|
-
// assign plugins as Promise.all only if needed
|
108
|
-
if (toBeAwaited.length) plugins = Promise.all(toBeAwaited);
|
111
|
+
// assign plugins as Promise.all only if needed
|
112
|
+
if (toBeAwaited.length) plugins = Promise.all(toBeAwaited);
|
113
|
+
|
114
|
+
configs.set(TYPE, { config: parsed, plugins, error });
|
115
|
+
}
|
109
116
|
|
110
|
-
export
|
117
|
+
export default configs;
|
package/src/core.css
CHANGED
package/src/core.js
CHANGED
@@ -9,23 +9,18 @@ import { queryTarget } from "../node_modules/polyscript/esm/script-handler.js";
|
|
9
9
|
import { dedent, dispatch } from "../node_modules/polyscript/esm/utils.js";
|
10
10
|
import { Hook } from "../node_modules/polyscript/esm/worker/hooks.js";
|
11
11
|
|
12
|
-
import
|
12
|
+
import TYPES from "./types.js";
|
13
|
+
import configs from "./config.js";
|
13
14
|
import sync from "./sync.js";
|
14
15
|
import stdlib from "./stdlib.js";
|
15
|
-
import {
|
16
|
+
import { ErrorCode } from "./exceptions.js";
|
16
17
|
import { robustFetch as fetch, getText } from "./fetch.js";
|
17
18
|
|
18
|
-
const { assign, defineProperty
|
19
|
-
|
20
|
-
const TYPE = "py";
|
19
|
+
const { assign, defineProperty } = Object;
|
21
20
|
|
22
21
|
// allows lazy element features on code evaluation
|
23
22
|
let currentElement;
|
24
23
|
|
25
|
-
// create a unique identifier when/if needed
|
26
|
-
let id = 0;
|
27
|
-
const getID = (prefix = TYPE) => `${prefix}-${id++}`;
|
28
|
-
|
29
24
|
// generic helper to disambiguate between custom element and script
|
30
25
|
const isScript = ({ tagName }) => tagName === "SCRIPT";
|
31
26
|
|
@@ -41,35 +36,11 @@ const after = () => {
|
|
41
36
|
delete document.currentScript;
|
42
37
|
};
|
43
38
|
|
44
|
-
/**
|
45
|
-
* Given a generic DOM Element, tries to fetch the 'src' attribute, if present.
|
46
|
-
* It either throws an error if the 'src' can't be fetched or it returns a fallback
|
47
|
-
* content as source.
|
48
|
-
*/
|
49
|
-
const fetchSource = async (tag, io, asText) => {
|
50
|
-
if (tag.hasAttribute("src")) {
|
51
|
-
try {
|
52
|
-
return await fetch(tag.getAttribute("src")).then(getText);
|
53
|
-
} catch (error) {
|
54
|
-
io.stderr(error);
|
55
|
-
}
|
56
|
-
}
|
57
|
-
|
58
|
-
if (asText) return dedent(tag.textContent);
|
59
|
-
|
60
|
-
console.warn(
|
61
|
-
`Deprecated: use <script type="${TYPE}"> for an always safe content parsing:\n`,
|
62
|
-
tag.innerHTML,
|
63
|
-
);
|
64
|
-
|
65
|
-
return dedent(tag.innerHTML);
|
66
|
-
};
|
67
|
-
|
68
39
|
// common life-cycle handlers for any node
|
69
|
-
const bootstrapNodeAndPlugins = (
|
40
|
+
const bootstrapNodeAndPlugins = (wrap, element, callback, hook) => {
|
70
41
|
// make it possible to reach the current target node via Python
|
71
42
|
callback(element);
|
72
|
-
for (const fn of hooks[hook]) fn(
|
43
|
+
for (const fn of hooks[hook]) fn(wrap, element);
|
73
44
|
};
|
74
45
|
|
75
46
|
let shouldRegister = true;
|
@@ -128,132 +99,188 @@ const workerHooks = {
|
|
128
99
|
[...hooks.codeAfterRunWorkerAsync].map(dedent).join("\n"),
|
129
100
|
};
|
130
101
|
|
131
|
-
|
132
|
-
|
133
|
-
|
134
|
-
|
135
|
-
|
136
|
-
|
137
|
-
|
138
|
-
|
139
|
-
|
140
|
-
|
141
|
-
|
142
|
-
|
143
|
-
|
144
|
-
|
145
|
-
|
146
|
-
|
147
|
-
|
148
|
-
|
149
|
-
|
150
|
-
|
151
|
-
|
152
|
-
onBeforeRunAsync(pyodide, element) {
|
153
|
-
currentElement = element;
|
154
|
-
bootstrapNodeAndPlugins(
|
155
|
-
pyodide,
|
156
|
-
element,
|
157
|
-
before,
|
158
|
-
"onBeforeRunAsync",
|
159
|
-
);
|
160
|
-
},
|
161
|
-
onAfterRun(pyodide, element) {
|
162
|
-
bootstrapNodeAndPlugins(pyodide, element, after, "onAfterRun");
|
163
|
-
},
|
164
|
-
onAfterRunAsync(pyodide, element) {
|
165
|
-
bootstrapNodeAndPlugins(pyodide, element, after, "onAfterRunAsync");
|
166
|
-
},
|
167
|
-
async onInterpreterReady(pyodide, element) {
|
168
|
-
if (shouldRegister) {
|
169
|
-
shouldRegister = false;
|
170
|
-
registerModule(pyodide);
|
102
|
+
const exportedConfig = {};
|
103
|
+
export { exportedConfig as config };
|
104
|
+
|
105
|
+
for (const [TYPE, interpreter] of TYPES) {
|
106
|
+
const { config, plugins, error } = configs.get(TYPE);
|
107
|
+
|
108
|
+
// create a unique identifier when/if needed
|
109
|
+
let id = 0;
|
110
|
+
const getID = (prefix = TYPE) => `${prefix}-${id++}`;
|
111
|
+
|
112
|
+
/**
|
113
|
+
* Given a generic DOM Element, tries to fetch the 'src' attribute, if present.
|
114
|
+
* It either throws an error if the 'src' can't be fetched or it returns a fallback
|
115
|
+
* content as source.
|
116
|
+
*/
|
117
|
+
const fetchSource = async (tag, io, asText) => {
|
118
|
+
if (tag.hasAttribute("src")) {
|
119
|
+
try {
|
120
|
+
return await fetch(tag.getAttribute("src")).then(getText);
|
121
|
+
} catch (error) {
|
122
|
+
io.stderr(error);
|
171
123
|
}
|
124
|
+
}
|
172
125
|
|
173
|
-
|
174
|
-
|
175
|
-
|
176
|
-
|
177
|
-
|
178
|
-
|
179
|
-
|
180
|
-
|
181
|
-
|
182
|
-
|
183
|
-
|
184
|
-
|
185
|
-
|
186
|
-
|
187
|
-
|
188
|
-
|
189
|
-
|
190
|
-
|
191
|
-
|
126
|
+
if (asText) return dedent(tag.textContent);
|
127
|
+
|
128
|
+
console.warn(
|
129
|
+
`Deprecated: use <script type="${TYPE}"> for an always safe content parsing:\n`,
|
130
|
+
tag.innerHTML,
|
131
|
+
);
|
132
|
+
|
133
|
+
return dedent(tag.innerHTML);
|
134
|
+
};
|
135
|
+
|
136
|
+
// define the module as both `<script type="py">` and `<py-script>`
|
137
|
+
// but only if the config didn't throw an error
|
138
|
+
if (!error) {
|
139
|
+
// possible early errors sent by polyscript
|
140
|
+
const errors = new Map();
|
141
|
+
|
142
|
+
define(TYPE, {
|
143
|
+
config,
|
144
|
+
interpreter,
|
145
|
+
env: `${TYPE}-script`,
|
146
|
+
onerror(error, element) {
|
147
|
+
errors.set(element, error);
|
148
|
+
},
|
149
|
+
...workerHooks,
|
150
|
+
onWorkerReady(_, xworker) {
|
151
|
+
assign(xworker.sync, sync);
|
152
|
+
},
|
153
|
+
onBeforeRun(wrap, element) {
|
154
|
+
currentElement = element;
|
155
|
+
bootstrapNodeAndPlugins(wrap, element, before, "onBeforeRun");
|
156
|
+
},
|
157
|
+
onBeforeRunAsync(wrap, element) {
|
158
|
+
currentElement = element;
|
159
|
+
bootstrapNodeAndPlugins(
|
160
|
+
wrap,
|
161
|
+
element,
|
162
|
+
before,
|
163
|
+
"onBeforeRunAsync",
|
164
|
+
);
|
165
|
+
},
|
166
|
+
onAfterRun(wrap, element) {
|
167
|
+
bootstrapNodeAndPlugins(wrap, element, after, "onAfterRun");
|
168
|
+
},
|
169
|
+
onAfterRunAsync(wrap, element) {
|
170
|
+
bootstrapNodeAndPlugins(
|
171
|
+
wrap,
|
172
|
+
element,
|
173
|
+
after,
|
174
|
+
"onAfterRunAsync",
|
175
|
+
);
|
176
|
+
},
|
177
|
+
async onInterpreterReady(wrap, element) {
|
178
|
+
if (shouldRegister) {
|
179
|
+
shouldRegister = false;
|
180
|
+
registerModule(wrap);
|
181
|
+
}
|
192
182
|
|
193
|
-
|
194
|
-
|
195
|
-
|
196
|
-
|
197
|
-
|
198
|
-
const
|
199
|
-
|
200
|
-
|
201
|
-
|
202
|
-
if
|
203
|
-
|
204
|
-
|
205
|
-
|
183
|
+
// ensure plugins are bootstrapped already
|
184
|
+
if (plugins) await plugins;
|
185
|
+
|
186
|
+
// allows plugins to do whatever they want with the element
|
187
|
+
// before regular stuff happens in here
|
188
|
+
for (const callback of hooks.onInterpreterReady)
|
189
|
+
callback(wrap, element);
|
190
|
+
|
191
|
+
// now that all possible plugins are configured,
|
192
|
+
// bail out if polyscript encountered an error
|
193
|
+
if (errors.has(element)) {
|
194
|
+
let { message } = errors.get(element);
|
195
|
+
errors.delete(element);
|
196
|
+
const clone = message === INVALID_CONTENT;
|
197
|
+
message = `(${ErrorCode.CONFLICTING_CODE}) ${message} for `;
|
198
|
+
message += element.cloneNode(clone).outerHTML;
|
199
|
+
wrap.io.stderr(message);
|
200
|
+
return;
|
206
201
|
}
|
207
|
-
if (!show.id) show.id = getID();
|
208
202
|
|
209
|
-
|
210
|
-
|
211
|
-
|
203
|
+
if (isScript(element)) {
|
204
|
+
const {
|
205
|
+
attributes: { async: isAsync, target },
|
206
|
+
} = element;
|
207
|
+
const hasTarget = !!target?.value;
|
208
|
+
const show = hasTarget
|
209
|
+
? queryTarget(target.value)
|
210
|
+
: document.createElement("script-py");
|
211
|
+
|
212
|
+
if (!hasTarget) {
|
213
|
+
const { head, body } = document;
|
214
|
+
if (head.contains(element)) body.append(show);
|
215
|
+
else element.after(show);
|
216
|
+
}
|
217
|
+
if (!show.id) show.id = getID();
|
218
|
+
|
219
|
+
// allows the code to retrieve the target element via
|
220
|
+
// document.currentScript.target if needed
|
221
|
+
defineProperty(element, "target", { value: show });
|
222
|
+
|
223
|
+
// notify before the code runs
|
224
|
+
dispatch(element, TYPE);
|
225
|
+
wrap[`run${isAsync ? "Async" : ""}`](
|
226
|
+
await fetchSource(element, wrap.io, true),
|
227
|
+
);
|
228
|
+
} else {
|
229
|
+
// resolve PyScriptElement to allow connectedCallback
|
230
|
+
element._wrap.resolve(wrap);
|
231
|
+
}
|
232
|
+
console.debug("[pyscript/main] PyScript Ready");
|
233
|
+
},
|
234
|
+
});
|
235
|
+
}
|
212
236
|
|
213
|
-
|
214
|
-
|
215
|
-
|
216
|
-
|
237
|
+
class PyScriptElement extends HTMLElement {
|
238
|
+
constructor() {
|
239
|
+
assign(super(), {
|
240
|
+
_wrap: Promise.withResolvers(),
|
241
|
+
srcCode: "",
|
242
|
+
executed: false,
|
243
|
+
});
|
244
|
+
}
|
245
|
+
get _pyodide() {
|
246
|
+
// TODO: deprecate this hidden attribute already
|
247
|
+
// currently used by integration tests
|
248
|
+
return this._wrap;
|
249
|
+
}
|
250
|
+
get id() {
|
251
|
+
return super.id || (super.id = getID());
|
252
|
+
}
|
253
|
+
set id(value) {
|
254
|
+
super.id = value;
|
255
|
+
}
|
256
|
+
async connectedCallback() {
|
257
|
+
if (!this.executed) {
|
258
|
+
this.executed = true;
|
259
|
+
const { io, run, runAsync } = await this._wrap.promise;
|
260
|
+
const runner = this.hasAttribute("async") ? runAsync : run;
|
261
|
+
this.srcCode = await fetchSource(
|
262
|
+
this,
|
263
|
+
io,
|
264
|
+
!this.childElementCount,
|
217
265
|
);
|
218
|
-
|
219
|
-
//
|
220
|
-
|
266
|
+
this.replaceChildren();
|
267
|
+
// notify before the code runs
|
268
|
+
dispatch(this, TYPE);
|
269
|
+
runner(this.srcCode);
|
270
|
+
this.style.display = "block";
|
221
271
|
}
|
222
|
-
console.debug("[pyscript/main] PyScript Ready");
|
223
|
-
},
|
224
|
-
});
|
225
|
-
|
226
|
-
class PyScriptElement extends HTMLElement {
|
227
|
-
constructor() {
|
228
|
-
assign(super(), {
|
229
|
-
_pyodide: Promise.withResolvers(),
|
230
|
-
srcCode: "",
|
231
|
-
executed: false,
|
232
|
-
});
|
233
|
-
}
|
234
|
-
get id() {
|
235
|
-
return super.id || (super.id = getID());
|
236
|
-
}
|
237
|
-
set id(value) {
|
238
|
-
super.id = value;
|
239
|
-
}
|
240
|
-
async connectedCallback() {
|
241
|
-
if (!this.executed) {
|
242
|
-
this.executed = true;
|
243
|
-
const { io, run, runAsync } = await this._pyodide.promise;
|
244
|
-
const runner = this.hasAttribute("async") ? runAsync : run;
|
245
|
-
this.srcCode = await fetchSource(this, io, !this.childElementCount);
|
246
|
-
this.replaceChildren();
|
247
|
-
// notify before the code runs
|
248
|
-
dispatch(this, TYPE);
|
249
|
-
runner(this.srcCode);
|
250
|
-
this.style.display = "block";
|
251
272
|
}
|
252
273
|
}
|
274
|
+
|
275
|
+
// define py-script only if the config didn't throw an error
|
276
|
+
if (!error) customElements.define(`${TYPE}-script`, PyScriptElement);
|
277
|
+
|
278
|
+
// export the used config without allowing leaks through it
|
279
|
+
exportedConfig[TYPE] = structuredClone(config);
|
253
280
|
}
|
254
281
|
|
255
|
-
//
|
256
|
-
|
282
|
+
// TBD: I think manual worker cases are interesting in pyodide only
|
283
|
+
// so for the time being we should be fine with this export.
|
257
284
|
|
258
285
|
/**
|
259
286
|
* A `Worker` facade able to bootstrap on the worker thread only a PyScript module.
|
@@ -31,4 +31,13 @@
|
|
31
31
|
|
32
32
|
from pyscript.magic_js import RUNNING_IN_WORKER, window, document, sync
|
33
33
|
from pyscript.display import HTML, display
|
34
|
-
|
34
|
+
|
35
|
+
try:
|
36
|
+
from pyscript.event_handling import when
|
37
|
+
except:
|
38
|
+
from pyscript.util import NotSupported
|
39
|
+
|
40
|
+
when = NotSupported(
|
41
|
+
"pyscript.when",
|
42
|
+
"pyscript.when currently not available with this interpreter"
|
43
|
+
)
|
@@ -5,12 +5,11 @@ class NotSupported:
|
|
5
5
|
"""
|
6
6
|
|
7
7
|
def __init__(self, name, error):
|
8
|
-
|
9
|
-
self
|
10
|
-
self.__dict__['error'] = error
|
8
|
+
object.__setattr__(self, "name", name)
|
9
|
+
object.__setattr__(self, "error", error)
|
11
10
|
|
12
11
|
def __repr__(self):
|
13
|
-
return f
|
12
|
+
return f"<NotSupported {self.name} [{self.error}]>"
|
14
13
|
|
15
14
|
def __getattr__(self, attr):
|
16
15
|
raise AttributeError(self.error)
|
package/src/stdlib/pyscript.js
CHANGED
@@ -1,11 +1,11 @@
|
|
1
1
|
// ⚠️ This file is an artifact: DO NOT MODIFY
|
2
2
|
export default {
|
3
3
|
"pyscript": {
|
4
|
-
"__init__.py": "# Some notes about the naming conventions and the relationship between various\n# similar-but-different names.\n#\n# import pyscript\n# this package contains the main user-facing API offered by pyscript. All\n# the names which are supposed be used by end users should be made\n# available in pyscript/__init__.py (i.e., this file)\n#\n# import _pyscript\n# this is an internal module implemented in JS. It is used internally by\n# the pyscript package, end users should not use it directly. For its\n# implementation, grep for `interpreter.registerJsModule(\"_pyscript\",\n# ...)` in core.js\n#\n# import js\n# this is the JS globalThis, as exported by pyodide and/or micropython's\n# FFIs. As such, it contains different things in the main thread or in a\n# worker.\n#\n# import pyscript.magic_js\n# this submodule abstracts away some of the differences between the main\n# thread and the worker. In particular, it defines `window` and `document`\n# in such a way that these names work in both cases: in the main thread,\n# they are the \"real\" objects, in the worker they are proxies which work\n# thanks to coincident.\n#\n# from pyscript import window, document\n# these are just the window and document objects as defined by\n# pyscript.magic_js. This is the blessed way to access them from pyscript,\n# as it works transparently in both the main thread and worker cases.\n\nfrom pyscript.magic_js import RUNNING_IN_WORKER, window, document, sync\nfrom pyscript.display import HTML, display\
|
4
|
+
"__init__.py": "# Some notes about the naming conventions and the relationship between various\n# similar-but-different names.\n#\n# import pyscript\n# this package contains the main user-facing API offered by pyscript. All\n# the names which are supposed be used by end users should be made\n# available in pyscript/__init__.py (i.e., this file)\n#\n# import _pyscript\n# this is an internal module implemented in JS. It is used internally by\n# the pyscript package, end users should not use it directly. For its\n# implementation, grep for `interpreter.registerJsModule(\"_pyscript\",\n# ...)` in core.js\n#\n# import js\n# this is the JS globalThis, as exported by pyodide and/or micropython's\n# FFIs. As such, it contains different things in the main thread or in a\n# worker.\n#\n# import pyscript.magic_js\n# this submodule abstracts away some of the differences between the main\n# thread and the worker. In particular, it defines `window` and `document`\n# in such a way that these names work in both cases: in the main thread,\n# they are the \"real\" objects, in the worker they are proxies which work\n# thanks to coincident.\n#\n# from pyscript import window, document\n# these are just the window and document objects as defined by\n# pyscript.magic_js. This is the blessed way to access them from pyscript,\n# as it works transparently in both the main thread and worker cases.\n\nfrom pyscript.magic_js import RUNNING_IN_WORKER, window, document, sync\nfrom pyscript.display import HTML, display\n\ntry:\n from pyscript.event_handling import when\nexcept:\n from pyscript.util import NotSupported\n\n when = NotSupported(\n \"pyscript.when\",\n \"pyscript.when currently not available with this interpreter\"\n )\n",
|
5
5
|
"display.py": "import base64\nimport html\nimport io\nimport re\n\nfrom pyscript.magic_js import document, window, current_target\n\n_MIME_METHODS = {\n \"__repr__\": \"text/plain\",\n \"_repr_html_\": \"text/html\",\n \"_repr_markdown_\": \"text/markdown\",\n \"_repr_svg_\": \"image/svg+xml\",\n \"_repr_png_\": \"image/png\",\n \"_repr_pdf_\": \"application/pdf\",\n \"_repr_jpeg_\": \"image/jpeg\",\n \"_repr_latex\": \"text/latex\",\n \"_repr_json_\": \"application/json\",\n \"_repr_javascript_\": \"application/javascript\",\n \"savefig\": \"image/png\",\n}\n\n\ndef _render_image(mime, value, meta):\n # If the image value is using bytes we should convert it to base64\n # otherwise it will return raw bytes and the browser will not be able to\n # render it.\n if isinstance(value, bytes):\n value = base64.b64encode(value).decode(\"utf-8\")\n\n # This is the pattern of base64 strings\n base64_pattern = re.compile(\n r\"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$\"\n )\n # If value doesn't match the base64 pattern we should encode it to base64\n if len(value) > 0 and not base64_pattern.match(value):\n value = base64.b64encode(value.encode(\"utf-8\")).decode(\"utf-8\")\n\n data = f\"data:{mime};charset=utf-8;base64,{value}\"\n attrs = \" \".join(['{k}=\"{v}\"' for k, v in meta.items()])\n return f'<img src=\"{data}\" {attrs}></img>'\n\n\ndef _identity(value, meta):\n return value\n\n\n_MIME_RENDERERS = {\n \"text/plain\": html.escape,\n \"text/html\": _identity,\n \"image/png\": lambda value, meta: _render_image(\"image/png\", value, meta),\n \"image/jpeg\": lambda value, meta: _render_image(\"image/jpeg\", value, meta),\n \"image/svg+xml\": _identity,\n \"application/json\": _identity,\n \"application/javascript\": lambda value, meta: f\"<script>{value}<\\\\/script>\",\n}\n\n\nclass HTML:\n \"\"\"\n Wrap a string so that display() can render it as plain HTML\n \"\"\"\n\n def __init__(self, html):\n self._html = html\n\n def _repr_html_(self):\n return self._html\n\n\ndef _eval_formatter(obj, print_method):\n \"\"\"\n Evaluates a formatter method.\n \"\"\"\n if print_method == \"__repr__\":\n return repr(obj)\n elif hasattr(obj, print_method):\n if print_method == \"savefig\":\n buf = io.BytesIO()\n obj.savefig(buf, format=\"png\")\n buf.seek(0)\n return base64.b64encode(buf.read()).decode(\"utf-8\")\n return getattr(obj, print_method)()\n elif print_method == \"_repr_mimebundle_\":\n return {}, {}\n return None\n\n\ndef _format_mime(obj):\n \"\"\"\n Formats object using _repr_x_ methods.\n \"\"\"\n if isinstance(obj, str):\n return html.escape(obj), \"text/plain\"\n\n mimebundle = _eval_formatter(obj, \"_repr_mimebundle_\")\n if isinstance(mimebundle, tuple):\n format_dict, _ = mimebundle\n else:\n format_dict = mimebundle\n\n output, not_available = None, []\n for method, mime_type in reversed(_MIME_METHODS.items()):\n if mime_type in format_dict:\n output = format_dict[mime_type]\n else:\n output = _eval_formatter(obj, method)\n\n if output is None:\n continue\n elif mime_type not in _MIME_RENDERERS:\n not_available.append(mime_type)\n continue\n break\n if output is None:\n if not_available:\n window.console.warn(\n f\"Rendered object requested unavailable MIME renderers: {not_available}\"\n )\n output = repr(output)\n mime_type = \"text/plain\"\n elif isinstance(output, tuple):\n output, meta = output\n else:\n meta = {}\n return _MIME_RENDERERS[mime_type](output, meta), mime_type\n\n\ndef _write(element, value, append=False):\n html, mime_type = _format_mime(value)\n if html == \"\\\\n\":\n return\n\n if append:\n out_element = document.createElement(\"div\")\n element.append(out_element)\n else:\n out_element = element.lastElementChild\n if out_element is None:\n out_element = element\n\n if mime_type in (\"application/javascript\", \"text/html\"):\n script_element = document.createRange().createContextualFragment(html)\n out_element.append(script_element)\n else:\n out_element.innerHTML = html\n\n\ndef display(*values, target=None, append=True):\n if target is None:\n target = current_target()\n\n element = document.getElementById(target)\n\n # if element is a <script type=\"py\">, it has a 'target' attribute which\n # points to the visual element holding the displayed values. In that case,\n # use that.\n if element.tagName == 'SCRIPT' and hasattr(element, 'target'):\n element = element.target\n\n for v in values:\n _write(element, v, append=append)\n",
|
6
6
|
"event_handling.py": "import inspect\n\nfrom pyodide.ffi.wrappers import add_event_listener\nfrom pyscript.magic_js import document\n\n\ndef when(event_type=None, selector=None):\n \"\"\"\n Decorates a function and passes py-* events to the decorated function\n The events might or not be an argument of the decorated function\n \"\"\"\n\n def decorator(func):\n if isinstance(selector, str):\n elements = document.querySelectorAll(selector)\n else:\n # TODO: This is a hack that will be removed when pyscript becomes a package\n # and we can better manage the imports without circular dependencies\n from pyweb import pydom\n\n if isinstance(selector, pydom.Element):\n elements = [selector._js]\n elif isinstance(selector, pydom.ElementCollection):\n elements = [el._js for el in selector]\n else:\n raise ValueError(\n f\"Invalid selector: {selector}. Selector must\"\n \" be a string, a pydom.Element or a pydom.ElementCollection.\"\n )\n\n sig = inspect.signature(func)\n # Function doesn't receive events\n if not sig.parameters:\n\n def wrapper(*args, **kwargs):\n func()\n\n for el in elements:\n add_event_listener(el, event_type, wrapper)\n else:\n for el in elements:\n add_event_listener(el, event_type, func)\n return func\n\n return decorator\n",
|
7
7
|
"magic_js.py": "from pyscript.util import NotSupported\nimport js as globalThis\n\nRUNNING_IN_WORKER = not hasattr(globalThis, \"document\")\n\nif RUNNING_IN_WORKER:\n import polyscript\n\n PyWorker = NotSupported(\n 'pyscript.PyWorker',\n 'pyscript.PyWorker works only when running in the main thread')\n window = polyscript.xworker.window\n document = window.document\n sync = polyscript.xworker.sync\n\n # in workers the display does not have a default ID\n # but there is a sync utility from xworker\n def current_target():\n return polyscript.target\n\nelse:\n import _pyscript\n from _pyscript import PyWorker\n window = globalThis\n document = globalThis.document\n sync = NotSupported(\n 'pyscript.sync',\n 'pyscript.sync works only when running in a worker')\n\n # in MAIN the current element target exist, just use it\n def current_target():\n return _pyscript.target\n",
|
8
|
-
"util.py": "class NotSupported:\n \"\"\"\n Small helper that raises exceptions if you try to get/set any attribute on\n it.\n \"\"\"\n\n def __init__(self, name, error):\n
|
8
|
+
"util.py": "class NotSupported:\n \"\"\"\n Small helper that raises exceptions if you try to get/set any attribute on\n it.\n \"\"\"\n\n def __init__(self, name, error):\n object.__setattr__(self, \"name\", name)\n object.__setattr__(self, \"error\", error)\n\n def __repr__(self):\n return f\"<NotSupported {self.name} [{self.error}]>\"\n\n def __getattr__(self, attr):\n raise AttributeError(self.error)\n\n def __setattr__(self, attr, value):\n raise AttributeError(self.error)\n\n def __call__(self, *args):\n raise TypeError(self.error)\n"
|
9
9
|
},
|
10
10
|
"pyweb": {
|
11
11
|
"pydom.py": "import sys\nimport warnings\nfrom functools import cached_property\nfrom typing import Any\n\nfrom pyodide.ffi import JsProxy\nfrom pyscript import display, document, window\n\n# from pyscript import when as _when\n\nalert = window.alert\n\n\nclass BaseElement:\n def __init__(self, js_element):\n self._js = js_element\n self._parent = None\n self.style = StyleProxy(self)\n\n def __eq__(self, obj):\n \"\"\"Check if the element is the same as the other element by comparing\n the underlying JS element\"\"\"\n return isinstance(obj, BaseElement) and obj._js == self._js\n\n @property\n def parent(self):\n if self._parent:\n return self._parent\n\n if self._js.parentElement:\n self._parent = self.__class__(self._js.parentElement)\n\n return self._parent\n\n @property\n def __class(self):\n return self.__class__ if self.__class__ != PyDom else Element\n\n def create(self, type_, is_child=True, classes=None, html=None, label=None):\n js_el = document.createElement(type_)\n element = self.__class(js_el)\n\n if classes:\n for class_ in classes:\n element.add_class(class_)\n\n if html is not None:\n element.html = html\n\n if label is not None:\n element.label = label\n\n if is_child:\n self.append(element)\n\n return element\n\n def find(self, selector):\n \"\"\"Return an ElementCollection representing all the child elements that\n match the specified selector.\n\n Args:\n selector (str): A string containing a selector expression\n\n Returns:\n ElementCollection: A collection of elements matching the selector\n \"\"\"\n elements = self._js.querySelectorAll(selector)\n if not elements:\n return None\n return ElementCollection([Element(el) for el in elements])\n\n\nclass Element(BaseElement):\n @property\n def children(self):\n return [self.__class__(el) for el in self._js.children]\n\n def append(self, child):\n # TODO: this is Pyodide specific for now!!!!!!\n # if we get passed a JSProxy Element directly we just map it to the\n # higher level Python element\n if isinstance(child, JsProxy):\n return self.append(Element(child))\n\n elif isinstance(child, Element):\n self._js.appendChild(child._js)\n\n return child\n\n elif isinstance(child, ElementCollection):\n for el in child:\n self.append(el)\n\n # -------- Pythonic Interface to Element -------- #\n @property\n def html(self):\n return self._js.innerHTML\n\n @html.setter\n def html(self, value):\n self._js.innerHTML = value\n\n @property\n def content(self):\n # TODO: This breaks with with standard template elements. Define how to best\n # handle this specifica use case. Just not support for now?\n if self._js.tagName == \"TEMPLATE\":\n warnings.warn(\n \"Content attribute not supported for template elements.\", stacklevel=2\n )\n return None\n return self._js.innerHTML\n\n @content.setter\n def content(self, value):\n # TODO: (same comment as above)\n if self._js.tagName == \"TEMPLATE\":\n warnings.warn(\n \"Content attribute not supported for template elements.\", stacklevel=2\n )\n return\n\n display(value, target=self.id)\n\n @property\n def id(self):\n return self._js.id\n\n @id.setter\n def id(self, value):\n self._js.id = value\n\n def clone(self, new_id=None):\n clone = Element(self._js.cloneNode(True))\n clone.id = new_id\n\n return clone\n\n def remove_class(self, classname):\n classList = self._js.classList\n if isinstance(classname, list):\n classList.remove(*classname)\n else:\n classList.remove(classname)\n return self\n\n def add_class(self, classname):\n classList = self._js.classList\n if isinstance(classname, list):\n classList.add(*classname)\n else:\n self._js.classList.add(classname)\n return self\n\n @property\n def classes(self):\n classes = self._js.classList.values()\n return [x for x in classes]\n\n def show_me(self):\n self._js.scrollIntoView()\n\n def when(self, event, handler):\n document.when(event, selector=self)(handler)\n\n\nclass StyleProxy(dict):\n def __init__(self, element: Element) -> None:\n self._element = element\n\n @cached_property\n def _style(self):\n return self._element._js.style\n\n def __getitem__(self, key):\n return self._style.getPropertyValue(key)\n\n def __setitem__(self, key, value):\n self._style.setProperty(key, value)\n\n def remove(self, key):\n self._style.removeProperty(key)\n\n def set(self, **kws):\n for k, v in kws.items():\n self._element._js.style.setProperty(k, v)\n\n # CSS Properties\n # Reference: https://github.com/microsoft/TypeScript/blob/main/src/lib/dom.generated.d.ts#L3799C1-L5005C2\n # Following prperties automatically generated from the above reference using\n # tools/codegen_css_proxy.py\n @property\n def visible(self):\n return self._element._js.style.visibility\n\n @visible.setter\n def visible(self, value):\n self._element._js.style.visibility = value\n\n\nclass StyleCollection:\n def __init__(self, collection: \"ElementCollection\") -> None:\n self._collection = collection\n\n def __get__(self, obj, objtype=None):\n return obj._get_attribute(\"style\")\n\n def __getitem__(self, key):\n return self._collection._get_attribute(\"style\")[key]\n\n def __setitem__(self, key, value):\n for element in self._collection._elements:\n element.style[key] = value\n\n def remove(self, key):\n for element in self._collection._elements:\n element.style.remove(key)\n\n\nclass ElementCollection:\n def __init__(self, elements: [Element]) -> None:\n self._elements = elements\n self.style = StyleCollection(self)\n\n def __getitem__(self, key):\n # If it's an integer we use it to access the elements in the collection\n if isinstance(key, int):\n return self._elements[key]\n # If it's a slice we use it to support slice operations over the elements\n # in the collection\n elif isinstance(key, slice):\n return ElementCollection(self._elements[key])\n\n # If it's anything else (basically a string) we use it as a selector\n # TODO: Write tests!\n elements = self._element.querySelectorAll(key)\n return ElementCollection([Element(el) for el in elements])\n\n def __len__(self):\n return len(self._elements)\n\n def __eq__(self, obj):\n \"\"\"Check if the element is the same as the other element by comparing\n the underlying JS element\"\"\"\n return isinstance(obj, ElementCollection) and obj._elements == self._elements\n\n def _get_attribute(self, attr, index=None):\n if index is None:\n return [getattr(el, attr) for el in self._elements]\n\n # As JQuery, when getting an attr, only return it for the first element\n return getattr(self._elements[index], attr)\n\n def _set_attribute(self, attr, value):\n for el in self._elements:\n setattr(el, attr, value)\n\n @property\n def html(self):\n return self._get_attribute(\"html\")\n\n @html.setter\n def html(self, value):\n self._set_attribute(\"html\", value)\n\n @property\n def children(self):\n return self._elements\n\n def __iter__(self):\n yield from self._elements\n\n def __repr__(self):\n return f\"{self.__class__.__name__} (length: {len(self._elements)}) {self._elements}\"\n\n\nclass DomScope:\n def __getattr__(self, __name: str) -> Any:\n element = document[f\"#{__name}\"]\n if element:\n return element[0]\n\n\nclass PyDom(BaseElement):\n # Add objects we want to expose to the DOM namespace since this class instance is being\n # remapped as \"the module\" itself\n BaseElement = BaseElement\n Element = Element\n ElementCollection = ElementCollection\n\n def __init__(self):\n super().__init__(document)\n self.ids = DomScope()\n self.body = Element(document.body)\n self.head = Element(document.head)\n\n def create(self, type_, parent=None, classes=None, html=None):\n return super().create(type_, is_child=False)\n\n def __getitem__(self, key):\n if isinstance(key, int):\n indices = range(*key.indices(len(self.list)))\n return [self.list[i] for i in indices]\n\n elements = self._js.querySelectorAll(key)\n if not elements:\n return None\n return ElementCollection([Element(el) for el in elements])\n\n\ndom = PyDom()\n\nsys.modules[__name__] = dom\n"
|
package/src/types.js
ADDED
package/types/config.d.ts
CHANGED
package/types/core.d.ts
CHANGED
@@ -21,5 +21,6 @@ export namespace hooks {
|
|
21
21
|
let codeAfterRunWorker: Set<string>;
|
22
22
|
let codeAfterRunWorkerAsync: Set<string>;
|
23
23
|
}
|
24
|
-
|
24
|
+
export { exportedConfig as config };
|
25
25
|
import sync from "./sync.js";
|
26
|
+
declare const exportedConfig: {};
|
package/types/types.d.ts
ADDED