8000 add initializers that run before py-script scripts run and post initi… · evolution99/pyscript@5ec8569 · GitHub
[go: up one dir, main page]

Skip to content

Commit 5ec8569

Browse files
committed
add initializers that run before py-script scripts run and post initializers that run after. Also add function to unescape some of the characters when read form html tags
1 parent be0037b commit 5ec8569

File tree

4 files changed

+55
-16
lines changed

4 files changed

+55
-16
lines changed

pyscriptjs/src/App.svelte

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import { faPlusCircle } from '@fortawesome/free-solid-svg-icons'
55
import Tailwind from "./Tailwind.svelte";
66
import { loadInterpreter } from './interpreter';
7-
import { pyodideLoaded, loadedEnvironments, navBarOpen, componentsNavOpen, mode, scriptsQueue, initializers } from './stores';
7+
import { pyodideLoaded, loadedEnvironments, navBarOpen, componentsNavOpen, mode, scriptsQueue, initializers, postInitializers } from './stores';
88
import Main from "./Main.svelte";
99
import Header from "./Header.svelte";
1010
import SideNav from "./SideNav.svelte";
@@ -42,16 +42,21 @@
4242
showNavBar = value;
4343
});
4444
45+
// now we call all initializers before we actually executed all page scripts
46+
for (let initializer of $initializers){
47+
initializer();
48+
}
49+
4550
// now we can actually execute the page scripts if we are in play mode
4651
if ($mode == "play"){
4752
for (let script of $scriptsQueue) {
4853
script.evaluate();
4954
}
50-
scriptsQueue.set([])
55+
scriptsQueue.set([]);
5156
}
5257
53-
// now we call all initializers AFTER we actually executed all page scripts
54-
for (let initializer of $initializers){
58+
// now we call all post initializers AFTER we actually executed all page scripts
59+
for (let initializer of $postInitializers){
5560
initializer();
5661
}
5762
}

pyscriptjs/src/components/pyscript.ts

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { keymap, ViewUpdate } from "@codemirror/view";
66
import { defaultKeymap } from "@codemirror/commands";
77
import { oneDarkTheme } from "@codemirror/theme-one-dark";
88

9-
import { pyodideLoaded, loadedEnvironments, componentDetailsNavOpen, currentComponentDetails, mode, addToScriptsQueue, addInitializer } from '../stores';
9+
import { pyodideLoaded, loadedEnvironments, componentDetailsNavOpen, currentComponentDetails, mode, addToScriptsQueue, addInitializer, addPostInitializer } from '../stores';
1010
import { addClasses } from '../utils';
1111

1212
// Premise used to connect to the first available pyodide interpreter
@@ -40,6 +40,10 @@ function createCmdHandler(el){
4040
return toggleCheckbox
4141
}
4242

43+
function htmlDecode(input) {
44+
var doc = new DOMParser().parseFromString(input, "text/html");
45+
return doc.documentElement.textContent;
46+
}
4347

4448
class Script {
4549
source: string;
@@ -214,7 +218,7 @@ export class PyScript extends HTMLElement {
214218
// debugger
215219
try {
216220
// @ts-ignore
217-
let source = this.editor.state.doc.toString();
221+
let source = htmlDecode(this.editor.state.doc.toString());
218222
let output;
219223
if (source.includes("asyncio")){
220224
output = await pyodide.runPythonAsync(source);
@@ -232,6 +236,7 @@ export class PyScript extends HTMLElement {
232236
}
233237
} catch (err) {
234238
this.addToOutput(err);
239+
console.log(err);
235240
}
236241
}
237242

@@ -241,9 +246,8 @@ export class PyScript extends HTMLElement {
241246
}
242247
}
243248

249+
/** Initialize all elements with py-onClick handlers attributes */
244250
async function initHandlers() {
245-
if( handlersCollected == true ) return;
246-
247251
console.log('Collecting nodes...');
248252
let pyodide = await pyodideReadyPromise;
249253
let matches : NodeListOf<HTMLElement> = document.querySelectorAll('[pys-onClick]');
@@ -254,6 +258,7 @@ async function initHandlers() {
254258
source = `Element("${ el.id }").element.onclick = ${ handlerCode }`;
255259
output = await pyodide.runPythonAsync(source);
256260

261+
// TODO: Should we actually map handlers in JS instaed of Python?
257262
// el.onclick = (evt: any) => {
258263
// console.log("click");
259264
// new Promise((resolve, reject) => {
@@ -276,11 +281,22 @@ async function initHandlers() {
276281
output = await pyodide.runPythonAsync(source);
277282
}
278283
}
279-
addInitializer(initHandlers)
280284

281-
// if( document.readyState === 'loading' ) {
282-
// document.addEventListener( 'DOMContentLoaded', initHandlers );
283-
// }
284-
// else if( document.readyState === 'interactive' || document.readyState === 'complete' ) {
285-
// initHandlers();
286-
// }
285+
/** Mount all elements with attribute py-mount into the Python namespace */
286+
async function mountElements() {
287+
console.log('Collecting nodes to be mounted into python namespace...');
288+
let pyodide = await pyodideReadyPromise;
289+
let matches : NodeListOf<HTMLElement> = document.querySelectorAll('[py-mount]');
290+
let output;
291+
let source = "";
292+
for (var el of matches) {
293+
let mountName = el.getAttribute('py-mount');
294+
if (!mountName){
295+
mountName = el.id.replace("-", "_");
296+
}
297+
source += `\n${ mountName } = Element("${ el.id }")`;
298+
}
299+
await pyodide.runPythonAsync(source);
300+
}
301+
addPostInitializer(initHandlers);
302+
addInitializer(mountElements);

pyscriptjs/src/interpreter.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ let loadInterpreter = async function(): any {
107107
});
108108

109109
// now that we loaded, add additional convenience fuctions
110-
pyodide.loadPackage(['matplotlib', 'numpy'])
110+
pyodide.loadPackage(['matplotlib', 'numpy', 'bokeh'])
111111

112112
await pyodide.loadPackage("micropip");
113113
// await pyodide.runPythonAsync(`

pyscriptjs/src/stores.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,11 @@ export const currentComponentDetails = writable([]);
2424
export const mode = writable(DEFAULT_MODE)
2525
export const scriptsQueue = writable([])
2626
export const initializers = writable([])
27+
export const postInitializers = writable([])
2728

2829
let scriptsQueue_ = [];
2930
let initializers_ = [];
31+
let postInitializers_ = [];
3032

3133
scriptsQueue.subscribe(value => {
3234
scriptsQueue_ = value;
@@ -40,6 +42,22 @@ scriptsQueue.subscribe(value => {
4042
scriptsQueue_ = value;
4143
});
4244

45+
initializers.subscribe(value => {
46+
initializers_ = value;
47+
});
48+
4349
export const addInitializer = (initializer) => {
50+
console.log("adding initializer", initializer);
4451
initializers.set([...initializers_, initializer]);
52+
console.log("adding initializer", initializer);
53+
};
54+
55+
postInitializers.subscribe(value => {
56+
postInitializers_ = value;
57+
});
58+
59+
export const addPostInitializer = (initializer) => {
60+
console.log("adding post initializer", initializer);
61+
postInitializers.set([...postInitializers_, initializer]);
62+
console.log("adding post initializer", initializer);
4563
};

0 commit comments

Comments
 (0)
0