@pyscript/core 0.3.20 → 0.3.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/core.js CHANGED
@@ -1,2 +1,2 @@
1
- export{b as PyWorker,T as TYPES,c as config,e as hooks,f as whenDefined}from"./core-_MDTi7dy.js";
1
+ export{b as PyWorker,T as TYPES,c as config,e as hooks,f as whenDefined}from"./core-14p8E60X.js";
2
2
  //# sourceMappingURL=core.js.map
@@ -1,2 +1,2 @@
1
- import{e}from"./core-_MDTi7dy.js";import{notify as o}from"./error-yavCjy9g.js";function r(){const e=document.querySelectorAll("script");for(const o of e)s(o.src)}function s(e){/\/pyscript\.net\/latest/.test(e)&&o("Loading scripts from latest is deprecated and will be removed soon. Please use a specific version instead.")}e.main.onReady.add(r),e.main.onWorker.add(r);
2
- //# sourceMappingURL=deprecations-manager-xSJEJMfx.js.map
1
+ import{e}from"./core-14p8E60X.js";import{notify as o}from"./error-tt9AxwDf.js";function r(){const e=document.querySelectorAll("script");for(const o of e)s(o.src)}function s(e){/\/pyscript\.net\/latest/.test(e)&&o("Loading scripts from latest is deprecated and will be removed soon. Please use a specific version instead.")}e.main.onReady.add(r),e.main.onWorker.add(r);
2
+ //# sourceMappingURL=deprecations-manager-DiLupR6w.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"deprecations-manager-xSJEJMfx.js","sources":["../src/plugins/deprecations-manager.js"],"sourcesContent":["// PyScript Derepcations Plugin\nimport { hooks } from \"../core.js\";\nimport { notify } from \"./error.js\";\n\n// react lazily on PyScript bootstrap\nhooks.main.onReady.add(checkDeprecations);\nhooks.main.onWorker.add(checkDeprecations);\n\n/**\n * Check that there are no scripts loading from pyscript.net/latest\n */\nfunction checkDeprecations() {\n const scripts = document.querySelectorAll(\"script\");\n for (const script of scripts) checkLoadingScriptsFromLatest(script.src);\n}\n\n/**\n * Check if src being loaded from pyscript.net/latest and display a notification if true\n * * @param {string} src\n */\nfunction checkLoadingScriptsFromLatest(src) {\n if (/\\/pyscript\\.net\\/latest/.test(src)) {\n notify(\n \"Loading scripts from latest is deprecated and will be removed soon. Please use a specific version instead.\",\n );\n }\n}\n"],"names":["checkDeprecations","scripts","document","querySelectorAll","script","checkLoadingScriptsFromLatest","src","test","notify","hooks","main","onReady","add","onWorker"],"mappings":"+EAWA,SAASA,IACL,MAAMC,EAAUC,SAASC,iBAAiB,UAC1C,IAAK,MAAMC,KAAUH,EAASI,EAA8BD,EAAOE,IACvE,CAMA,SAASD,EAA8BC,GAC/B,0BAA0BC,KAAKD,IAC/BE,EACI,6GAGZ,CArBAC,EAAMC,KAAKC,QAAQC,IAAIZ,GACvBS,EAAMC,KAAKG,SAASD,IAAIZ"}
1
+ {"version":3,"file":"deprecations-manager-DiLupR6w.js","sources":["../src/plugins/deprecations-manager.js"],"sourcesContent":["// PyScript Derepcations Plugin\nimport { hooks } from \"../core.js\";\nimport { notify } from \"./error.js\";\n\n// react lazily on PyScript bootstrap\nhooks.main.onReady.add(checkDeprecations);\nhooks.main.onWorker.add(checkDeprecations);\n\n/**\n * Check that there are no scripts loading from pyscript.net/latest\n */\nfunction checkDeprecations() {\n const scripts = document.querySelectorAll(\"script\");\n for (const script of scripts) checkLoadingScriptsFromLatest(script.src);\n}\n\n/**\n * Check if src being loaded from pyscript.net/latest and display a notification if true\n * * @param {string} src\n */\nfunction checkLoadingScriptsFromLatest(src) {\n if (/\\/pyscript\\.net\\/latest/.test(src)) {\n notify(\n \"Loading scripts from latest is deprecated and will be removed soon. Please use a specific version instead.\",\n );\n }\n}\n"],"names":["checkDeprecations","scripts","document","querySelectorAll","script","checkLoadingScriptsFromLatest","src","test","notify","hooks","main","onReady","add","onWorker"],"mappings":"+EAWA,SAASA,IACL,MAAMC,EAAUC,SAASC,iBAAiB,UAC1C,IAAK,MAAMC,KAAUH,EAASI,EAA8BD,EAAOE,IACvE,CAMA,SAASD,EAA8BC,GAC/B,0BAA0BC,KAAKD,IAC/BE,EACI,6GAGZ,CArBAC,EAAMC,KAAKC,QAAQC,IAAIZ,GACvBS,EAAMC,KAAKG,SAASD,IAAIZ"}
@@ -1,2 +1,2 @@
1
- import{e}from"./core-_MDTi7dy.js";function n(e){const n=document.createElement("div");n.className="py-error",n.textContent=e,n.style.cssText="\n border: 1px solid red;\n background: #ffdddd;\n color: black;\n font-family: courier, monospace;\n white-space: pre;\n overflow-x: auto;\n padding: 8px;\n margin-top: 8px;\n ",document.body.append(n)}e.main.onReady.add((function o(r){e.main.onReady.delete(o);const{stderr:t}=r.io;r.io.stderr=(e,...o)=>(n(e.message||e),t(e,...o)),addEventListener("error",(({message:e})=>{e.startsWith("Uncaught PythonError")&&n(e)}))}));export{n as notify};
2
- //# sourceMappingURL=error-yavCjy9g.js.map
1
+ import{e}from"./core-14p8E60X.js";function n(e){const n=document.createElement("div");n.className="py-error",n.textContent=e,n.style.cssText="\n border: 1px solid red;\n background: #ffdddd;\n color: black;\n font-family: courier, monospace;\n white-space: pre;\n overflow-x: auto;\n padding: 8px;\n margin-top: 8px;\n ",document.body.append(n)}e.main.onReady.add((function o(r){e.main.onReady.delete(o);const{stderr:t}=r.io;r.io.stderr=(e,...o)=>(n(e.message||e),t(e,...o)),addEventListener("error",(({message:e})=>{e.startsWith("Uncaught PythonError")&&n(e)}))}));export{n as notify};
2
+ //# sourceMappingURL=error-tt9AxwDf.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"error-yavCjy9g.js","sources":["../src/plugins/error.js"],"sourcesContent":["// PyScript Error Plugin\nimport { hooks } from \"../core.js\";\n\nhooks.main.onReady.add(function override(pyScript) {\n // be sure this override happens only once\n hooks.main.onReady.delete(override);\n\n // trap generic `stderr` to propagate to it regardless\n const { stderr } = pyScript.io;\n\n // override it with our own logic\n pyScript.io.stderr = (error, ...rest) => {\n notify(error.message || error);\n // let other plugins or stderr hook, if any, do the rest\n return stderr(error, ...rest);\n };\n\n // be sure uncaught Python errors are also visible\n addEventListener(\"error\", ({ message }) => {\n if (message.startsWith(\"Uncaught PythonError\")) notify(message);\n });\n});\n\n// Error hook utilities\n\n// Custom function to show notifications\n\n/**\n * Add a banner to the top of the page, notifying the user of an error\n * @param {string} message\n */\nexport function notify(message) {\n const div = document.createElement(\"div\");\n div.className = \"py-error\";\n div.textContent = message;\n div.style.cssText = `\n border: 1px solid red;\n background: #ffdddd;\n color: black;\n font-family: courier, monospace;\n white-space: pre;\n overflow-x: auto;\n padding: 8px;\n margin-top: 8px;\n `;\n document.body.append(div);\n}\n"],"names":["notify","message","div","document","createElement","className","textContent","style","cssText","body","append","hooks","main","onReady","add","override","pyScript","delete","stderr","io","error","rest","addEventListener","startsWith"],"mappings":"kCA+BO,SAASA,EAAOC,GACnB,MAAMC,EAAMC,SAASC,cAAc,OACnCF,EAAIG,UAAY,WAChBH,EAAII,YAAcL,EAClBC,EAAIK,MAAMC,QAAU,6MAUpBL,SAASM,KAAKC,OAAOR,EACzB,CA3CAS,EAAMC,KAAKC,QAAQC,KAAI,SAASC,EAASC,GAErCL,EAAMC,KAAKC,QAAQI,OAAOF,GAG1B,MAAMG,OAAEA,GAAWF,EAASG,GAG5BH,EAASG,GAAGD,OAAS,CAACE,KAAUC,KAC5BrB,EAAOoB,EAAMnB,SAAWmB,GAEjBF,EAAOE,KAAUC,IAI5BC,iBAAiB,SAAS,EAAGrB,cACrBA,EAAQsB,WAAW,yBAAyBvB,EAAOC,EAAQ,GAEvE"}
1
+ {"version":3,"file":"error-tt9AxwDf.js","sources":["../src/plugins/error.js"],"sourcesContent":["// PyScript Error Plugin\nimport { hooks } from \"../core.js\";\n\nhooks.main.onReady.add(function override(pyScript) {\n // be sure this override happens only once\n hooks.main.onReady.delete(override);\n\n // trap generic `stderr` to propagate to it regardless\n const { stderr } = pyScript.io;\n\n // override it with our own logic\n pyScript.io.stderr = (error, ...rest) => {\n notify(error.message || error);\n // let other plugins or stderr hook, if any, do the rest\n return stderr(error, ...rest);\n };\n\n // be sure uncaught Python errors are also visible\n addEventListener(\"error\", ({ message }) => {\n if (message.startsWith(\"Uncaught PythonError\")) notify(message);\n });\n});\n\n// Error hook utilities\n\n// Custom function to show notifications\n\n/**\n * Add a banner to the top of the page, notifying the user of an error\n * @param {string} message\n */\nexport function notify(message) {\n const div = document.createElement(\"div\");\n div.className = \"py-error\";\n div.textContent = message;\n div.style.cssText = `\n border: 1px solid red;\n background: #ffdddd;\n color: black;\n font-family: courier, monospace;\n white-space: pre;\n overflow-x: auto;\n padding: 8px;\n margin-top: 8px;\n `;\n document.body.append(div);\n}\n"],"names":["notify","message","div","document","createElement","className","textContent","style","cssText","body","append","hooks","main","onReady","add","override","pyScript","delete","stderr","io","error","rest","addEventListener","startsWith"],"mappings":"kCA+BO,SAASA,EAAOC,GACnB,MAAMC,EAAMC,SAASC,cAAc,OACnCF,EAAIG,UAAY,WAChBH,EAAII,YAAcL,EAClBC,EAAIK,MAAMC,QAAU,6MAUpBL,SAASM,KAAKC,OAAOR,EACzB,CA3CAS,EAAMC,KAAKC,QAAQC,KAAI,SAASC,EAASC,GAErCL,EAAMC,KAAKC,QAAQI,OAAOF,GAG1B,MAAMG,OAAEA,GAAWF,EAASG,GAG5BH,EAASG,GAAGD,OAAS,CAACE,KAAUC,KAC5BrB,EAAOoB,EAAMnB,SAAWmB,GAEjBF,EAAOE,KAAUC,IAI5BC,iBAAiB,SAAS,EAAGrB,cACrBA,EAAQsB,WAAW,yBAAyBvB,EAAOC,EAAQ,GAEvE"}
@@ -1,2 +1,2 @@
1
- import{T as e,d as t,X as r,H as n}from"./core-_MDTi7dy.js";let o=0;const i=e=>`${e}-editor-${o++}`,s=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:i}=this;if(e.disabled=!0,i.innerHTML="",!s.has(t)){const e=URL.createObjectURL(new Blob([""])),o=r.call(new n(null,a),e,{type:this.interpreter}),{sync:i}=o,{promise:c,resolve:l}=Promise.withResolvers();s.set(t,c),i.revoke=()=>{URL.revokeObjectURL(e),l(o)}}s.get(t).then((t=>{t.onerror=({error:e})=>{i.innerHTML+=`<span style='color:red'>${e.message||e}</span>\n`,console.error(e)};const r=()=>{e.disabled=!1},{sync:n}=t;n.write=e=>{i.innerText+=`${e}\n`},n.writeErr=e=>{i.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=`${i(e)}-output`,t})(t);return r.append(n,o),[r,o]},u=async(e,r,n)=>{const[{basicSetup:o,EditorView:s},{Compartment:a},{python:l},{indentUnit:u},{keymap:m},{defaultKeymap:p}]=await Promise.all([import("./codemirror-Maf5R0Dz.js"),import("./codemirror_state-W084kUeH.js"),import("./codemirror_lang-python-FADyYnPB.js"),import("./codemirror_language-xy4t5bF6.js").then((function(e){return e.x})),import("./codemirror_view-8wK3J563.js").then((function(e){return e.q})),import("./codemirror_commands-bA0DvCyD.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=i(r)),v.hasAttribute("exec-id")||v.setAttribute("exec-id",0),v.hasAttribute("root")||v.setAttribute("root",v.id);const f=`${n}-${e.getAttribute("env")||i(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 s({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;const p=()=>{m=0,y()},y=async()=>{if(!m){m=setTimeout(p,250);for(const[t,r]of e){const e=`script[type="${t}-editor"]`;for(const n of document.querySelectorAll(e))n.type+="-active",await u(n,t,r)}}};new MutationObserver(y).observe(document,{childList:!0,subtree:!0});var v=y();export{v as default};
2
- //# sourceMappingURL=py-editor-9M31cFPh.js.map
1
+ import{T as e,d as t,X as r,H as n}from"./core-14p8E60X.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-Maf5R0Dz.js"),import("./codemirror_state-W084kUeH.js"),import("./codemirror_lang-python-FADyYnPB.js"),import("./codemirror_language-xy4t5bF6.js").then((function(e){return e.x})),import("./codemirror_view-8wK3J563.js").then((function(e){return e.q})),import("./codemirror_commands-bA0DvCyD.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-d8hnd4Gu.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"py-editor-9M31cFPh.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// 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\n script.type += \"-active\";\n await init(script, type, interpreter);\n }\n }\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","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,gB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,CACV,GAIC8B,EAAWlC,EAAQ+E,KAAKL,IACvB1B,EAAQ5C,GAAU2C,EAAWb,EAAUlD,GAC9CgE,EAAOgC,QAAQ9E,IAAMiD,EAAOsB,aAAa,OAASvE,EAAMe,EAExD,MACMgE,EADajC,EAAOoB,cAAc,IAAIpF,wBAClBkG,aAAa,CAAEC,KAAM,SAE/CF,EAAO1E,UAAY,0CAEnB2D,EAAOkB,YAAYpC,GAEnB,MAAM6B,EAAMQ,EAAOlC,EAAOmC,aAAaC,OAGjCC,EAAc,UAAUC,KAAKZ,GAAOa,OAAOC,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,EAGd,MAAMC,EAAe,KACjBD,EAAU,EACVE,GAAU,EAIRA,EAAWrG,UACb,IAAImG,EAAJ,CACAA,EAAUG,WAAWF,EAAc,KACnC,IAAK,MAAOnH,EAAMiC,KAAgBqF,EAAO,CACrC,MAAMtC,EAAW,gBAAgBhF,aACjC,IAAK,MAAMmE,KAAUf,SAASmE,iBAAiBvC,GAE3Cb,EAAOnE,MAAQ,gBACTkE,EAAKC,EAAQnE,EAAMiC,EAEhC,CATmB,CASnB,EAGL,IAAIuF,iBAAiBJ,GAAUK,QAAQrE,SAAU,CAC7CsE,WAAW,EACXC,SAAS,IAIb,IAAAC,EAAeR"}
1
+ {"version":3,"file":"py-editor-d8hnd4Gu.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,EA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,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,2 +1,2 @@
1
- import{T as e,e as t,a as r}from"./core-_MDTi7dy.js";import{notify as n}from"./error-yavCjy9g.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-oMtvSdlI.js.map
1
+ import{T as e,e as t,a as r}from"./core-14p8E60X.js";import{notify as n}from"./error-tt9AxwDf.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-HcALwKhy.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"py-terminal-oMtvSdlI.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","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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-HcALwKhy.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,E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2
2
  "name": "@pyscript/core",
3
- "version": "0.3.20",
3
+ "version": "0.3.22",
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.6.15",
45
+ "polyscript": "^0.6.16",
46
46
  "sticky-module": "^0.1.1",
47
47
  "to-json-callback": "^0.1.1",
48
48
  "type-checked-collections": "^0.1.7"
@@ -200,6 +200,9 @@ const init = async (script, type, interpreter) => {
200
200
  // avoid too greedy MutationObserver operations at distance
201
201
  let timeout = 0;
202
202
 
203
+ // avoid delayed initialization
204
+ let queue = Promise.resolve();
205
+
203
206
  // reset interval value then check for new scripts
204
207
  const resetTimeout = () => {
205
208
  timeout = 0;
@@ -213,11 +216,14 @@ const pyEditor = async () => {
213
216
  for (const [type, interpreter] of TYPES) {
214
217
  const selector = `script[type="${type}-editor"]`;
215
218
  for (const script of document.querySelectorAll(selector)) {
216
- // avoid any further bootstrap
219
+ // avoid any further bootstrap by changing the type as active
217
220
  script.type += "-active";
218
- await init(script, type, interpreter);
221
+ // don't await in here or multiple calls might happen
222
+ // while the first script is being initialized
223
+ queue = queue.then(() => init(script, type, interpreter));
219
224
  }
220
225
  }
226
+ return queue;
221
227
  };
222
228
 
223
229
  new MutationObserver(pyEditor).observe(document, {
@@ -8,6 +8,7 @@ export default {
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
- "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\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"
11
+ "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"
12
13
  }
13
14
  };
@@ -0,0 +1,95 @@
1
+ from pyodide.ffi import to_js
2
+ from pyscript import window
3
+
4
+
5
+ class Device:
6
+ """Device represents a media input or output device, such as a microphone,
7
+ camera, or headset.
8
+ """
9
+
10
+ def __init__(self, device):
11
+ self._js = device
12
+
13
+ @property
14
+ def id(self):
15
+ return self._js.deviceId
16
+
17
+ @property
18
+ def group(self):
19
+ return self._js.groupId
20
+
21
+ @property
22
+ def kind(self):
23
+ return self._js.kind
24
+
25
+ @property
26
+ def label(self):
27
+ return self._js.label
28
+
29
+ def __getitem__(self, key):
30
+ return getattr(self, key)
31
+
32
+ @classmethod
33
+ async def load(cls, audio=False, video=True):
34
+ """Load the device stream."""
35
+ options = window.Object.new()
36
+ options.audio = audio
37
+ if isinstance(video, bool):
38
+ options.video = video
39
+ else:
40
+ # TODO: Think this can be simplified but need to check it on the pyodide side
41
+
42
+ # TODO: this is pyodide specific. shouldn't be!
43
+ options.video = window.Object.new()
44
+ for k in video:
45
+ setattr(
46
+ options.video,
47
+ k,
48
+ to_js(video[k], dict_converter=window.Object.fromEntries),
49
+ )
50
+
51
+ stream = await window.navigator.mediaDevices.getUserMedia(options)
52
+ return stream
53
+
54
+ async def get_stream(self):
55
+ key = self.kind.replace("input", "").replace("output", "")
56
+ options = {key: {"deviceId": {"exact": self.id}}}
57
+
58
+ return await self.load(**options)
59
+
60
+
61
+ async def list_devices() -> list[dict]:
62
+ """
63
+ Return the list of the currently available media input and output devices,
64
+ such as microphones, cameras, headsets, and so forth.
65
+
66
+ Output:
67
+
68
+ list(dict) - list of dictionaries representing the available media devices.
69
+ Each dictionary has the following keys:
70
+ * deviceId: a string that is an identifier for the represented device
71
+ that is persisted across sessions. It is un-guessable by other
72
+ applications and unique to the origin of the calling application.
73
+ It is reset when the user clears cookies (for Private Browsing, a
74
+ different identifier is used that is not persisted across sessions).
75
+
76
+ * groupId: a string that is a group identifier. Two devices have the same
77
+ group identifier if they belong to the same physical device — for
78
+ example a monitor with both a built-in camera and a microphone.
79
+
80
+ * kind: an enumerated value that is either "videoinput", "audioinput"
81
+ or "audiooutput".
82
+
83
+ * label: a string describing this device (for example "External USB
84
+ Webcam").
85
+
86
+ Note: the returned list will omit any devices that are blocked by the document
87
+ Permission Policy: microphone, camera, speaker-selection (for output devices),
88
+ and so on. Access to particular non-default devices is also gated by the
89
+ Permissions API, and the list will omit devices for which the user has not
90
+ granted explicit permission.
91
+ """
92
+ # https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices
93
+ return [
94
+ Device(obj) for obj in await window.navigator.mediaDevices.enumerateDevices()
95
+ ]
@@ -204,6 +204,91 @@ class Element(BaseElement):
204
204
  def show_me(self):
205
205
  self._js.scrollIntoView()
206
206
 
207
+ def snap(
208
+ self,
209
+ to: BaseElement | str = None,
210
+ width: int | None = None,
211
+ height: int | None = None,
212
+ ):
213
+ """
214
+ Captures a snapshot of a video element. (Only available for video elements)
215
+
216
+ Inputs:
217
+
218
+ * to: element where to save the snapshot of the video frame to
219
+ * width: width of the image
220
+ * height: height of the image
221
+
222
+ Output:
223
+ (Element) canvas element where the video frame snapshot was drawn into
224
+ """
225
+ if self._js.tagName != "VIDEO":
226
+ raise AttributeError("Snap method is only available for video Elements")
227
+
228
+ if to is None:
229
+ canvas = self.create("canvas")
230
+ if width is None:
231
+ width = self._js.width
232
+ if height is None:
233
+ height = self._js.height
234
+ canvas._js.width = width
235
+ canvas._js.height = height
236
+
237
+ elif isistance(to, Element):
238
+ if to._js.tagName != "CANVAS":
239
+ raise TypeError("Element to snap to must a canvas.")
240
+ canvas = to
241
+ elif getattr(to, "tagName", "") == "CANVAS":
242
+ canvas = Element(to)
243
+ elif isinstance(to, str):
244
+ canvas = pydom[to][0]
245
+ if canvas._js.tagName != "CANVAS":
246
+ raise TypeError("Element to snap to must a be canvas.")
247
+
248
+ canvas.draw(self, width, height)
249
+
250
+ return canvas
251
+
252
+ def download(self, filename: str = "snapped.png") -> None:
253
+ """Download the current element (only available for canvas elements) with the filename
254
+ provided in input.
255
+
256
+ Inputs:
257
+ * filename (str): name of the file being downloaded
258
+
259
+ Output:
260
+ None
261
+ """
262
+ if self._js.tagName != "CANVAS":
263
+ raise AttributeError(
264
+ "The download method is only available for canvas Elements"
265
+ )
266
+
267
+ link = self.create("a")
268
+ link._js.download = filename
269
+ link._js.href = self._js.toDataURL()
270
+ link._js.click()
271
+
272
+ def draw(self, what, width, height):
273
+ """Draw `what` on the current element (only available for canvas elements).
274
+
275
+ Inputs:
276
+
277
+ * what (canvas image source): An element to draw into the context. The specification permits any canvas
278
+ image source, specifically, an HTMLImageElement, an SVGImageElement, an HTMLVideoElement,
279
+ an HTMLCanvasElement, an ImageBitmap, an OffscreenCanvas, or a VideoFrame.
280
+ """
281
+ if self._js.tagName != "CANVAS":
282
+ raise AttributeError(
283
+ "The draw method is only available for canvas Elements"
284
+ )
285
+
286
+ if isinstance(what, Element):
287
+ what = what._js
288
+
289
+ # https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage
290
+ self._js.getContext("2d").drawImage(what, 0, 0, width, height)
291
+
207
292
 
208
293
  class OptionsProxy:
209
294
  """This class represents the options of a select element. It
@@ -7,6 +7,7 @@ declare namespace _default {
7
7
  "util.py": string;
8
8
  };
9
9
  let pyweb: {
10
+ "media.py": string;
10
11
  "pydom.py": string;
11
12
  };
12
13
  }