@pyscript/core 0.3.23 → 0.4.1
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/{codemirror-Maf5R0Dz.js → codemirror-7Z74h-SU.js} +2 -2
- package/dist/{codemirror-Maf5R0Dz.js.map → codemirror-7Z74h-SU.js.map} +1 -1
- package/dist/{codemirror_commands-bA0DvCyD.js → codemirror_commands-KteZ2xa6.js} +2 -2
- package/dist/{codemirror_commands-bA0DvCyD.js.map → codemirror_commands-KteZ2xa6.js.map} +1 -1
- package/dist/{codemirror_lang-python-FADyYnPB.js → codemirror_lang-python-Hxg36r9_.js} +2 -2
- package/dist/{codemirror_lang-python-FADyYnPB.js.map → codemirror_lang-python-Hxg36r9_.js.map} +1 -1
- package/dist/{codemirror_language-xy4t5bF6.js → codemirror_language-h7RmiDU2.js} +2 -2
- package/dist/{codemirror_language-xy4t5bF6.js.map → codemirror_language-h7RmiDU2.js.map} +1 -1
- package/dist/core-czqNvlPu.js +3 -0
- package/dist/core-czqNvlPu.js.map +1 -0
- package/dist/core.js +1 -1
- package/dist/{deprecations-manager-2rEkYgsn.js → deprecations-manager-Eol5DbEM.js} +2 -2
- package/dist/{deprecations-manager-2rEkYgsn.js.map → deprecations-manager-Eol5DbEM.js.map} +1 -1
- package/dist/{error-sz_Yjd9A.js → error-rou3ZMUs.js} +2 -2
- package/dist/{error-sz_Yjd9A.js.map → error-rou3ZMUs.js.map} +1 -1
- package/dist/{index-e6mx5aWM.js → index-AoMXVlyu.js} +2 -2
- package/dist/{index-e6mx5aWM.js.map → index-AoMXVlyu.js.map} +1 -1
- package/dist/{py-editor-1Il3Lcfv.js → py-editor-jp5-KhgB.js} +2 -2
- package/dist/{py-editor-1Il3Lcfv.js.map → py-editor-jp5-KhgB.js.map} +1 -1
- package/dist/{py-terminal-E5d6qafs.js → py-terminal-8Mwmha2x.js} +2 -2
- package/dist/{py-terminal-E5d6qafs.js.map → py-terminal-8Mwmha2x.js.map} +1 -1
- package/dist.zip +0 -0
- package/package.json +4 -4
- package/src/core.js +28 -21
- package/src/stdlib/pyscript/__init__.py +2 -0
- package/src/stdlib/pyscript/event_handling.py +31 -10
- package/src/stdlib/pyscript/magic_js.py +21 -4
- package/src/stdlib/pyscript.js +5 -4
- package/src/stdlib/pyweb/__init__.py +1 -0
- package/src/stdlib/pyweb/pydom.py +38 -14
- package/types/core.d.ts +22 -6
- package/types/stdlib/pyscript.d.ts +1 -0
- package/dist/core-78rkmWeI.js +0 -3
- package/dist/core-78rkmWeI.js.map +0 -1
@@ -1,2 +1,2 @@
|
|
1
|
-
import{T as e,d as t,X as r,H as n}from"./core-
|
2
|
-
//# sourceMappingURL=py-editor-
|
1
|
+
import{T as e,d as t,X as r,H as n}from"./core-czqNvlPu.js";let o=0;const s=e=>`${e}-editor-${o++}`,i=new Map,a={worker:{onReady:({runAsync:e,io:t},{sync:r})=>{t.stdout=e=>r.write(e),t.stderr=e=>r.writeErr(e),r.revoke(),r.runAsync=e}}};async function c({currentTarget:e}){const{env:t,pySrc:o,outDiv:s}=this;if(e.disabled=!0,s.innerHTML="",!i.has(t)){const e=URL.createObjectURL(new Blob([""])),o=r.call(new n(null,a),e,{type:this.interpreter}),{sync:s}=o,{promise:c,resolve:l}=Promise.withResolvers();i.set(t,c),s.revoke=()=>{URL.revokeObjectURL(e),l(o)}}i.get(t).then((t=>{t.onerror=({error:e})=>{s.innerHTML+=`<span style='color:red'>${e.message||e}</span>\n`,console.error(e)};const r=()=>{e.disabled=!1},{sync:n}=t;n.write=e=>{s.innerText+=`${e}\n`},n.writeErr=e=>{s.innerHTML+=`<span style='color:red'>${e}</span>\n`},n.runAsync(o).then(r,r)}))}const l=(e,t)=>{const r=document.createElement("div");r.className=`${t}-editor-input`,r.setAttribute("aria-label","Python Script Area");const n=((e,t)=>{const r=document.createElement("button");return r.className=`absolute ${t}-editor-run-button`,r.innerHTML='<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>',r.setAttribute("aria-label","Python Script Run Button"),r.addEventListener("click",e),r})(e,t),o=document.createElement("div");return o.addEventListener("keydown",(e=>{e.stopPropagation()})),r.append(n,o),r},d=(e,t)=>{const r=document.createElement("div");r.className=`${t}-editor-box`;const n=l(e,t),o=(e=>{const t=document.createElement("div");return t.className=`${e}-editor-output`,t.id=`${s(e)}-output`,t})(t);return r.append(n,o),[r,o]},u=async(e,r,n)=>{const[{basicSetup:o,EditorView:i},{Compartment:a},{python:l},{indentUnit:u},{keymap:m},{defaultKeymap:p}]=await Promise.all([import("./codemirror-7Z74h-SU.js"),import("./codemirror_state-W084kUeH.js"),import("./codemirror_lang-python-Hxg36r9_.js"),import("./codemirror_language-h7RmiDU2.js").then((function(e){return e.x})),import("./codemirror_view-8wK3J563.js").then((function(e){return e.q})),import("./codemirror_commands-KteZ2xa6.js")]),y=e.getAttribute("target");let v;if(y){if(v=document.getElementById(y)||document.querySelector(y),!v)throw new Error(`Unknown target ${y}`)}else v=document.createElement(`${r}-editor`),v.style.display="block",e.after(v);v.id||(v.id=s(r)),v.hasAttribute("exec-id")||v.setAttribute("exec-id",0),v.hasAttribute("root")||v.setAttribute("root",v.id);const f=`${n}-${e.getAttribute("env")||s(r)}`,g={interpreter:n,env:f,get pySrc(){return L.state.doc.toString()},get outDiv(){return w}},h=c.bind(g),[b,w]=d(h,r);b.dataset.env=e.hasAttribute("env")?f:n;const E=b.querySelector(`.${r}-editor-input > div`).attachShadow({mode:"open"});E.innerHTML="<style> :host { all: initial; }</style>",v.appendChild(b);const $=t(e.textContent).trim(),A=/^(\s+)/m.test($)?RegExp.$1:" ",L=new i({extensions:[u.of(A),(new a).of(l()),m.of([...p,{key:"Ctrl-Enter",run:h,preventDefault:!0},{key:"Cmd-Enter",run:h,preventDefault:!0},{key:"Shift-Enter",run:h,preventDefault:!0}]),o],parent:E,doc:$});L.focus()};let m=0,p=Promise.resolve();const y=()=>{m=0,v()},v=async()=>{if(!m){m=setTimeout(y,250);for(const[t,r]of e){const e=`script[type="${t}-editor"]`;for(const n of document.querySelectorAll(e))n.type+="-active",p=p.then((()=>u(n,t,r)))}return p}};new MutationObserver(v).observe(document,{childList:!0,subtree:!0});var f=v();export{f as default};
|
2
|
+
//# sourceMappingURL=py-editor-jp5-KhgB.js.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"py-editor-1Il3Lcfv.js","sources":["../src/plugins/py-editor.js"],"sourcesContent":["// PyScript py-editor plugin\nimport { Hook, XWorker, dedent } from \"polyscript/exports\";\nimport { TYPES } from \"../core.js\";\n\nconst 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>`;\n\nlet id = 0;\nconst getID = (type) => `${type}-editor-${id++}`;\n\nconst envs = new Map();\n\nconst hooks = {\n worker: {\n // works on both Pyodide and MicroPython\n onReady: ({ runAsync, io }, { sync }) => {\n io.stdout = (line) => sync.write(line);\n io.stderr = (line) => sync.writeErr(line);\n sync.revoke();\n sync.runAsync = runAsync;\n },\n },\n};\n\nasync function execute({ currentTarget }) {\n const { env, pySrc, outDiv } = this;\n\n currentTarget.disabled = true;\n outDiv.innerHTML = \"\";\n\n if (!envs.has(env)) {\n const srcLink = URL.createObjectURL(new Blob([\"\"]));\n const xworker = XWorker.call(new Hook(null, hooks), srcLink, {\n type: this.interpreter,\n });\n\n const { sync } = xworker;\n const { promise, resolve } = Promise.withResolvers();\n envs.set(env, promise);\n sync.revoke = () => {\n URL.revokeObjectURL(srcLink);\n resolve(xworker);\n };\n }\n\n // wait for the env then set the target div\n // before executing the current code\n envs.get(env).then((xworker) => {\n xworker.onerror = ({ error }) => {\n outDiv.innerHTML += `<span style='color:red'>${\n error.message || error\n }</span>\\n`;\n console.error(error);\n };\n\n const enable = () => {\n currentTarget.disabled = false;\n };\n const { sync } = xworker;\n sync.write = (str) => {\n outDiv.innerText += `${str}\\n`;\n };\n sync.writeErr = (str) => {\n outDiv.innerHTML += `<span style='color:red'>${str}</span>\\n`;\n };\n sync.runAsync(pySrc).then(enable, enable);\n });\n}\n\nconst makeRunButton = (listener, type) => {\n const runButton = document.createElement(\"button\");\n runButton.className = `absolute ${type}-editor-run-button`;\n runButton.innerHTML = RUN_BUTTON;\n runButton.setAttribute(\"aria-label\", \"Python Script Run Button\");\n runButton.addEventListener(\"click\", listener);\n return runButton;\n};\n\nconst makeEditorDiv = (listener, type) => {\n const editorDiv = document.createElement(\"div\");\n editorDiv.className = `${type}-editor-input`;\n editorDiv.setAttribute(\"aria-label\", \"Python Script Area\");\n\n const runButton = makeRunButton(listener, type);\n const editorShadowContainer = document.createElement(\"div\");\n\n // avoid outer elements intercepting key events (reveal as example)\n editorShadowContainer.addEventListener(\"keydown\", (event) => {\n event.stopPropagation();\n });\n\n editorDiv.append(runButton, editorShadowContainer);\n\n return editorDiv;\n};\n\nconst makeOutDiv = (type) => {\n const outDiv = document.createElement(\"div\");\n outDiv.className = `${type}-editor-output`;\n outDiv.id = `${getID(type)}-output`;\n return outDiv;\n};\n\nconst makeBoxDiv = (listener, type) => {\n const boxDiv = document.createElement(\"div\");\n boxDiv.className = `${type}-editor-box`;\n\n const editorDiv = makeEditorDiv(listener, type);\n const outDiv = makeOutDiv(type);\n boxDiv.append(editorDiv, outDiv);\n\n return [boxDiv, outDiv];\n};\n\nconst init = async (script, type, interpreter) => {\n const [\n { basicSetup, EditorView },\n { Compartment },\n { python },\n { indentUnit },\n { keymap },\n { defaultKeymap },\n ] = await Promise.all([\n // TODO: find a way to actually produce these bundles locally\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_state.js\"),\n import(\n /* webpackIgnore: true */ \"../3rd-party/codemirror_lang-python.js\"\n ),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_language.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_view.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_commands.js\"),\n ]);\n\n const selector = script.getAttribute(\"target\");\n\n let target;\n if (selector) {\n target =\n document.getElementById(selector) ||\n document.querySelector(selector);\n if (!target) throw new Error(`Unknown target ${selector}`);\n } else {\n target = document.createElement(`${type}-editor`);\n target.style.display = \"block\";\n script.after(target);\n }\n\n if (!target.id) target.id = getID(type);\n if (!target.hasAttribute(\"exec-id\")) target.setAttribute(\"exec-id\", 0);\n if (!target.hasAttribute(\"root\")) target.setAttribute(\"root\", target.id);\n\n const env = `${interpreter}-${script.getAttribute(\"env\") || getID(type)}`;\n const context = {\n interpreter,\n env,\n get pySrc() {\n return editor.state.doc.toString();\n },\n get outDiv() {\n return outDiv;\n },\n };\n\n // @see https://github.com/JeffersGlass/mkdocs-pyscript/blob/main/mkdocs_pyscript/js/makeblocks.js\n const listener = execute.bind(context);\n const [boxDiv, outDiv] = makeBoxDiv(listener, type);\n boxDiv.dataset.env = script.hasAttribute(\"env\") ? env : interpreter;\n\n const inputChild = boxDiv.querySelector(`.${type}-editor-input > div`);\n const parent = inputChild.attachShadow({ mode: \"open\" });\n // avoid inheriting styles from the outer component\n parent.innerHTML = `<style> :host { all: initial; }</style>`;\n\n target.appendChild(boxDiv);\n\n const doc = dedent(script.textContent).trim();\n\n // preserve user indentation, if any\n const indentation = /^(\\s+)/m.test(doc) ? RegExp.$1 : \" \";\n\n const editor = new EditorView({\n extensions: [\n indentUnit.of(indentation),\n new Compartment().of(python()),\n keymap.of([\n ...defaultKeymap,\n { key: \"Ctrl-Enter\", run: listener, preventDefault: true },\n { key: \"Cmd-Enter\", run: listener, preventDefault: true },\n { key: \"Shift-Enter\", run: listener, preventDefault: true },\n ]),\n basicSetup,\n ],\n parent,\n doc,\n });\n\n editor.focus();\n};\n\n// avoid too greedy MutationObserver operations at distance\nlet timeout = 0;\n\n// avoid delayed initialization\nlet queue = Promise.resolve();\n\n// reset interval value then check for new scripts\nconst resetTimeout = () => {\n timeout = 0;\n pyEditor();\n};\n\n// triggered both ASAP on the living DOM and via MutationObserver later\nconst pyEditor = async () => {\n if (timeout) return;\n timeout = setTimeout(resetTimeout, 250);\n for (const [type, interpreter] of TYPES) {\n const selector = `script[type=\"${type}-editor\"]`;\n for (const script of document.querySelectorAll(selector)) {\n // avoid any further bootstrap by changing the type as active\n script.type += \"-active\";\n // don't await in here or multiple calls might happen\n // while the first script is being initialized\n queue = queue.then(() => init(script, type, interpreter));\n }\n }\n return queue;\n};\n\nnew MutationObserver(pyEditor).observe(document, {\n childList: true,\n subtree: true,\n});\n\n// try to check the current document ASAP\nexport default pyEditor();\n"],"names":["id","getID","type","envs","Map","hooks","worker","onReady","runAsync","io","sync","stdout","line","write","stderr","writeErr","revoke","async","execute","currentTarget","env","pySrc","outDiv","this","disabled","innerHTML","has","srcLink","URL","createObjectURL","Blob","xworker","XWorker","call","Hook","interpreter","promise","resolve","Promise","withResolvers","set","revokeObjectURL","get","then","onerror","error","message","console","enable","str","innerText","makeEditorDiv","listener","editorDiv","document","createElement","className","setAttribute","runButton","addEventListener","makeRunButton","editorShadowContainer","event","stopPropagation","append","makeBoxDiv","boxDiv","makeOutDiv","init","script","basicSetup","EditorView","Compartment","python","indentUnit","keymap","defaultKeymap","all","import","n","x","q","selector","getAttribute","target","getElementById","querySelector","Error","style","display","after","hasAttribute","context","editor","state","doc","toString","bind","dataset","parent","attachShadow","mode","appendChild","dedent","textContent","trim","indentation","test","RegExp","$1","extensions","of","key","run","preventDefault","focus","timeout","queue","resetTimeout","pyEditor","setTimeout","TYPES","querySelectorAll","MutationObserver","observe","childList","subtree","pyEditor$1"],"mappings":"4DAMA,IAAIA,EAAK,EACT,MAAMC,EAASC,GAAS,GAAGA,YAAeF,MAEpCG,EAAO,IAAIC,IAEXC,EAAQ,CACVC,OAAQ,CAEJC,QAAS,EAAGC,WAAUC,OAAQC,WAC1BD,EAAGE,OAAUC,GAASF,EAAKG,MAAMD,GACjCH,EAAGK,OAAUF,GAASF,EAAKK,SAASH,GACpCF,EAAKM,SACLN,EAAKF,SAAWA,CAAQ,IAKpCS,eAAeC,GAAQC,cAAEA,IACrB,MAAMC,IAAEA,EAAGC,MAAEA,EAAKC,OAAEA,GAAWC,KAK/B,GAHAJ,EAAcK,UAAW,EACzBF,EAAOG,UAAY,IAEdtB,EAAKuB,IAAIN,GAAM,CAChB,MAAMO,EAAUC,IAAIC,gBAAgB,IAAIC,KAAK,CAAC,MACxCC,EAAUC,EAAQC,KAAK,IAAIC,EAAK,KAAM7B,GAAQsB,EAAS,CACzDzB,KAAMqB,KAAKY,eAGTzB,KAAEA,GAASqB,GACXK,QAAEA,EAAOC,QAAEA,GAAYC,QAAQC,gBACrCpC,EAAKqC,IAAIpB,EAAKgB,GACd1B,EAAKM,OAAS,KACVY,IAAIa,gBAAgBd,GACpBU,EAAQN,EAAQ,CAEvB,CAID5B,EAAKuC,IAAItB,GAAKuB,MAAMZ,IAChBA,EAAQa,QAAU,EAAGC,YACjBvB,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GAAK,OAEhDhB,EAAS,IAAItB,EAAW,CAC1BuC,WAAY,CACRpC,EAAWqC,GAAGL,IACd,IAAIlC,GAAcuC,GAAGtC,KACrBE,EAAOoC,GAAG,IACHnC,EACH,CAAEoC,IAAK,aAAcC,IAAK7D,EAAU8D,gBAAgB,GACpD,CAAEF,IAAK,YAAaC,IAAK7D,EAAU8D,gBAAgB,GACnD,CAAEF,IAAK,cAAeC,IAAK7D,EAAU8D,gBAAgB,KAEzD5C,GAEJ6B,SACAJ,QAGJF,EAAOsB,OAAO,EAIlB,IAAIC,EAAU,EAGVC,EAAQ/E,QAAQD,UAGpB,MAAMiF,EAAe,KACjBF,EAAU,EACVG,GAAU,EAIRA,EAAWtG,UACb,IAAImG,EAAJ,CACAA,EAAUI,WAAWF,EAAc,KACnC,IAAK,MAAOpH,EAAMiC,KAAgBsF,EAAO,CACrC,MAAMvC,EAAW,gBAAgBhF,aACjC,IAAK,MAAMmE,KAAUf,SAASoE,iBAAiBxC,GAE3Cb,EAAOnE,MAAQ,UAGfmH,EAAQA,EAAM1E,MAAK,IAAMyB,EAAKC,EAAQnE,EAAMiC,IAEnD,CACD,OAAOkF,CAZa,CAYR,EAGhB,IAAIM,iBAAiBJ,GAAUK,QAAQtE,SAAU,CAC7CuE,WAAW,EACXC,SAAS,IAIb,IAAAC,EAAeR"}
|
1
|
+
{"version":3,"file":"py-editor-jp5-KhgB.js","sources":["../src/plugins/py-editor.js"],"sourcesContent":["// PyScript py-editor plugin\nimport { Hook, XWorker, dedent } from \"polyscript/exports\";\nimport { TYPES } from \"../core.js\";\n\nconst 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>`;\n\nlet id = 0;\nconst getID = (type) => `${type}-editor-${id++}`;\n\nconst envs = new Map();\n\nconst hooks = {\n worker: {\n // works on both Pyodide and MicroPython\n onReady: ({ runAsync, io }, { sync }) => {\n io.stdout = (line) => sync.write(line);\n io.stderr = (line) => sync.writeErr(line);\n sync.revoke();\n sync.runAsync = runAsync;\n },\n },\n};\n\nasync function execute({ currentTarget }) {\n const { env, pySrc, outDiv } = this;\n\n currentTarget.disabled = true;\n outDiv.innerHTML = \"\";\n\n if (!envs.has(env)) {\n const srcLink = URL.createObjectURL(new Blob([\"\"]));\n const xworker = XWorker.call(new Hook(null, hooks), srcLink, {\n type: this.interpreter,\n });\n\n const { sync } = xworker;\n const { promise, resolve } = Promise.withResolvers();\n envs.set(env, promise);\n sync.revoke = () => {\n URL.revokeObjectURL(srcLink);\n resolve(xworker);\n };\n }\n\n // wait for the env then set the target div\n // before executing the current code\n envs.get(env).then((xworker) => {\n xworker.onerror = ({ error }) => {\n outDiv.innerHTML += `<span style='color:red'>${\n error.message || error\n }</span>\\n`;\n console.error(error);\n };\n\n const enable = () => {\n currentTarget.disabled = false;\n };\n const { sync } = xworker;\n sync.write = (str) => {\n outDiv.innerText += `${str}\\n`;\n };\n sync.writeErr = (str) => {\n outDiv.innerHTML += `<span style='color:red'>${str}</span>\\n`;\n };\n sync.runAsync(pySrc).then(enable, enable);\n });\n}\n\nconst makeRunButton = (listener, type) => {\n const runButton = document.createElement(\"button\");\n runButton.className = `absolute ${type}-editor-run-button`;\n runButton.innerHTML = RUN_BUTTON;\n runButton.setAttribute(\"aria-label\", \"Python Script Run Button\");\n runButton.addEventListener(\"click\", listener);\n return runButton;\n};\n\nconst makeEditorDiv = (listener, type) => {\n const editorDiv = document.createElement(\"div\");\n editorDiv.className = `${type}-editor-input`;\n editorDiv.setAttribute(\"aria-label\", \"Python Script Area\");\n\n const runButton = makeRunButton(listener, type);\n const editorShadowContainer = document.createElement(\"div\");\n\n // avoid outer elements intercepting key events (reveal as example)\n editorShadowContainer.addEventListener(\"keydown\", (event) => {\n event.stopPropagation();\n });\n\n editorDiv.append(runButton, editorShadowContainer);\n\n return editorDiv;\n};\n\nconst makeOutDiv = (type) => {\n const outDiv = document.createElement(\"div\");\n outDiv.className = `${type}-editor-output`;\n outDiv.id = `${getID(type)}-output`;\n return outDiv;\n};\n\nconst makeBoxDiv = (listener, type) => {\n const boxDiv = document.createElement(\"div\");\n boxDiv.className = `${type}-editor-box`;\n\n const editorDiv = makeEditorDiv(listener, type);\n const outDiv = makeOutDiv(type);\n boxDiv.append(editorDiv, outDiv);\n\n return [boxDiv, outDiv];\n};\n\nconst init = async (script, type, interpreter) => {\n const [\n { basicSetup, EditorView },\n { Compartment },\n { python },\n { indentUnit },\n { keymap },\n { defaultKeymap },\n ] = await Promise.all([\n // TODO: find a way to actually produce these bundles locally\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_state.js\"),\n import(\n /* webpackIgnore: true */ \"../3rd-party/codemirror_lang-python.js\"\n ),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_language.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_view.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/codemirror_commands.js\"),\n ]);\n\n const selector = script.getAttribute(\"target\");\n\n let target;\n if (selector) {\n target =\n document.getElementById(selector) ||\n document.querySelector(selector);\n if (!target) throw new Error(`Unknown target ${selector}`);\n } else {\n target = document.createElement(`${type}-editor`);\n target.style.display = \"block\";\n script.after(target);\n }\n\n if (!target.id) target.id = getID(type);\n if (!target.hasAttribute(\"exec-id\")) target.setAttribute(\"exec-id\", 0);\n if (!target.hasAttribute(\"root\")) target.setAttribute(\"root\", target.id);\n\n const env = `${interpreter}-${script.getAttribute(\"env\") || getID(type)}`;\n const context = {\n interpreter,\n env,\n get pySrc() {\n return editor.state.doc.toString();\n },\n get outDiv() {\n return outDiv;\n },\n };\n\n // @see https://github.com/JeffersGlass/mkdocs-pyscript/blob/main/mkdocs_pyscript/js/makeblocks.js\n const listener = execute.bind(context);\n const [boxDiv, outDiv] = makeBoxDiv(listener, type);\n boxDiv.dataset.env = script.hasAttribute(\"env\") ? env : interpreter;\n\n const inputChild = boxDiv.querySelector(`.${type}-editor-input > div`);\n const parent = inputChild.attachShadow({ mode: \"open\" });\n // avoid inheriting styles from the outer component\n parent.innerHTML = `<style> :host { all: initial; }</style>`;\n\n target.appendChild(boxDiv);\n\n const doc = dedent(script.textContent).trim();\n\n // preserve user indentation, if any\n const indentation = /^(\\s+)/m.test(doc) ? RegExp.$1 : \" \";\n\n const editor = new EditorView({\n extensions: [\n indentUnit.of(indentation),\n new Compartment().of(python()),\n keymap.of([\n ...defaultKeymap,\n { key: \"Ctrl-Enter\", run: listener, preventDefault: true },\n { key: \"Cmd-Enter\", run: listener, preventDefault: true },\n { key: \"Shift-Enter\", run: listener, preventDefault: true },\n ]),\n basicSetup,\n ],\n parent,\n doc,\n });\n\n editor.focus();\n};\n\n// avoid too greedy MutationObserver operations at distance\nlet timeout = 0;\n\n// avoid delayed initialization\nlet queue = Promise.resolve();\n\n// reset interval value then check for new scripts\nconst resetTimeout = () => {\n timeout = 0;\n pyEditor();\n};\n\n// triggered both ASAP on the living DOM and via MutationObserver later\nconst pyEditor = async () => {\n if (timeout) return;\n timeout = setTimeout(resetTimeout, 250);\n for (const [type, interpreter] of TYPES) {\n const selector = `script[type=\"${type}-editor\"]`;\n for (const script of document.querySelectorAll(selector)) {\n // avoid any further bootstrap by changing the type as active\n script.type += \"-active\";\n // don't await in here or multiple calls might happen\n // while the first script is being initialized\n queue = queue.then(() => init(script, type, interpreter));\n }\n }\n return queue;\n};\n\nnew MutationObserver(pyEditor).observe(document, {\n childList: true,\n subtree: true,\n});\n\n// try to check the current document ASAP\nexport default pyEditor();\n"],"names":["id","getID","type","envs","Map","hooks","worker","onReady","runAsync","io","sync","stdout","line","write","stderr","writeErr","revoke","async","execute","currentTarget","env","pySrc","outDiv","this","disabled","innerHTML","has","srcLink","URL","createObjectURL","Blob","xworker","XWorker","call","Hook","interpreter","promise","resolve","Promise","withResolvers","set","revokeObjectURL","get","then","onerror","error","message","console","enable","str","innerText","makeEditorDiv","listener","editorDiv","document","createElement","className","setAttribute","runButton","addEventListener","makeRunButton","editorShadowContainer","event","stopPropagation","append","makeBoxDiv","boxDiv","makeOutDiv","init","script","basicSetup","EditorView","Compartment","python","indentUnit","keymap","defaultKeymap","all","import","n","x","q","selector","getAttribute","target","getElementById","querySelector","Error","style","display","after","hasAttribute","context","editor","state","doc","toString","bind","dataset","parent","attachShadow","mode","appendChild","dedent","textContent","trim","indentation","test","RegExp","$1","extensions","of","key","run","preventDefault","focus","timeout","queue","resetTimeout","pyEditor","setTimeout","TYPES","querySelectorAll","MutationObserver","observe","childList","subtree","pyEditor$1"],"mappings":"4DAMA,IAAIA,EAAK,EACT,MAAMC,EAASC,GAAS,GAAGA,YAAeF,MAEpCG,EAAO,IAAIC,IAEXC,EAAQ,CACVC,OAAQ,CAEJC,QAAS,EAAGC,WAAUC,OAAQC,WAC1BD,EAAGE,OAAUC,GAASF,EAAKG,MAAMD,GACjCH,EAAGK,OAAUF,GAASF,EAAKK,SAASH,GACpCF,EAAKM,SACLN,EAAKF,SAAWA,CAAQ,IAKpCS,eAAeC,GAAQC,cAAEA,IACrB,MAAMC,IAAEA,EAAGC,MAAEA,EAAKC,OAAEA,GAAWC,KAK/B,GAHAJ,EAAcK,UAAW,EACzBF,EAAOG,UAAY,IAEdtB,EAAKuB,IAAIN,GAAM,CAChB,MAAMO,EAAUC,IAAIC,gBAAgB,IAAIC,KAAK,CAAC,MACxCC,EAAUC,EAAQC,KAAK,IAAIC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as e,e as t,a as r}from"./core-czqNvlPu.js";import{notify as n}from"./error-rou3ZMUs.js";const i=[...e.keys()].map((e=>`script[type="${e}"][terminal],${e}-script[terminal]`)).join(","),a=e=>{throw n(e),new Error(e)},o=e=>!l.has(e),s=({attributes:{worker:e}})=>!e,l=new WeakSet;let d=!0;const m=({interpreter:e,io:t,run:r},{sync:n})=>{if(!n.is_pyterminal())return;r("from polyscript.currentScript import terminal as __terminal__");const i=new TextDecoder;let a="";const o={isatty:!0,write:e=>(a=i.decode(e),n.pyterminal_write(a),e.length)};e.setStdout(o),e.setStderr(o),e.setStdin({isatty:!0,stdin:()=>n.pyterminal_read(a)}),t.stderr=e=>{n.pyterminal_write(`${e.message||e}\n`)}},c=async()=>{const e=document.querySelectorAll(i),n=[].filter.call(e,o);if(!n.length)return;n.forEach(l.add,l),[].filter.call(e,s).length>1&&a("You can use at most 1 main terminal"),d&&(d=!1,document.head.append(Object.assign(document.createElement("link"),{rel:"stylesheet",href:new URL("./xterm.css",import.meta.url)})));const[{Terminal:c},{Readline:p},{FitAddon:y}]=await Promise.all([import("./xterm-f2QfYNGL.js"),import("./xterm-readline-ONk85xtH.js"),import("./xterm_addon-fit-E4yMPZTX.js")]);for(const e of n){e.matches('script[type="mpy"],mpy-script')&&a("Unsupported terminal.");const n=new p,i=t=>{let i=e;const a=e.getAttribute("target");if(a){if(i=document.getElementById(a)||document.querySelector(a),!i)throw new Error(`Unknown target ${a}`)}else i=document.createElement("py-terminal"),i.style.display="block",e.after(i);const o=new c({theme:{background:"#191A19",foreground:"#F5F2E7"},...t}),s=new y;return o.loadAddon(s),o.loadAddon(n),o.open(i),s.fit(),o.focus(),r(e,"terminal",{value:o}),o};e.hasAttribute("worker")?(t.main.onWorker.add((function e(r,a){l.has(a)||(l.add(a),t.main.onWorker.delete(e),i({disableStdin:!1,cursorBlink:!0,cursorStyle:"block"}),a.sync.is_pyterminal=()=>!0,a.sync.pyterminal_read=n.read.bind(n),a.sync.pyterminal_write=n.write.bind(n))})),t.worker.onReady.add(m)):t.main.onReady.add((function e({interpreter:r,io:a,run:o}){console.warn("py-terminal is read only on main thread"),t.main.onReady.delete(e),globalThis.__py_terminal__=i({disableStdin:!0,cursorBlink:!1,cursorStyle:"underline"}),o("from js import __py_terminal__ as __terminal__"),delete globalThis.__py_terminal__;const s=new TextDecoder;let l="";const d={isatty:!0,write:e=>(l=s.decode(e),n.write(l),e.length)};r.setStdout(d),r.setStderr(d),r.setStdin({isatty:!0,stdin:()=>n.read(l)}),a.stderr=e=>{n.write(`${e.message||e}\n`)}}))}};new MutationObserver(c).observe(document,{childList:!0,subtree:!0});var p=c();export{p as default};
|
2
|
+
//# sourceMappingURL=py-terminal-8Mwmha2x.js.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"py-terminal-E5d6qafs.js","sources":["../src/plugins/py-terminal.js"],"sourcesContent":["// PyScript py-terminal plugin\nimport { TYPES, hooks } from \"../core.js\";\nimport { notify } from \"./error.js\";\nimport { defineProperty } from \"polyscript/exports\";\n\nconst SELECTOR = [...TYPES.keys()]\n .map((type) => `script[type=\"${type}\"][terminal],${type}-script[terminal]`)\n .join(\",\");\n\n// show the error on main and\n// stops the module from keep executing\nconst notifyAndThrow = (message) => {\n notify(message);\n throw new Error(message);\n};\n\nconst notParsedYet = (script) => !bootstrapped.has(script);\n\nconst onceOnMain = ({ attributes: { worker } }) => !worker;\n\nconst bootstrapped = new WeakSet();\n\nlet addStyle = true;\n\n// this callback will be serialized as string and it never needs\n// to be invoked multiple times. Each xworker here is bootstrapped\n// only once thanks to the `sync.is_pyterminal()` check.\nconst workerReady = ({ interpreter, io, run }, { sync }) => {\n if (!sync.is_pyterminal()) return;\n\n // in workers it's always safe to grab the polyscript currentScript\n run(\"from polyscript.currentScript import terminal as __terminal__\");\n\n // This part is inevitably duplicated as external scope\n // can't be reached by workers out of the box.\n // The detail is that here we use sync though, not readline.\n const decoder = new TextDecoder();\n let data = \"\";\n const generic = {\n isatty: true,\n write(buffer) {\n data = decoder.decode(buffer);\n sync.pyterminal_write(data);\n return buffer.length;\n },\n };\n interpreter.setStdout(generic);\n interpreter.setStderr(generic);\n interpreter.setStdin({\n isatty: true,\n stdin: () => sync.pyterminal_read(data),\n });\n\n io.stderr = (error) => {\n sync.pyterminal_write(`${error.message || error}\\n`);\n };\n};\n\nconst pyTerminal = async () => {\n const terminals = document.querySelectorAll(SELECTOR);\n\n const unknown = [].filter.call(terminals, notParsedYet);\n\n // no results will look further for runtime nodes\n if (!unknown.length) return;\n // early flag elements as known to avoid concurrent\n // MutationObserver invokes of this async handler\n else unknown.forEach(bootstrapped.add, bootstrapped);\n\n // we currently support only one terminal as in \"classic\"\n if ([].filter.call(terminals, onceOnMain).length > 1)\n notifyAndThrow(\"You can use at most 1 main terminal\");\n\n // import styles lazily\n if (addStyle) {\n addStyle = false;\n document.head.append(\n Object.assign(document.createElement(\"link\"), {\n rel: \"stylesheet\",\n href: new URL(\"./xterm.css\", import.meta.url),\n }),\n );\n }\n\n // lazy load these only when a valid terminal is found\n const [{ Terminal }, { Readline }, { FitAddon }] = await Promise.all([\n import(/* webpackIgnore: true */ \"../3rd-party/xterm.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/xterm-readline.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/xterm_addon-fit.js\"),\n ]);\n\n for (const element of unknown) {\n // hopefully to be removed in the near future!\n if (element.matches('script[type=\"mpy\"],mpy-script'))\n notifyAndThrow(\"Unsupported terminal.\");\n\n const readline = new Readline();\n\n // common main thread initialization for both worker\n // or main case, bootstrapping the terminal on its target\n const init = (options) => {\n let target = element;\n const selector = element.getAttribute(\"target\");\n if (selector) {\n target =\n document.getElementById(selector) ||\n document.querySelector(selector);\n if (!target) throw new Error(`Unknown target ${selector}`);\n } else {\n target = document.createElement(\"py-terminal\");\n target.style.display = \"block\";\n element.after(target);\n }\n const terminal = new Terminal({\n theme: {\n background: \"#191A19\",\n foreground: \"#F5F2E7\",\n },\n ...options,\n });\n const fitAddon = new FitAddon();\n terminal.loadAddon(fitAddon);\n terminal.loadAddon(readline);\n terminal.open(target);\n fitAddon.fit();\n terminal.focus();\n defineProperty(element, \"terminal\", { value: terminal });\n return terminal;\n };\n\n // branch logic for the worker\n if (element.hasAttribute(\"worker\")) {\n // add a hook on the main thread to setup all sync helpers\n // also bootstrapping the XTerm target on main *BUT* ...\n hooks.main.onWorker.add(function worker(_, xworker) {\n // ... as multiple workers will add multiple callbacks\n // be sure no xworker is ever initialized twice!\n if (bootstrapped.has(xworker)) return;\n bootstrapped.add(xworker);\n\n // still cleanup this callback for future scripts/workers\n hooks.main.onWorker.delete(worker);\n\n init({\n disableStdin: false,\n cursorBlink: true,\n cursorStyle: \"block\",\n });\n\n xworker.sync.is_pyterminal = () => true;\n xworker.sync.pyterminal_read = readline.read.bind(readline);\n xworker.sync.pyterminal_write = readline.write.bind(readline);\n });\n\n // setup remote thread JS/Python code for whenever the\n // worker is ready to become a terminal\n hooks.worker.onReady.add(workerReady);\n } else {\n // in the main case, just bootstrap XTerm without\n // allowing any input as that's not possible / awkward\n hooks.main.onReady.add(function main({ interpreter, io, run }) {\n console.warn(\"py-terminal is read only on main thread\");\n hooks.main.onReady.delete(main);\n\n // on main, it's easy to trash and clean the current terminal\n globalThis.__py_terminal__ = init({\n disableStdin: true,\n cursorBlink: false,\n cursorStyle: \"underline\",\n });\n run(\"from js import __py_terminal__ as __terminal__\");\n delete globalThis.__py_terminal__;\n\n // This part is inevitably duplicated as external scope\n // can't be reached by workers out of the box.\n // The detail is that here we use readline here, not sync.\n const decoder = new TextDecoder();\n let data = \"\";\n const generic = {\n isatty: true,\n write(buffer) {\n data = decoder.decode(buffer);\n readline.write(data);\n return buffer.length;\n },\n };\n interpreter.setStdout(generic);\n interpreter.setStderr(generic);\n interpreter.setStdin({\n isatty: true,\n stdin: () => readline.read(data),\n });\n\n io.stderr = (error) => {\n readline.write(`${error.message || error}\\n`);\n };\n });\n }\n }\n};\n\nconst mo = new MutationObserver(pyTerminal);\nmo.observe(document, { childList: true, subtree: true });\n\n// try to check the current document ASAP\nexport default pyTerminal();\n"],"names":["SELECTOR","TYPES","keys","map","type","join","notifyAndThrow","message","notify","Error","notParsedYet","script","bootstrapped","has","onceOnMain","attributes","worker","WeakSet","addStyle","workerReady","interpreter","io","run","sync","is_pyterminal","decoder","TextDecoder","data","generic","isatty","write","buffer","decode","pyterminal_write","length","setStdout","setStderr","setStdin","stdin","pyterminal_read","stderr","error","pyTerminal","async","terminals","document","querySelectorAll","unknown","filter","call","forEach","add","head","append","Object","assign","createElement","rel","href","URL","url","Terminal","Readline","FitAddon","Promise","all","import","element","matches","readline","init","options","target","selector","getAttribute","getElementById","querySelector","style","display","after","terminal","theme","background","foreground","fitAddon","loadAddon","open","fit","focus","defineProperty","value","hasAttribute","hooks","main","onWorker","_","xworker","delete","disableStdin","cursorBlink","cursorStyle","read","bind","onReady","console","warn","globalThis","__py_terminal__","MutationObserver","observe","childList","subtree","pyTerminal$1"],"mappings":"kGAKA,MAAMA,EAAW,IAAIC,EAAMC,QACtBC,KAAKC,GAAS,gBAAgBA,iBAAoBA,uBAClDC,KAAK,KAIJC,EAAkBC,IAEpB,MADAC,EAAOD,GACD,IAAIE,MAAMF,EAAQ,EAGtBG,EAAgBC,IAAYC,EAAaC,IAAIF,GAE7CG,EAAa,EAAGC,YAAcC,cAAgBA,EAE9CJ,EAAe,IAAIK,QAEzB,IAAIC,GAAW,EAKf,MAAMC,EAAc,EAAGC,cAAaC,KAAIC,QAASC,WAC7C,IAAKA,EAAKC,gBAAiB,OAG3BF,EAAI,iEAKJ,MAAMG,EAAU,IAAIC,YACpB,IAAIC,EAAO,GACX,MAAMC,EAAU,CACZC,QAAQ,EACRC,MAAMC,IACFJ,EAAOF,EAAQO,OAAOD,GACtBR,EAAKU,iBAAiBN,GACfI,EAAOG,SAGtBd,EAAYe,UAAUP,GACtBR,EAAYgB,UAAUR,GACtBR,EAAYiB,SAAS,CACjBR,QAAQ,EACRS,MAAO,IAA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a,WAGrBC,EAAMC,KAAKC,SAAS3C,KAAI,SAASnC,EAAO+E,EAAGC,GAGnCpF,EAAaC,IAAImF,KACrBpF,EAAauC,IAAI6C,GAGjBJ,EAAMC,KAAKC,SAASG,OAAOjF,GAE3BsD,EAAK,CACD4B,cAAc,EACdC,aAAa,EACbC,YAAa,UAGjBJ,EAAQzE,KAAKC,cAAgB,KAAM,EACnCwE,EAAQzE,KAAKgB,gBAAkB8B,EAASgC,KAAKC,KAAKjC,GAClD2B,EAAQzE,KAAKU,iBAAmBoC,EAASvC,MAAMwE,KAAKjC,GACpE,IAIYuB,EAAM5E,OAAOuF,QAAQpD,IAAIhC,IAIzByE,EAAMC,KAAKU,QAAQpD,KAAI,SAAS0C,GAAKzE,YAAEA,EAAWC,GAAEA,EAAEC,IAAEA,IACpDkF,QAAQC,KAAK,2CACbb,EAAMC,KAAKU,QAAQN,OAAOJ,GAG1Ba,WAAWC,gBAAkBrC,EAAK,CAC9B4B,cAAc,EACdC,aAAa,EACbC,YAAa,cAEjB9E,EAAI,yDACGoF,WAAWC,gBAKlB,MAAMlF,EAAU,IAAIC,YACpB,IAAIC,EAAO,GACX,MAAMC,EAAU,CACZC,QAAQ,EACRC,MAAMC,IACFJ,EAAOF,EAAQO,OAAOD,GACtBsC,EAASvC,MAAMH,GACRI,EAAOG,SAGtBd,EAAYe,UAAUP,GACtBR,EAAYgB,UAAUR,GACtBR,EAAYiB,SAAS,CACjBR,QAAQ,EACRS,MAAO,IAAM+B,EAASgC,KAAK1E,KAG/BN,EAAGmB,OAAUC,IACT4B,EAASvC,MAAM,GAAGW,EAAMlC,SAAWkC,MAAU,CAEjE,GAEK,GAGM,IAAImE,iBAAiBlE,GAC7BmE,QAAQhE,SAAU,CAAEiE,WAAW,EAAMC,SAAS,IAGjD,IAAAC,EAAetE"}
|
1
|
+
{"version":3,"file":"py-terminal-8Mwmha2x.js","sources":["../src/plugins/py-terminal.js"],"sourcesContent":["// PyScript py-terminal plugin\nimport { TYPES, hooks } from \"../core.js\";\nimport { notify } from \"./error.js\";\nimport { defineProperty } from \"polyscript/exports\";\n\nconst SELECTOR = [...TYPES.keys()]\n .map((type) => `script[type=\"${type}\"][terminal],${type}-script[terminal]`)\n .join(\",\");\n\n// show the error on main and\n// stops the module from keep executing\nconst notifyAndThrow = (message) => {\n notify(message);\n throw new Error(message);\n};\n\nconst notParsedYet = (script) => !bootstrapped.has(script);\n\nconst onceOnMain = ({ attributes: { worker } }) => !worker;\n\nconst bootstrapped = new WeakSet();\n\nlet addStyle = true;\n\n// this callback will be serialized as string and it never needs\n// to be invoked multiple times. Each xworker here is bootstrapped\n// only once thanks to the `sync.is_pyterminal()` check.\nconst workerReady = ({ interpreter, io, run }, { sync }) => {\n if (!sync.is_pyterminal()) return;\n\n // in workers it's always safe to grab the polyscript currentScript\n run(\"from polyscript.currentScript import terminal as __terminal__\");\n\n // This part is inevitably duplicated as external scope\n // can't be reached by workers out of the box.\n // The detail is that here we use sync though, not readline.\n const decoder = new TextDecoder();\n let data = \"\";\n const generic = {\n isatty: true,\n write(buffer) {\n data = decoder.decode(buffer);\n sync.pyterminal_write(data);\n return buffer.length;\n },\n };\n interpreter.setStdout(generic);\n interpreter.setStderr(generic);\n interpreter.setStdin({\n isatty: true,\n stdin: () => sync.pyterminal_read(data),\n });\n\n io.stderr = (error) => {\n sync.pyterminal_write(`${error.message || error}\\n`);\n };\n};\n\nconst pyTerminal = async () => {\n const terminals = document.querySelectorAll(SELECTOR);\n\n const unknown = [].filter.call(terminals, notParsedYet);\n\n // no results will look further for runtime nodes\n if (!unknown.length) return;\n // early flag elements as known to avoid concurrent\n // MutationObserver invokes of this async handler\n else unknown.forEach(bootstrapped.add, bootstrapped);\n\n // we currently support only one terminal as in \"classic\"\n if ([].filter.call(terminals, onceOnMain).length > 1)\n notifyAndThrow(\"You can use at most 1 main terminal\");\n\n // import styles lazily\n if (addStyle) {\n addStyle = false;\n document.head.append(\n Object.assign(document.createElement(\"link\"), {\n rel: \"stylesheet\",\n href: new URL(\"./xterm.css\", import.meta.url),\n }),\n );\n }\n\n // lazy load these only when a valid terminal is found\n const [{ Terminal }, { Readline }, { FitAddon }] = await Promise.all([\n import(/* webpackIgnore: true */ \"../3rd-party/xterm.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/xterm-readline.js\"),\n import(/* webpackIgnore: true */ \"../3rd-party/xterm_addon-fit.js\"),\n ]);\n\n for (const element of unknown) {\n // hopefully to be removed in the near future!\n if (element.matches('script[type=\"mpy\"],mpy-script'))\n notifyAndThrow(\"Unsupported terminal.\");\n\n const readline = new Readline();\n\n // common main thread initialization for both worker\n // or main case, bootstrapping the terminal on its target\n const init = (options) => {\n let target = element;\n const selector = element.getAttribute(\"target\");\n if (selector) {\n target =\n document.getElementById(selector) ||\n document.querySelector(selector);\n if (!target) throw new Error(`Unknown target ${selector}`);\n } else {\n target = document.createElement(\"py-terminal\");\n target.style.display = \"block\";\n element.after(target);\n }\n const terminal = new Terminal({\n theme: {\n background: \"#191A19\",\n foreground: \"#F5F2E7\",\n },\n ...options,\n });\n const fitAddon = new FitAddon();\n terminal.loadAddon(fitAddon);\n terminal.loadAddon(readline);\n terminal.open(target);\n fitAddon.fit();\n terminal.focus();\n defineProperty(element, \"terminal\", { value: terminal });\n return terminal;\n };\n\n // branch logic for the worker\n if (element.hasAttribute(\"worker\")) {\n // add a hook on the main thread to setup all sync helpers\n // also bootstrapping the XTerm target on main *BUT* ...\n hooks.main.onWorker.add(function worker(_, xworker) {\n // ... as multiple workers will add multiple callbacks\n // be sure no xworker is ever initialized twice!\n if (bootstrapped.has(xworker)) return;\n bootstrapped.add(xworker);\n\n // still cleanup this callback for future scripts/workers\n hooks.main.onWorker.delete(worker);\n\n init({\n disableStdin: false,\n cursorBlink: true,\n cursorStyle: \"block\",\n });\n\n xworker.sync.is_pyterminal = () => true;\n xworker.sync.pyterminal_read = readline.read.bind(readline);\n xworker.sync.pyterminal_write = readline.write.bind(readline);\n });\n\n // setup remote thread JS/Python code for whenever the\n // worker is ready to become a terminal\n hooks.worker.onReady.add(workerReady);\n } else {\n // in the main case, just bootstrap XTerm without\n // allowing any input as that's not possible / awkward\n hooks.main.onReady.add(function main({ interpreter, io, run }) {\n console.warn(\"py-terminal is read only on main thread\");\n hooks.main.onReady.delete(main);\n\n // on main, it's easy to trash and clean the current terminal\n globalThis.__py_terminal__ = init({\n disableStdin: true,\n cursorBlink: false,\n cursorStyle: \"underline\",\n });\n run(\"from js import __py_terminal__ as __terminal__\");\n delete globalThis.__py_terminal__;\n\n // This part is inevitably duplicated as external scope\n // can't be reached by workers out of the box.\n // The detail is that here we use readline here, not sync.\n const decoder = new TextDecoder();\n let data = \"\";\n const generic = {\n isatty: true,\n write(buffer) {\n data = decoder.decode(buffer);\n readline.write(data);\n return buffer.length;\n },\n };\n interpreter.setStdout(generic);\n interpreter.setStderr(generic);\n interpreter.setStdin({\n isatty: true,\n stdin: () => readline.read(data),\n });\n\n io.stderr = (error) => {\n readline.write(`${error.message || error}\\n`);\n };\n });\n }\n }\n};\n\nconst mo = new MutationObserver(pyTerminal);\nmo.observe(document, { childList: true, subtree: true });\n\n// try to check the current document ASAP\nexport default pyTerminal();\n"],"names":["SELECTOR","TYPES","keys","map","type","join","notifyAndThrow","message","notify","Error","notParsedYet","script","bootstrapped","has","onceOnMain","attributes","worker","WeakSet","addStyle","workerReady","interpreter","io","run","sync","is_pyterminal","decoder","TextDecoder","data","generic","isatty","write","buffer","decode","pyterminal_write","length","setStdout","setStderr","setStdin","stdin","pyterminal_read","stderr","error","pyTerminal","async","terminals","document","querySelectorAll","unknown","filter","call","forEach","add","head","append","Object","assign","createElement","rel","href","URL","url","Terminal","Readline","FitAddon","Promise","all","import","element","matches","readline","init","options","target","selector","getAttribute","getElementById","querySelector","style","display","after","terminal","theme","background","foreground","fitAddon","loadAddon","open","fit","focus","defineProperty","value","hasAttribute","hooks","main","onWorker","_","xworker","delete","disableStdin","cursorBlink","cursorStyle","read","bind","onReady","console","warn","globalThis","__py_termin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C,gBAAkBrC,EAAK,CAC9B4B,cAAc,EACdC,aAAa,EACbC,YAAa,cAEjB9E,EAAI,yDACGoF,WAAWC,gBAKlB,MAAMlF,EAAU,IAAIC,YACpB,IAAIC,EAAO,GACX,MAAMC,EAAU,CACZC,QAAQ,EACRC,MAAMC,IACFJ,EAAOF,EAAQO,OAAOD,GACtBsC,EAASvC,MAAMH,GACRI,EAAOG,SAGtBd,EAAYe,UAAUP,GACtBR,EAAYgB,UAAUR,GACtBR,EAAYiB,SAAS,CACjBR,QAAQ,EACRS,MAAO,IAAM+B,EAASgC,KAAK1E,KAG/BN,EAAGmB,OAAUC,IACT4B,EAASvC,MAAM,GAAGW,EAAMlC,SAAWkC,MAAU,CAEjE,GAEK,GAGM,IAAImE,iBAAiBlE,GAC7BmE,QAAQhE,SAAU,CAAEiE,WAAW,EAAMC,SAAS,IAGjD,IAAAC,EAAetE"}
|
package/dist.zip
ADDED
Binary file
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@pyscript/core",
|
3
|
-
"version": "0.
|
3
|
+
"version": "0.4.1",
|
4
4
|
"type": "module",
|
5
5
|
"description": "PyScript",
|
6
6
|
"module": "./index.js",
|
@@ -42,7 +42,7 @@
|
|
42
42
|
"dependencies": {
|
43
43
|
"@ungap/with-resolvers": "^0.1.0",
|
44
44
|
"basic-devtools": "^0.1.6",
|
45
|
-
"polyscript": "^0.
|
45
|
+
"polyscript": "^0.7.1",
|
46
46
|
"sticky-module": "^0.1.1",
|
47
47
|
"to-json-callback": "^0.1.1",
|
48
48
|
"type-checked-collections": "^0.1.7"
|
@@ -50,10 +50,10 @@
|
|
50
50
|
"devDependencies": {
|
51
51
|
"@codemirror/commands": "^6.3.3",
|
52
52
|
"@codemirror/lang-python": "^6.1.3",
|
53
|
-
"@codemirror/language": "^6.10.
|
53
|
+
"@codemirror/language": "^6.10.1",
|
54
54
|
"@codemirror/state": "^6.4.0",
|
55
55
|
"@codemirror/view": "^6.23.1",
|
56
|
-
"@playwright/test": "^1.41.
|
56
|
+
"@playwright/test": "^1.41.2",
|
57
57
|
"@rollup/plugin-commonjs": "^25.0.7",
|
58
58
|
"@rollup/plugin-node-resolve": "^15.2.3",
|
59
59
|
"@rollup/plugin-terser": "^0.4.4",
|
package/src/core.js
CHANGED
@@ -29,10 +29,36 @@ import { hooks, main, worker, codeFor, createFunction } from "./hooks.js";
|
|
29
29
|
// generic helper to disambiguate between custom element and script
|
30
30
|
const isScript = ({ tagName }) => tagName === "SCRIPT";
|
31
31
|
|
32
|
+
// Used to create either Pyodide or MicroPython workers
|
33
|
+
// with the PyScript module available within the code
|
34
|
+
const [PyWorker, MPWorker] = [...TYPES.entries()].map(
|
35
|
+
([TYPE, interpreter]) =>
|
36
|
+
/**
|
37
|
+
* A `Worker` facade able to bootstrap on the worker thread only a PyScript module.
|
38
|
+
* @param {string} file the python file to run ina worker.
|
39
|
+
* @param {{config?: string | object, async?: boolean}} [options] optional configuration for the worker.
|
40
|
+
* @returns {Promise<Worker & {sync: object}>}
|
41
|
+
*/
|
42
|
+
async function PyScriptWorker(file, options) {
|
43
|
+
await configs.get(TYPE).plugins;
|
44
|
+
const xworker = XWorker.call(
|
45
|
+
new Hook(null, hooked.get(TYPE)),
|
46
|
+
file,
|
47
|
+
{
|
48
|
+
...options,
|
49
|
+
type: interpreter,
|
50
|
+
},
|
51
|
+
);
|
52
|
+
assign(xworker.sync, sync);
|
53
|
+
return xworker.ready;
|
54
|
+
},
|
55
|
+
);
|
56
|
+
|
32
57
|
// avoid multiple initialization of the same library
|
33
58
|
const [
|
34
59
|
{
|
35
60
|
PyWorker: exportedPyWorker,
|
61
|
+
MPWorker: exportedMPWorker,
|
36
62
|
hooks: exportedHooks,
|
37
63
|
config: exportedConfig,
|
38
64
|
whenDefined: exportedWhenDefined,
|
@@ -40,6 +66,7 @@ const [
|
|
40
66
|
alreadyLive,
|
41
67
|
] = stickyModule("@pyscript/core", {
|
42
68
|
PyWorker,
|
69
|
+
MPWorker,
|
43
70
|
hooks,
|
44
71
|
config: {},
|
45
72
|
whenDefined,
|
@@ -48,6 +75,7 @@ const [
|
|
48
75
|
export {
|
49
76
|
TYPES,
|
50
77
|
exportedPyWorker as PyWorker,
|
78
|
+
exportedMPWorker as MPWorker,
|
51
79
|
exportedHooks as hooks,
|
52
80
|
exportedConfig as config,
|
53
81
|
exportedWhenDefined as whenDefined,
|
@@ -314,24 +342,3 @@ for (const [TYPE, interpreter] of TYPES) {
|
|
314
342
|
// export the used config without allowing leaks through it
|
315
343
|
exportedConfig[TYPE] = structuredClone(config);
|
316
344
|
}
|
317
|
-
|
318
|
-
/**
|
319
|
-
* A `Worker` facade able to bootstrap on the worker thread only a PyScript module.
|
320
|
-
* @param {string} file the python file to run ina worker.
|
321
|
-
* @param {{config?: string | object, async?: boolean}} [options] optional configuration for the worker.
|
322
|
-
* @returns {Worker & {sync: ProxyHandler<object>}}
|
323
|
-
*/
|
324
|
-
function PyWorker(file, options) {
|
325
|
-
const hooks = hooked.get("py");
|
326
|
-
// this propagates pyscript worker hooks without needing a pyscript
|
327
|
-
// bootstrap + it passes arguments and it defaults to `pyodide`
|
328
|
-
// as the interpreter to use in the worker, as all hooks assume that
|
329
|
-
// and as `pyodide` is the only default interpreter that can deal with
|
330
|
-
// all the features we need to deliver pyscript out there.
|
331
|
-
const xworker = XWorker.call(new Hook(null, hooks), file, {
|
332
|
-
type: "pyodide",
|
333
|
-
...options,
|
334
|
-
});
|
335
|
-
assign(xworker.sync, sync);
|
336
|
-
return xworker;
|
337
|
-
}
|
@@ -43,6 +43,8 @@ from pyscript.magic_js import (
|
|
43
43
|
try:
|
44
44
|
from pyscript.event_handling import when
|
45
45
|
except:
|
46
|
+
# TODO: should we remove this? Or at the very least, we should capture
|
47
|
+
# the traceback otherwise it's very hard to debug
|
46
48
|
from pyscript.util import NotSupported
|
47
49
|
|
48
50
|
when = NotSupported(
|
@@ -1,6 +1,14 @@
|
|
1
1
|
import inspect
|
2
2
|
|
3
|
-
|
3
|
+
try:
|
4
|
+
from pyodide.ffi.wrappers import add_event_listener
|
5
|
+
|
6
|
+
except ImportError:
|
7
|
+
|
8
|
+
def add_event_listener(el, event_type, func):
|
9
|
+
el.addEventListener(event_type, func)
|
10
|
+
|
11
|
+
|
4
12
|
from pyscript.magic_js import document
|
5
13
|
|
6
14
|
|
@@ -27,19 +35,32 @@ def when(event_type=None, selector=None):
|
|
27
35
|
f"Invalid selector: {selector}. Selector must"
|
28
36
|
" be a string, a pydom.Element or a pydom.ElementCollection."
|
29
37
|
)
|
38
|
+
try:
|
39
|
+
sig = inspect.signature(func)
|
40
|
+
# Function doesn't receive events
|
41
|
+
if not sig.parameters:
|
30
42
|
|
31
|
-
|
32
|
-
|
33
|
-
if not sig.parameters:
|
43
|
+
def wrapper(*args, **kwargs):
|
44
|
+
func()
|
34
45
|
|
46
|
+
else:
|
47
|
+
wrapper = func
|
48
|
+
|
49
|
+
except AttributeError:
|
50
|
+
# TODO: this is currently an quick hack to get micropython working but we need
|
51
|
+
# to actually properly replace inspect.signature with something else
|
35
52
|
def wrapper(*args, **kwargs):
|
36
|
-
|
53
|
+
try:
|
54
|
+
return func(*args, **kwargs)
|
55
|
+
except TypeError as e:
|
56
|
+
if "takes 0 positional arguments" in str(e):
|
57
|
+
return func()
|
58
|
+
|
59
|
+
raise
|
60
|
+
|
61
|
+
for el in elements:
|
62
|
+
add_event_listener(el, event_type, wrapper)
|
37
63
|
|
38
|
-
for el in elements:
|
39
|
-
add_event_listener(el, event_type, wrapper)
|
40
|
-
else:
|
41
|
-
for el in elements:
|
42
|
-
add_event_listener(el, event_type, func)
|
43
64
|
return func
|
44
65
|
|
45
66
|
return decorator
|
@@ -24,16 +24,33 @@ for name in globalThis.Reflect.ownKeys(js_modules):
|
|
24
24
|
sys.modules["pyscript.js_modules"] = js_modules
|
25
25
|
|
26
26
|
if RUNNING_IN_WORKER:
|
27
|
-
import js
|
28
27
|
import polyscript
|
29
28
|
|
30
29
|
PyWorker = NotSupported(
|
31
30
|
"pyscript.PyWorker",
|
32
31
|
"pyscript.PyWorker works only when running in the main thread",
|
33
32
|
)
|
34
|
-
|
35
|
-
|
36
|
-
|
33
|
+
|
34
|
+
try:
|
35
|
+
globalThis.SharedArrayBuffer.new(4)
|
36
|
+
import js
|
37
|
+
|
38
|
+
window = polyscript.xworker.window
|
39
|
+
document = window.document
|
40
|
+
js.document = document
|
41
|
+
except:
|
42
|
+
globalThis.console.debug("SharedArrayBuffer is not available")
|
43
|
+
# in this scenario none of the utilities would work
|
44
|
+
# as expected so we better export these as NotSupported
|
45
|
+
window = NotSupported(
|
46
|
+
"pyscript.window",
|
47
|
+
"pyscript.window in workers works only via SharedArrayBuffer",
|
48
|
+
)
|
49
|
+
document = NotSupported(
|
50
|
+
"pyscript.document",
|
51
|
+
"pyscript.document in workers works only via SharedArrayBuffer",
|
52
|
+
)
|
53
|
+
|
37
54
|
sync = polyscript.xworker.sync
|
38
55
|
|
39
56
|
# in workers the display does not have a default ID
|
package/src/stdlib/pyscript.js
CHANGED
@@ -1,14 +1,15 @@
|
|
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.display import HTML, display\nfrom pyscript.magic_js import (\n RUNNING_IN_WORKER,\n PyWorker,\n current_target,\n document,\n js_modules,\n sync,\n window,\n)\n\ntry:\n from pyscript.event_handling import when\nexcept:\n from pyscript.util import NotSupported\n\n when = NotSupported(\n \"pyscript.when\", \"pyscript.when currently not available with this interpreter\"\n )\n",
|
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.display import HTML, display\nfrom pyscript.magic_js import (\n RUNNING_IN_WORKER,\n PyWorker,\n current_target,\n document,\n js_modules,\n sync,\n window,\n)\n\ntry:\n from pyscript.event_handling import when\nexcept:\n # TODO: should we remove this? Or at the very least, we should capture\n # the traceback otherwise it's very hard to debug\n from pyscript.util import NotSupported\n\n when = NotSupported(\n \"pyscript.when\", \"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 current_target, document, window\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_pdf_\": \"application/pdf\",\n \"_repr_jpeg_\": \"image/jpeg\",\n \"_repr_png_\": \"image/png\",\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 elif not isinstance(target, str):\n raise TypeError(f\"target must be str or None, not {target.__class__.__name__}\")\n elif target == \"\":\n raise ValueError(\"Cannot have an empty target\")\n elif target.startswith(\"#\"):\n # note: here target is str and not None!\n # align with @when behavior\n target = target[1:]\n\n element = document.getElementById(target)\n\n # If target cannot be found on the page, a ValueError is raised\n if element is None:\n raise ValueError(\n f\"Invalid selector with id={target}. Cannot be found in the page.\"\n )\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 if not append:\n element.replaceChildren()\n _write(element, v, append=append)\n",
|
6
|
-
"event_handling.py": "import inspect\n\
|
7
|
-
"magic_js.py": "import sys\n\nimport js as globalThis\nfrom polyscript import js_modules\nfrom pyscript.util import NotSupported\n\nRUNNING_IN_WORKER = not hasattr(globalThis, \"document\")\n\n\n# allow `from pyscript.js_modules.xxx import yyy`\nclass JSModule:\n def __init__(self, name):\n self.name = name\n\n def __getattr__(self, field):\n # avoid pyodide looking for non existent fields\n if not field.startswith(\"_\"):\n return getattr(getattr(js_modules, self.name), field)\n\n\n# generate N modules in the system that will proxy the real value\nfor name in globalThis.Reflect.ownKeys(js_modules):\n sys.modules[f\"pyscript.js_modules.{name}\"] = JSModule(name)\nsys.modules[\"pyscript.js_modules\"] = js_modules\n\nif RUNNING_IN_WORKER:\n import
|
6
|
+
"event_handling.py": "import inspect\n\ntry:\n from pyodide.ffi.wrappers import add_event_listener\n\nexcept ImportError:\n\n def add_event_listener(el, event_type, func):\n el.addEventListener(event_type, func)\n\n\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 try:\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 else:\n wrapper = func\n\n except AttributeError:\n # TODO: this is currently an quick hack to get micropython working but we need\n # to actually properly replace inspect.signature with something else\n def wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except TypeError as e:\n if \"takes 0 positional arguments\" in str(e):\n return func()\n\n raise\n\n for el in elements:\n add_event_listener(el, event_type, wrapper)\n\n return func\n\n return decorator\n",
|
7
|
+
"magic_js.py": "import sys\n\nimport js as globalThis\nfrom polyscript import js_modules\nfrom pyscript.util import NotSupported\n\nRUNNING_IN_WORKER = not hasattr(globalThis, \"document\")\n\n\n# allow `from pyscript.js_modules.xxx import yyy`\nclass JSModule:\n def __init__(self, name):\n self.name = name\n\n def __getattr__(self, field):\n # avoid pyodide looking for non existent fields\n if not field.startswith(\"_\"):\n return getattr(getattr(js_modules, self.name), field)\n\n\n# generate N modules in the system that will proxy the real value\nfor name in globalThis.Reflect.ownKeys(js_modules):\n sys.modules[f\"pyscript.js_modules.{name}\"] = JSModule(name)\nsys.modules[\"pyscript.js_modules\"] = js_modules\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 )\n\n try:\n globalThis.SharedArrayBuffer.new(4)\n import js\n\n window = polyscript.xworker.window\n document = window.document\n js.document = document\n except:\n globalThis.console.debug(\"SharedArrayBuffer is not available\")\n # in this scenario none of the utilities would work\n # as expected so we better export these as NotSupported\n window = NotSupported(\n \"pyscript.window\",\n \"pyscript.window in workers works only via SharedArrayBuffer\",\n )\n document = NotSupported(\n \"pyscript.document\",\n \"pyscript.document in workers works only via SharedArrayBuffer\",\n )\n\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\n window = globalThis\n document = globalThis.document\n sync = NotSupported(\n \"pyscript.sync\", \"pyscript.sync works only when running in a worker\"\n )\n\n # in MAIN the current element target exist, just use it\n def current_target():\n return _pyscript.target\n",
|
8
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
|
+
"__init__.py": "from .pydom import dom as pydom\n",
|
11
12
|
"media.py": "from pyodide.ffi import to_js\nfrom pyscript import window\n\n\nclass Device:\n \"\"\"Device represents a media input or output device, such as a microphone,\n camera, or headset.\n \"\"\"\n\n def __init__(self, device):\n self._js = device\n\n @property\n def id(self):\n return self._js.deviceId\n\n @property\n def group(self):\n return self._js.groupId\n\n @property\n def kind(self):\n return self._js.kind\n\n @property\n def label(self):\n return self._js.label\n\n def __getitem__(self, key):\n return getattr(self, key)\n\n @classmethod\n async def load(cls, audio=False, video=True):\n \"\"\"Load the device stream.\"\"\"\n options = window.Object.new()\n options.audio = audio\n if isinstance(video, bool):\n options.video = video\n else:\n # TODO: Think this can be simplified but need to check it on the pyodide side\n\n # TODO: this is pyodide specific. shouldn't be!\n options.video = window.Object.new()\n for k in video:\n setattr(\n options.video,\n k,\n to_js(video[k], dict_converter=window.Object.fromEntries),\n )\n\n stream = await window.navigator.mediaDevices.getUserMedia(options)\n return stream\n\n async def get_stream(self):\n key = self.kind.replace(\"input\", \"\").replace(\"output\", \"\")\n options = {key: {\"deviceId\": {\"exact\": self.id}}}\n\n return await self.load(**options)\n\n\nasync def list_devices() -> list[dict]:\n \"\"\"\n Return the list of the currently available media input and output devices,\n such as microphones, cameras, headsets, and so forth.\n\n Output:\n\n list(dict) - list of dictionaries representing the available media devices.\n Each dictionary has the following keys:\n * deviceId: a string that is an identifier for the represented device\n that is persisted across sessions. It is un-guessable by other\n applications and unique to the origin of the calling application.\n It is reset when the user clears cookies (for Private Browsing, a\n different identifier is used that is not persisted across sessions).\n\n * groupId: a string that is a group identifier. Two devices have the same\n group identifier if they belong to the same physical device — for\n example a monitor with both a built-in camera and a microphone.\n\n * kind: an enumerated value that is either \"videoinput\", \"audioinput\"\n or \"audiooutput\".\n\n * label: a string describing this device (for example \"External USB\n Webcam\").\n\n Note: the returned list will omit any devices that are blocked by the document\n Permission Policy: microphone, camera, speaker-selection (for output devices),\n and so on. Access to particular non-default devices is also gated by the\n Permissions API, and the list will omit devices for which the user has not\n granted explicit permission.\n \"\"\"\n # https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices\n return [\n Device(obj) for obj in await window.navigator.mediaDevices.enumerateDevices()\n ]\n",
|
12
|
-
"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\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 self._proxies = {}\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 @property\n def options(self):\n if \"options\" in self._proxies:\n return self._proxies[\"options\"]\n\n if not self._js.tagName.lower() in {\"select\", \"datalist\", \"optgroup\"}:\n raise AttributeError(\n f\"Element {self._js.tagName} has no options attribute.\"\n )\n self._proxies[\"options\"] = OptionsProxy(self)\n return self._proxies[\"options\"]\n\n @property\n def value(self):\n return self._js.value\n\n @value.setter\n def value(self, value):\n # in order to avoid confusion to the user, we don't allow setting the\n # value of elements that don't have a value attribute\n if not hasattr(self._js, \"value\"):\n raise AttributeError(\n f\"Element {self._js.tagName} has no value attribute. If you want to \"\n \"force a value attribute, set it directly using the `_js.value = <value>` \"\n \"javascript API attribute instead.\"\n )\n self._js.value = value\n\n @property\n def selected(self):\n return self._js.selected\n\n @selected.setter\n def selected(self, value):\n # in order to avoid confusion to the user, we don't allow setting the\n # value of elements that don't have a value attribute\n if not hasattr(self._js, \"selected\"):\n raise AttributeError(\n f\"Element {self._js.tagName} has no value attribute. If you want to \"\n \"force a value attribute, set it directly using the `_js.value = <value>` \"\n \"javascript API attribute instead.\"\n )\n self._js.selected = 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 snap(\n self,\n to: BaseElement | str = None,\n width: int | None = None,\n height: int | None = None,\n ):\n \"\"\"\n Captures a snapshot of a video element. (Only available for video elements)\n\n Inputs:\n\n * to: element where to save the snapshot of the video frame to\n * width: width of the image\n * height: height of the image\n\n Output:\n (Element) canvas element where the video frame snapshot was drawn into\n \"\"\"\n if self._js.tagName != \"VIDEO\":\n raise AttributeError(\"Snap method is only available for video Elements\")\n\n if to is None:\n canvas = self.create(\"canvas\")\n if width is None:\n width = self._js.width\n if height is None:\n height = self._js.height\n canvas._js.width = width\n canvas._js.height = height\n\n elif isistance(to, Element):\n if to._js.tagName != \"CANVAS\":\n raise TypeError(\"Element to snap to must a canvas.\")\n canvas = to\n elif getattr(to, \"tagName\", \"\") == \"CANVAS\":\n canvas = Element(to)\n elif isinstance(to, str):\n canvas = pydom[to][0]\n if canvas._js.tagName != \"CANVAS\":\n raise TypeError(\"Element to snap to must a be canvas.\")\n\n canvas.draw(self, width, height)\n\n return canvas\n\n def download(self, filename: str = \"snapped.png\") -> None:\n \"\"\"Download the current element (only available for canvas elements) with the filename\n provided in input.\n\n Inputs:\n * filename (str): name of the file being downloaded\n\n Output:\n None\n \"\"\"\n if self._js.tagName != \"CANVAS\":\n raise AttributeError(\n \"The download method is only available for canvas Elements\"\n )\n\n link = self.create(\"a\")\n link._js.download = filename\n link._js.href = self._js.toDataURL()\n link._js.click()\n\n def draw(self, what, width, height):\n \"\"\"Draw `what` on the current element (only available for canvas elements).\n\n Inputs:\n\n * what (canvas image source): An element to draw into the context. The specification permits any canvas\n image source, specifically, an HTMLImageElement, an SVGImageElement, an HTMLVideoElement,\n an HTMLCanvasElement, an ImageBitmap, an OffscreenCanvas, or a VideoFrame.\n \"\"\"\n if self._js.tagName != \"CANVAS\":\n raise AttributeError(\n \"The draw method is only available for canvas Elements\"\n )\n\n if isinstance(what, Element):\n what = what._js\n\n # https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage\n self._js.getContext(\"2d\").drawImage(what, 0, 0, width, height)\n\n\nclass OptionsProxy:\n \"\"\"This class represents the options of a select element. It\n allows to access to add and remove options by using the `add` and `remove` methods.\n \"\"\"\n\n def __init__(self, element: Element) -> None:\n self._element = element\n if self._element._js.tagName.lower() != \"select\":\n raise AttributeError(\n f\"Element {self._element._js.tagName} has no options attribute.\"\n )\n\n def add(\n self,\n value: Any = None,\n html: str = None,\n text: str = None,\n before: Element | int = None,\n **kws,\n ) -> None:\n \"\"\"Add a new option to the select element\"\"\"\n # create the option element and set the attributes\n option = document.createElement(\"option\")\n if value is not None:\n kws[\"value\"] = value\n if html is not None:\n option.innerHTML = html\n if text is not None:\n kws[\"text\"] = text\n\n for key, value in kws.items():\n option.setAttribute(key, value)\n\n if before:\n if isinstance(before, Element):\n before = before._js\n\n self._element._js.add(option, before)\n\n def remove(self, item: int) -> None:\n \"\"\"Remove the option at the specified index\"\"\"\n self._element._js.remove(item)\n\n def clear(self) -> None:\n \"\"\"Remove all the options\"\"\"\n for i in range(len(self)):\n self.remove(0)\n\n @property\n def options(self):\n \"\"\"Return the list of options\"\"\"\n return [Element(opt) for opt in self._element._js.options]\n\n @property\n def selected(self):\n \"\"\"Return the selected option\"\"\"\n return self.options[self._element._js.selectedIndex]\n\n def __iter__(self):\n yield from self.options\n\n def __len__(self):\n return len(self.options)\n\n def __repr__(self):\n return f\"{self.__class__.__name__} (length: {len(self)}) {self.options}\"\n\n def __getitem__(self, key):\n return self.options[key]\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 value(self):\n return self._get_attribute(\"value\")\n\n @value.setter\n def value(self, value):\n self._set_attribute(\"value\", 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_, classes=None, html=None):\n return super().create(type_, is_child=False, classes=classes, html=html)\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"
|
13
|
+
"pydom.py": "try:\n from typing import Any\nexcept ImportError:\n Any = \"Any\"\n\ntry:\n import warnings\nexcept ImportError:\n # TODO: For now it probably means we are in MicroPython. We should figure\n # out the \"right\" way to handle this. For now we just ignore the warning\n # and logging to console\n class warnings:\n @staticmethod\n def warn(*args, **kwargs):\n print(\"WARNING: \", *args, **kwargs)\n\n\ntry:\n from functools import cached_property\nexcept ImportError:\n # TODO: same comment about micropython as above\n cached_property = property\n\ntry:\n from pyodide.ffi import JsProxy\nexcept ImportError:\n # TODO: same comment about micropython as above\n def JsProxy(obj):\n return obj\n\n\nfrom pyscript import display, document, window\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 self._proxies = {}\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 @property\n def options(self):\n if \"options\" in self._proxies:\n return self._proxies[\"options\"]\n\n if not self._js.tagName.lower() in {\"select\", \"datalist\", \"optgroup\"}:\n raise AttributeError(\n f\"Element {self._js.tagName} has no options attribute.\"\n )\n self._proxies[\"options\"] = OptionsProxy(self)\n return self._proxies[\"options\"]\n\n @property\n def value(self):\n return self._js.value\n\n @value.setter\n def value(self, value):\n # in order to avoid confusion to the user, we don't allow setting the\n # value of elements that don't have a value attribute\n if not hasattr(self._js, \"value\"):\n raise AttributeError(\n f\"Element {self._js.tagName} has no value attribute. If you want to \"\n \"force a value attribute, set it directly using the `_js.value = <value>` \"\n \"javascript API attribute instead.\"\n )\n self._js.value = value\n\n @property\n def selected(self):\n return self._js.selected\n\n @selected.setter\n def selected(self, value):\n # in order to avoid confusion to the user, we don't allow setting the\n # value of elements that don't have a value attribute\n if not hasattr(self._js, \"selected\"):\n raise AttributeError(\n f\"Element {self._js.tagName} has no value attribute. If you want to \"\n \"force a value attribute, set it directly using the `_js.value = <value>` \"\n \"javascript API attribute instead.\"\n )\n self._js.selected = 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 snap(\n self,\n to: BaseElement | str = None,\n width: int | None = None,\n height: int | None = None,\n ):\n \"\"\"\n Captures a snapshot of a video element. (Only available for video elements)\n\n Inputs:\n\n * to: element where to save the snapshot of the video frame to\n * width: width of the image\n * height: height of the image\n\n Output:\n (Element) canvas element where the video frame snapshot was drawn into\n \"\"\"\n if self._js.tagName != \"VIDEO\":\n raise AttributeError(\"Snap method is only available for video Elements\")\n\n if to is None:\n canvas = self.create(\"canvas\")\n if width is None:\n width = self._js.width\n if height is None:\n height = self._js.height\n canvas._js.width = width\n canvas._js.height = height\n\n elif isistance(to, Element):\n if to._js.tagName != \"CANVAS\":\n raise TypeError(\"Element to snap to must a canvas.\")\n canvas = to\n elif getattr(to, \"tagName\", \"\") == \"CANVAS\":\n canvas = Element(to)\n elif isinstance(to, str):\n canvas = pydom[to][0]\n if canvas._js.tagName != \"CANVAS\":\n raise TypeError(\"Element to snap to must a be canvas.\")\n\n canvas.draw(self, width, height)\n\n return canvas\n\n def download(self, filename: str = \"snapped.png\") -> None:\n \"\"\"Download the current element (only available for canvas elements) with the filename\n provided in input.\n\n Inputs:\n * filename (str): name of the file being downloaded\n\n Output:\n None\n \"\"\"\n if self._js.tagName != \"CANVAS\":\n raise AttributeError(\n \"The download method is only available for canvas Elements\"\n )\n\n link = self.create(\"a\")\n link._js.download = filename\n link._js.href = self._js.toDataURL()\n link._js.click()\n\n def draw(self, what, width, height):\n \"\"\"Draw `what` on the current element (only available for canvas elements).\n\n Inputs:\n\n * what (canvas image source): An element to draw into the context. The specification permits any canvas\n image source, specifically, an HTMLImageElement, an SVGImageElement, an HTMLVideoElement,\n an HTMLCanvasElement, an ImageBitmap, an OffscreenCanvas, or a VideoFrame.\n \"\"\"\n if self._js.tagName != \"CANVAS\":\n raise AttributeError(\n \"The draw method is only available for canvas Elements\"\n )\n\n if isinstance(what, Element):\n what = what._js\n\n # https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage\n self._js.getContext(\"2d\").drawImage(what, 0, 0, width, height)\n\n\nclass OptionsProxy:\n \"\"\"This class represents the options of a select element. It\n allows to access to add and remove options by using the `add` and `remove` methods.\n \"\"\"\n\n def __init__(self, element: Element) -> None:\n self._element = element\n if self._element._js.tagName.lower() != \"select\":\n raise AttributeError(\n f\"Element {self._element._js.tagName} has no options attribute.\"\n )\n\n def add(\n self,\n value: Any = None,\n html: str = None,\n text: str = None,\n before: Element | int = None,\n **kws,\n ) -> None:\n \"\"\"Add a new option to the select element\"\"\"\n # create the option element and set the attributes\n option = document.createElement(\"option\")\n if value is not None:\n kws[\"value\"] = value\n if html is not None:\n option.innerHTML = html\n if text is not None:\n kws[\"text\"] = text\n\n for key, value in kws.items():\n option.setAttribute(key, value)\n\n if before:\n if isinstance(before, Element):\n before = before._js\n\n self._element._js.add(option, before)\n\n def remove(self, item: int) -> None:\n \"\"\"Remove the option at the specified index\"\"\"\n self._element._js.remove(item)\n\n def clear(self) -> None:\n \"\"\"Remove all the options\"\"\"\n for i in range(len(self)):\n self.remove(0)\n\n @property\n def options(self):\n \"\"\"Return the list of options\"\"\"\n return [Element(opt) for opt in self._element._js.options]\n\n @property\n def selected(self):\n \"\"\"Return the selected option\"\"\"\n return self.options[self._element._js.selectedIndex]\n\n def __iter__(self):\n yield from self.options\n\n def __len__(self):\n return len(self.options)\n\n def __repr__(self):\n return f\"{self.__class__.__name__} (length: {len(self)}) {self.options}\"\n\n def __getitem__(self, key):\n return self.options[key]\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 value(self):\n return self._get_attribute(\"value\")\n\n @value.setter\n def value(self, value):\n self._set_attribute(\"value\", 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):\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 # PyDom is a special case of BaseElement where we don't want to create a new JS element\n # and it really doesn't have a need for styleproxy or parent to to call to __init__\n # (which actually fails in MP for some reason)\n self._js = document\n self._parent = None\n self._proxies = {}\n self.ids = DomScope()\n self.body = Element(document.body)\n self.head = Element(document.head)\n\n def create(self, type_, classes=None, html=None):\n return super().create(type_, is_child=False, classes=classes, html=html)\n\n def __getitem__(self, key):\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"
|
13
14
|
}
|
14
15
|
};
|
@@ -0,0 +1 @@
|
|
1
|
+
from .pydom import dom as pydom
|