8000 adapt pyscript to new base class and clean Base · sudhircw/pyscript@4d89060 · GitHub
[go: up one dir, main page]

Skip to content

Commit 4d89060

Browse files
committed
adapt pyscript to new base class and clean Base
1 parent 955fb6f commit 4d89060

File tree

3 files changed

+47
-132
lines changed

3 files changed

+47
-132
lines changed

pyscriptjs/src/components/base.ts

Lines changed: 35 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ export class BaseEvalElement extends HTMLElement {
3232
shadow: ShadowRoot;
3333
wrapper: HTMLElement;
3434
code: string;
35+
source: string;
3536
btnConfig: HTMLElement;
3637
btnRun: HTMLElement;
3738
outputElement: HTMLElement; //HTMLTextAreaElement;
@@ -55,10 +56,17 @@ export class BaseEvalElement extends HTMLElement {
5556

5657
}
5758

58-
getSource(): string{
59+
getSourceFromElement(): string{
5960
return "";
6061
}
6162

63+
async getSourceFromFile(s: string): Promise<string>{
64+
let pyodide = await pyodideReadyPromise;
65+
let response = await fetch(s);
66+
this.code = await response.text();
67+
return this.code;
68+
}
69+
6270
protected async _register_esm(pyodide: PyodideInterface): Promise<void> {
6371
const imports: {[key: string]: unknown} = {}
6472

@@ -91,53 +99,44 @@ export class BaseEvalElement extends HTMLElement {
9199
pyodide.registerJsModule("esm", imports)
92100
}
93101

94-
async evaluate() {
102+
async evaluate(): Promise<void> {
95103
console.log('evaluate');
96-
let pyodide = await pyodideReadyPromise;
97-
98-
try {
104+
let pyodide = await pyodideReadyPromise;
105+
let source: string;
106+
let output;
107+
try {
99108
// @ts-ignore
100-
const source = this.getSource();
101-
await this._register_esm(pyodide)
102-
103-
let output;
109+
if (this.source){
110+
source = await this.getSourceFromFile(this.source);
111+
}else{
112+
source = this.getSourceFromElement();
113+
}
114+
115+
await this._register_esm(pyodide);
104116

105117
if (source.includes("asyncio")){
106-
output = await pyodide.runPythonAsync(source);
107-
await pyodide.runPythonAsync(`output_manager.revert()`)
118+
output = await pyodide.runPythonAsync(source);
119+
await pyodide.runPythonAsync(`output_manager.revert()`)
108120
}else{
109-
output = pyodide.runPython(source);
110-
pyodide.runPython(`output_manager.revert()`)
121+
output = pyodide.runPython(source);
122+
pyodide.runPython(`output_manager.revert()`)
111123
}
112-
124+
113125
if (output !== undefined){
114-
if (Element === undefined){
126+
if (Element === undefined){
115127
Element = pyodide.globals.get('Element');
116-
}
117-
const out = Element(this.outputElement.id);
118-
// @ts-ignore
119-
out.write.callKwargs(output, { append : true});
128+
}
129+
const out = Element(this.outputElement.id);
130+
// @ts-ignore
131+
out.write.callKwargs(output, { append : true});
120132

121-
if (!this.hasAttribute('target')) {
133+
if (!this.hasAttribute('target')) {
122134
this.outputElement.hidden = false;
123-
}
124135
}
136+
}
137+
138+
this.postEvaluate()
125139

126-
this.postEvaluate()
127-
128-
// if (this.hasAttribute('auto-generate')) {
129-
// let nextExecId = parseInt(this.getAttribute('exec-id')) + 1;
130-
// const newPyRepl = document.createElement("py-repl");
131-
// newPyRepl.setAttribute('root', this.getAttribute('root'));
132-
// newPyRepl.id = this.getAttribute('root') + "-" + nextExecId.toString();
133-
// newPyRepl.setAttribute('auto-generate', null);
134-
// if (this.hasAttribute('target')){
135-
// newPyRepl.setAttribute('target', this.getAttribute('target'));
136-
// }
137-
138-
// newPyRepl.setAttribute('exec-id', nextExecId.toString());
139-
// this.parentElement.appendChild(newPyRepl);
140-
// }
141140
} catch (err) {
142141
this.addToOutput(err);
143142
}

pyscriptjs/src/components/pyrepl.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ export class PyRepl extends BaseEvalElement {
204204
}
205205
}
206206

207-
getSource(): string {
207+
getSourceFromElement(): string {
208208
const sourceStrings = [`output_manager.change("`+this.outputElement.id+`")`,
209209
...this.editor.state.doc.toString().split("\n")];
210210
return sourceStrings.join('\n')

pyscriptjs/src/components/pyscript.ts

Lines changed: 11 additions & 95 deletions
F438
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { oneDarkTheme } from "@codemirror/theme-one-dark";
88

99
import { pyodideLoaded, loadedEnvironments, componentDetailsNavOpen, currentComponentDetails, mode, addToScriptsQueue, addInitializer, addPostInitializer } from '../stores';
1010
import { addClasses } from '../utils';
11+
import { BaseEvalElement } from './base';
1112

1213
// Premise used to connect to the first available pyodide interpreter
1314
let pyodideReadyPromise;
@@ -50,6 +51,8 @@ type PyodideInterface = {
5051
registerJsModule(name: string, module: object): void
5152
}
5253

54+
// TODO: This should be used as base for generic scripts that need exectutoin
55+
// from PyScript to initializers, etc...
5356
class Script {
5457
source: string;
5558
state: string;
@@ -90,30 +93,13 @@ class Script {
9093
}
9194
}
9295

93-
export class PyScript extends HTMLElement {
94-
shadow: ShadowRoot;
95-
wrapper: HTMLElement;
96-
editor: EditorView;
97-
editorNode: HTMLElement;
98-
code: string;
99-
cm: any;
100-
btnConfig: HTMLElement;
101-
btnRun: HTMLElement;
102-
editorOut: HTMLElement; //HTMLTextAreaElement;
103-
source: string;
96+
export class PyScript extends BaseEvalElement {
10497
// editorState: EditorState;
10598

10699
constructor() {
107100
super();
108101

109-
// attach shadow so we can preserve the element original innerHtml content
110-
this.shadow = this.attachShadow({ mode: 'open'});
111-
112-
this.wrapper = document.createElement('slot');
113-
114102
// add an extra div where we can attach the codemirror editor
115-
this.editorNode = document.createElement('div');
116-
addClasses(this.editorNode, ["editor-box"])
117103
this.shadow.appendChild(this.wrapper);
118104
}
119105

@@ -140,11 +126,6 @@ export class PyScript extends HTMLElement {
140126
]
141127
})
142128

143-
this.editor = new EditorView({
144-
state: startState,
145-
parent: this.editorNode
146-
})
147-
148129
let mainDiv = document.createElement('div');
149130
addClasses(mainDiv, ["parentBox", "flex", "flex-col", "border-4", "border-dashed", "border-gray-200", "rounded-lg"])
150131
// add Editor to main PyScript div
@@ -190,18 +171,17 @@ export class PyScript extends HTMLElement {
190171
eDiv.appendChild(this.btnConfig);
191172

192173
mainDiv.appendChild(eDiv);
193-
mainDiv.appendChild(this.editorNode);
194174

195175
if (this.hasAttribute('target')) {
196-
this.editorOut = document.getElementById(this.getAttribute('target'));
176+
this.outputElement = document.getElementById(this.getAttribute('target'));
197177
}else{
198178
// Editor Output Div
199-
this.editorOut = document.createElement('div');
200-
this.editorOut.classList.add("output");
201-
this.editorOut.hidden = true;
179+
this.outputElement = document.createElement('div');
180+
this.outputElement.classList.add("output");
181+
this.outputElement.hidden = true;
202182

203183
// add the output div id there's not target
204-
mainDiv.appendChild(this.editorOut);
184+
mainDiv.appendChild(this.outputElement);
205185
}
206186

207187
if (currentMode=="edit"){
@@ -217,35 +197,6 @@ export class PyScript extends HTMLElement {
217197
}
218198
}
219199

220-
addToOutput(s: string) {
221-
this.editorOut.innerHTML = s;
222-
this.editorOut.hidden = false;
223-
}
224-
225-
async loadFromFile(s: string){
226-
let pyodide = await pyodideReadyPromise;
227-
let response = await fetch(s);
228-
this.code = await response.text();
229-
230-
await pyodide.runPythonAsync(this.code);
231-
await pyodide.runPythonAsync(`
232-
from pyodide.http import pyfetch
233-
from pyodide import eval_code
234-
response = await pyfetch("`+s+`")
235-
content = await response.bytes()
236-
237-
with open("todo.py", "wb") as f:
238-
print(content)
239-
f.write(content)
240-
print("done writing")
241-
`)
242-
// let pkg = pyodide.pyimport("todo");
243-
// pyodide.runPython(`
244-
// import todo
245-
// `)
246-
// pkg.do_something();
247-
}
248-
249200
protected async _register_esm(pyodide: PyodideInterface): Promise<void> {
250201
const imports: {[key: string]: unknown} = {}
251202

@@ -278,43 +229,8 @@ export class PyScript extends HTMLElement {
278229
pyodide.registerJsModule("esm", imports)
279230
}
280231

281-
async evaluate(): Promise<void> {
282-
console.log('evaluate');
283-
284-
if (this.source){
285-
this.loadFromFile(this.source)
286-
}else{
287-
const pyodide = await pyodideReadyPromise;
288-
await this._register_esm(pyodide)
289-
// debugger
290-
try {
291-
// @ts-ignore
292-
const source = htmlDecode(this.editor.state.doc.toString());
293-
let output;
294-
if (source.includes("asyncio")){
295-
output = await pyodide.runPythonAsync(source);
296-
}else{
297-
output = pyodide.runPython(source);
298-
}
299-
if (output !== undefined){
300-
this.addToOutput(output);
301-
}
302-
303-
if (this.hasAttribute('auto-generate') && this.parentElement.lastChild === this) {
304-
const newPyscript = document.createElement("py-script");
305-
newPyscript.setAttribute('auto-generate', null);
306-
this.parentElement.appendChild(newPyscript);
307-
}
308-
} catch (err) {
309-
this.addToOutput(err);
310-
console.log(err);
311-
}
312-
}
313-
}
314-
315-
render(){
316-
console.log('rendered');
317-
232+
getSourceFromElement(): string {
233+
return this.code;
318234
}
319235
}
320236

0 commit comments

Comments
 (0)
0