@pyscript/core 0.6.7 → 0.6.9

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.
Files changed (81) hide show
  1. package/dist/codemirror-1dOfKU91.js +1832 -0
  2. package/dist/{codemirror-BFaBdIfQ.js.map → codemirror-1dOfKU91.js.map} +1 -1
  3. package/dist/codemirror_commands-CKMxnUcp.js +1714 -0
  4. package/dist/codemirror_commands-CKMxnUcp.js.map +1 -0
  5. package/dist/codemirror_lang-python-D9DYtDWr.js +2462 -0
  6. package/dist/{codemirror_lang-python-DvjhpaK2.js.map → codemirror_lang-python-D9DYtDWr.js.map} +1 -1
  7. package/dist/codemirror_language-B5lTPv2c.js +5337 -0
  8. package/dist/{codemirror_language-4kk4Aqm3.js.map → codemirror_language-B5lTPv2c.js.map} +1 -1
  9. package/dist/codemirror_state-n1sFh2hh.js +3930 -0
  10. package/dist/{codemirror_state-1d1uncXx.js.map → codemirror_state-n1sFh2hh.js.map} +1 -1
  11. package/dist/codemirror_view-1a1gCrKZ.js +11428 -0
  12. package/dist/{codemirror_view-aIuSN42d.js.map → codemirror_view-1a1gCrKZ.js.map} +1 -1
  13. package/dist/core-D2ytnMSk.js +4349 -0
  14. package/dist/core-D2ytnMSk.js.map +1 -0
  15. package/dist/core.css +75 -1
  16. package/dist/core.js +1 -1
  17. package/dist/deprecations-manager-Cf_aFUPK.js +29 -0
  18. package/dist/{deprecations-manager-BWDz_-4h.js.map → deprecations-manager-Cf_aFUPK.js.map} +1 -1
  19. package/dist/donkey-Cc8svH2Q.js +170 -0
  20. package/dist/{donkey-DvIAJuTW.js.map → donkey-Cc8svH2Q.js.map} +1 -1
  21. package/dist/error-DWoeKPDI.js +59 -0
  22. package/dist/{error-CVKnHrMr.js.map → error-DWoeKPDI.js.map} +1 -1
  23. package/dist/index-BVFrv_QY.js +1911 -0
  24. package/dist/{index-DqgFLybq.js.map → index-BVFrv_QY.js.map} +1 -1
  25. package/dist/mpy-CQiuZcjW.js +255 -0
  26. package/dist/{mpy-DoOh7bKP.js.map → mpy-CQiuZcjW.js.map} +1 -1
  27. package/dist/py-BgH4mprx.js +182 -0
  28. package/dist/{py-D401PjM8.js.map → py-BgH4mprx.js.map} +1 -1
  29. package/dist/py-editor-Dzsa3rsF.js +433 -0
  30. package/dist/{py-editor-Dxs1clgy.js.map → py-editor-Dzsa3rsF.js.map} +1 -1
  31. package/dist/py-terminal-BX_wPoTi.js +61 -0
  32. package/dist/{py-terminal-eUGMSqwz.js.map → py-terminal-BX_wPoTi.js.map} +1 -1
  33. package/dist/storage.js +421 -1
  34. package/dist/storage.js.map +1 -1
  35. package/dist/toml-CkEFU7ly.js +103 -0
  36. package/dist/{toml-DiUM0_qs.js.map → toml-CkEFU7ly.js.map} +1 -1
  37. package/dist/toml-DTuPg5as.js +5 -0
  38. package/dist/toml-DTuPg5as.js.map +1 -0
  39. package/dist/xterm-eU6F6YKE.js +10 -0
  40. package/dist/xterm-eU6F6YKE.js.map +1 -0
  41. package/dist/xterm-readline-C7HDczqS.js +501 -0
  42. package/dist/xterm-readline-C7HDczqS.js.map +1 -0
  43. package/dist/xterm_addon-fit-Cotzxdkz.js +10 -0
  44. package/dist/xterm_addon-fit-Cotzxdkz.js.map +1 -0
  45. package/dist/xterm_addon-web-links-DoNfCjeX.js +10 -0
  46. package/dist/xterm_addon-web-links-DoNfCjeX.js.map +1 -0
  47. package/dist/zip-Cj6c-tjp.js +13 -0
  48. package/dist/zip-Cj6c-tjp.js.map +1 -0
  49. package/package.json +5 -5
  50. package/src/core.js +2 -2
  51. package/src/stdlib/pyscript.js +13 -13
  52. package/dist/codemirror-BFaBdIfQ.js +0 -2
  53. package/dist/codemirror_commands-CvnouHng.js +0 -2
  54. package/dist/codemirror_commands-CvnouHng.js.map +0 -1
  55. package/dist/codemirror_lang-python-DvjhpaK2.js +0 -2
  56. package/dist/codemirror_language-4kk4Aqm3.js +0 -2
  57. package/dist/codemirror_state-1d1uncXx.js +0 -2
  58. package/dist/codemirror_view-aIuSN42d.js +0 -2
  59. package/dist/core-S0XBQFwV.js +0 -2
  60. package/dist/core-S0XBQFwV.js.map +0 -1
  61. package/dist/deprecations-manager-BWDz_-4h.js +0 -2
  62. package/dist/donkey-DvIAJuTW.js +0 -2
  63. package/dist/error-CVKnHrMr.js +0 -2
  64. package/dist/index-DqgFLybq.js +0 -2
  65. package/dist/mpy-DoOh7bKP.js +0 -2
  66. package/dist/py-D401PjM8.js +0 -2
  67. package/dist/py-editor-Dxs1clgy.js +0 -2
  68. package/dist/py-terminal-eUGMSqwz.js +0 -2
  69. package/dist/toml-CvAfdf9_.js +0 -3
  70. package/dist/toml-CvAfdf9_.js.map +0 -1
  71. package/dist/toml-DiUM0_qs.js +0 -3
  72. package/dist/xterm-BY7uk_OU.js +0 -2
  73. package/dist/xterm-BY7uk_OU.js.map +0 -1
  74. package/dist/xterm-readline-CZfBw7ic.js +0 -2
  75. package/dist/xterm-readline-CZfBw7ic.js.map +0 -1
  76. package/dist/xterm_addon-fit--gyF3PcZ.js +0 -2
  77. package/dist/xterm_addon-fit--gyF3PcZ.js.map +0 -1
  78. package/dist/xterm_addon-web-links-Cnej-nJ6.js +0 -2
  79. package/dist/xterm_addon-web-links-Cnej-nJ6.js.map +0 -1
  80. package/dist/zip-Bf48tRr5.js +0 -2
  81. package/dist/zip-Bf48tRr5.js.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pyscript/core",
3
- "version": "0.6.7",
3
+ "version": "0.6.9",
4
4
  "type": "module",
5
5
  "description": "PyScript",
6
6
  "module": "./index.js",
@@ -63,13 +63,13 @@
63
63
  "add-promise-listener": "^0.1.3",
64
64
  "basic-devtools": "^0.1.6",
65
65
  "polyscript": "^0.16.3",
66
- "sabayon": "^0.5.2",
66
+ "sabayon": "^0.6.0",
67
67
  "sticky-module": "^0.1.1",
68
68
  "to-json-callback": "^0.1.1",
69
69
  "type-checked-collections": "^0.1.7"
70
70
  },
71
71
  "devDependencies": {
72
- "@codemirror/commands": "^6.7.0",
72
+ "@codemirror/commands": "^6.7.1",
73
73
  "@codemirror/lang-python": "^6.1.6",
74
74
  "@codemirror/language": "^6.10.3",
75
75
  "@codemirror/state": "^6.4.1",
@@ -81,11 +81,11 @@
81
81
  "@webreflection/toml-j0.4": "^1.1.3",
82
82
  "@xterm/addon-fit": "^0.10.0",
83
83
  "@xterm/addon-web-links": "^0.11.0",
84
- "bun": "^1.1.30",
84
+ "bun": "^1.1.33",
85
85
  "chokidar": "^4.0.1",
86
86
  "codedent": "^0.1.2",
87
87
  "codemirror": "^6.0.1",
88
- "eslint": "^9.12.0",
88
+ "eslint": "^9.13.0",
89
89
  "flatted": "^3.3.1",
90
90
  "rollup": "^4.24.0",
91
91
  "rollup-plugin-postcss": "^4.0.2",
package/src/core.js CHANGED
@@ -26,7 +26,7 @@ import bootstrapNodeAndPlugins from "./plugins-helper.js";
26
26
  import { ErrorCode } from "./exceptions.js";
27
27
  import { robustFetch as fetch, getText } from "./fetch.js";
28
28
  import {
29
- hooks,
29
+ hooks as coreHooks,
30
30
  main,
31
31
  worker,
32
32
  codeFor,
@@ -83,7 +83,7 @@ const [
83
83
  ] = stickyModule("@pyscript/core", {
84
84
  PyWorker,
85
85
  MPWorker,
86
- hooks,
86
+ hooks: coreHooks,
87
87
  config: {},
88
88
  whenDefined,
89
89
  });
@@ -1,18 +1,18 @@
1
1
  // ⚠️ This file is an artifact: DO NOT MODIFY
2
2
  export default {
3
3
  "pyscript": {
4
- "__init__.py": "from polyscript import lazy_py_modules as py_import\nfrom pyscript.display import HTML,display\nfrom pyscript.fetch import fetch\nfrom pyscript.magic_js import RUNNING_IN_WORKER,PyWorker,config,current_target,document,js_import,js_modules,sync,window\nfrom pyscript.storage import Storage,storage\nfrom pyscript.websocket import WebSocket\nif not RUNNING_IN_WORKER:from pyscript.workers import create_named_worker,workers\ntry:from pyscript.event_handling import when\nexcept:from pyscript.util import NotSupported;when=NotSupported('pyscript.when','pyscript.when currently not available with this interpreter')",
5
- "display.py": "_L='_repr_mimebundle_'\n_K='image/svg+xml'\n_J='application/json'\n_I='__repr__'\n_H='savefig'\n_G='text/html'\n_F='image/jpeg'\n_E='application/javascript'\n_D='utf-8'\n_C='text/plain'\n_B='image/png'\n_A=None\nimport base64,html,io,re\nfrom pyscript.magic_js import current_target,document,window\n_MIME_METHODS={_H:_B,'_repr_javascript_':_E,'_repr_json_':_J,'_repr_latex':'text/latex','_repr_png_':_B,'_repr_jpeg_':_F,'_repr_pdf_':'application/pdf','_repr_svg_':_K,'_repr_markdown_':'text/markdown','_repr_html_':_G,_I:_C}\ndef _render_image(mime,value,meta):\n\tA=value\n\tif isinstance(A,bytes):A=base64.b64encode(A).decode(_D)\n\tB=re.compile('^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$')\n\tif len(A)>0 and not B.match(A):A=base64.b64encode(A.encode(_D)).decode(_D)\n\tC=f\"data:{mime};charset=utf-8;base64,{A}\";D=' '.join(['{k}=\"{v}\"'for(A,B)in meta.items()]);return f'<img src=\"{C}\" {D}></img>'\ndef _identity(value,meta):return value\n_MIME_RENDERERS={_C:html.escape,_G:_identity,_B:lambda value,meta:_render_image(_B,value,meta),_F:lambda value,meta:_render_image(_F,value,meta),_K:_identity,_J:_identity,_E:lambda value,meta:f\"<script>{value}<\\\\/script>\"}\nclass HTML:\n\tdef __init__(A,html):A._html=html\n\tdef _repr_html_(A):return A._html\ndef _eval_formatter(obj,print_method):\n\tB=obj;A=print_method\n\tif A==_I:return repr(B)\n\telif hasattr(B,A):\n\t\tif A==_H:C=io.BytesIO();B.savefig(C,format='png');C.seek(0);return base64.b64encode(C.read()).decode(_D)\n\t\treturn getattr(B,A)()\n\telif A==_L:return{},{}\ndef _format_mime(obj):\n\tC=obj\n\tif isinstance(C,str):return html.escape(C),_C\n\tD=_eval_formatter(C,_L)\n\tif isinstance(D,tuple):E,I=D\n\telse:E=D\n\tA,F=_A,[]\n\tfor(H,B)in _MIME_METHODS.items():\n\t\tif B in E:A=E[B]\n\t\telse:A=_eval_formatter(C,H)\n\t\tif A is _A:continue\n\t\telif B not in _MIME_RENDERERS:F.append(B);continue\n\t\tbreak\n\tif A is _A:\n\t\tif F:window.console.warn(f\"Rendered object requested unavailable MIME renderers: {F}\")\n\t\tA=repr(A);B=_C\n\telif isinstance(A,tuple):A,G=A\n\telse:G={}\n\treturn _MIME_RENDERERS[B](A,G),B\ndef _write(element,value,append=False):\n\tB=element;C,D=_format_mime(value)\n\tif C=='\\\\n':return\n\tif append:A=document.createElement('div');B.append(A)\n\telse:\n\t\tA=B.lastElementChild\n\t\tif A is _A:A=B\n\tif D in(_E,_G):E=document.createRange().createContextualFragment(C);A.append(E)\n\telse:A.innerHTML=C\ndef display(*D,target=_A,append=True):\n\tC=append;A=target\n\tif A is _A:A=current_target()\n\telif not isinstance(A,str):raise TypeError(f\"target must be str or None, not {A.__class__.__name__}\")\n\telif A=='':raise ValueError('Cannot have an empty target')\n\telif A.startswith('#'):A=A[1:]\n\tB=document.getElementById(A)\n\tif B is _A:raise ValueError(f\"Invalid selector with id={A}. Cannot be found in the page.\")\n\tif B.tagName=='SCRIPT'and hasattr(B,'target'):B=B.target\n\tfor E in D:\n\t\tif not C:B.replaceChildren()\n\t\t_write(B,E,append=C)",
6
- "event_handling.py": "import inspect\ntry:from pyodide.ffi.wrappers import add_event_listener\nexcept ImportError:\n\tdef add_event_listener(el,event_type,func):el.addEventListener(event_type,func)\nfrom pyscript.magic_js import document\ndef when(event_type=None,selector=None):\n\tA=selector\n\tdef B(func):\n\t\tB=func;from pyscript.web import Element as E,ElementCollection as F\n\t\tif isinstance(A,str):C=document.querySelectorAll(A)\n\t\telif isinstance(A,E):C=[A._dom_element]\n\t\telif isinstance(A,F):C=[A._dom_element for A in A]\n\t\telif isinstance(A,list):C=A\n\t\telse:C=[A]\n\t\ttry:\n\t\t\tG=inspect.signature(B)\n\t\t\tif not G.parameters:\n\t\t\t\tif inspect.iscoroutinefunction(B):\n\t\t\t\t\tasync def D(*A,**C):await B()\n\t\t\t\telse:\n\t\t\t\t\tdef D(*A,**C):B()\n\t\t\telse:D=B\n\t\texcept AttributeError:\n\t\t\tdef D(*C,**D):\n\t\t\t\ttry:return B(*C,**D)\n\t\t\t\texcept TypeError as A:\n\t\t\t\t\tif'takes'in str(A)and'positional arguments'in str(A):return B()\n\t\t\t\t\traise\n\t\tfor H in C:add_event_listener(H,event_type,D)\n\t\treturn B\n\treturn B",
7
- "fetch.py": "import json,js\nfrom pyscript.util import as_bytearray\nclass _Response:\n\tdef __init__(A,response):A._response=response\n\tdef __getattr__(A,attr):return getattr(A._response,attr)\n\tasync def arrayBuffer(B):\n\t\tA=await B._response.arrayBuffer()\n\t\tif hasattr(A,'to_py'):return A.to_py()\n\t\treturn memoryview(as_bytearray(A))\n\tasync def blob(A):return await A._response.blob()\n\tasync def bytearray(A):B=await A._response.arrayBuffer();return as_bytearray(B)\n\tasync def json(A):return json.loads(await A.text())\n\tasync def text(A):return await A._response.text()\nclass _DirectResponse:\n\t@staticmethod\n\tdef setup(promise,response):A=promise;A._response=_Response(response);return A._response\n\tdef __init__(B,promise):A=promise;B._promise=A;A._response=None;A.arrayBuffer=B.arrayBuffer;A.blob=B.blob;A.bytearray=B.bytearray;A.json=B.json;A.text=B.text\n\tasync def _response(A):\n\t\tif not A._promise._response:await A._promise\n\t\treturn A._promise._response\n\tasync def arrayBuffer(A):B=await A._response();return await B.arrayBuffer()\n\tasync def blob(A):B=await A._response();return await B.blob()\n\tasync def bytearray(A):B=await A._response();return await B.bytearray()\n\tasync def json(A):B=await A._response();return await B.json()\n\tasync def text(A):B=await A._response();return await B.text()\ndef fetch(url,**B):C=js.JSON.parse(json.dumps(B));D=lambda response,*B:_DirectResponse.setup(A,response);A=js.fetch(url,C).then(D);_DirectResponse(A);return A",
8
- "ffi.py": "try:\n\timport js;from pyodide.ffi import create_proxy as _cp,to_js as _py_tjs;from_entries=js.Object.fromEntries\n\tdef _tjs(value,**A):\n\t\tB='dict_converter'\n\t\tif not hasattr(A,B):A[B]=from_entries\n\t\treturn _py_tjs(value,**A)\nexcept:from jsffi import create_proxy as _cp;from jsffi import to_js as _tjs\ncreate_proxy=_cp\nto_js=_tjs",
9
- "flatted.py": "import json as _json\nclass _Known:\n\tdef __init__(A):A.key=[];A.value=[]\nclass _String:\n\tdef __init__(A,value):A.value=value\ndef _array_keys(value):\n\tA=[];B=0\n\tfor C in value:A.append(B);B+=1\n\treturn A\ndef _object_keys(value):\n\tA=[]\n\tfor B in value:A.append(B)\n\treturn A\ndef _is_array(value):A=value;return isinstance(A,list)or isinstance(A,tuple)\ndef _is_object(value):return isinstance(value,dict)\ndef _is_string(value):return isinstance(value,str)\ndef _index(known,input,value):B=value;A=known;input.append(B);C=str(len(input)-1);A.key.append(B);A.value.append(C);return C\ndef _loop(keys,input,known,output):\n\tA=output\n\tfor B in keys:\n\t\tC=A[B]\n\t\tif isinstance(C,_String):_ref(B,input[int(C.value)],input,known,A)\n\treturn A\ndef _ref(key,value,input,known,output):\n\tB=known;A=value\n\tif _is_array(A)and not A in B:B.append(A);A=_loop(_array_keys(A),input,B,A)\n\telif _is_object(A)and not A in B:B.append(A);A=_loop(_object_keys(A),input,B,A)\n\toutput[key]=A\ndef _relate(known,input,value):\n\tB=known;A=value\n\tif _is_string(A)or _is_array(A)or _is_object(A):\n\t\ttry:return B.value[B.key.index(A)]\n\t\texcept:return _index(B,input,A)\n\treturn A\ndef _transform(known,input,value):\n\tB=known;A=value\n\tif _is_array(A):\n\t\tC=[]\n\t\tfor F in A:C.append(_relate(B,input,F))\n\t\treturn C\n\tif _is_object(A):\n\t\tD={}\n\t\tfor E in A:D[E]=_relate(B,input,A[E])\n\t\treturn D\n\treturn A\ndef _wrap(value):\n\tA=value\n\tif _is_string(A):return _String(A)\n\tif _is_array(A):\n\t\tB=0\n\t\tfor D in A:A[B]=_wrap(D);B+=1\n\telif _is_object(A):\n\t\tfor C in A:A[C]=_wrap(A[C])\n\treturn A\ndef parse(value,*C,**D):\n\tA=value;E=_json.loads(A,*C,**D);B=[]\n\tfor A in E:B.append(_wrap(A))\n\tinput=[]\n\tfor A in B:\n\t\tif isinstance(A,_String):input.append(A.value)\n\t\telse:input.append(A)\n\tA=input[0]\n\tif _is_array(A):return _loop(_array_keys(A),input,[A],A)\n\tif _is_object(A):return _loop(_object_keys(A),input,[A],A)\n\treturn A\ndef stringify(value,*D,**E):\n\tB=_Known();input=[];C=[];A=int(_index(B,input,value))\n\twhile A<len(input):C.append(_transform(B,input,input[A]));A+=1\n\treturn _json.dumps(C,*D,**E)",
10
- "magic_js.py": "import json,sys,js as globalThis\nfrom polyscript import config as _config,js_modules\nfrom pyscript.util import NotSupported\nRUNNING_IN_WORKER=not hasattr(globalThis,'document')\nconfig=json.loads(globalThis.JSON.stringify(_config))\nif'MicroPython'in sys.version:config['type']='mpy'\nelse:config['type']='py'\nclass JSModule:\n\tdef __init__(A,name):A.name=name\n\tdef __getattr__(B,field):\n\t\tA=field\n\t\tif not A.startswith('_'):return getattr(getattr(js_modules,B.name),A)\nfor name in globalThis.Reflect.ownKeys(js_modules):sys.modules[f\"pyscript.js_modules.{name}\"]=JSModule(name)\nsys.modules['pyscript.js_modules']=js_modules\nif RUNNING_IN_WORKER:\n\timport polyscript;PyWorker=NotSupported('pyscript.PyWorker','pyscript.PyWorker works only when running in the main thread')\n\ttry:import js;window=polyscript.xworker.window;document=window.document;js.document=document;js_import=window.Function('return (...urls) => Promise.all(urls.map((url) => import(url)))')()\n\texcept:message='Unable to use `window` or `document` -> https://docs.pyscript.net/latest/faq/#sharedarraybuffer';globalThis.console.warn(message);window=NotSupported('pyscript.window',message);document=NotSupported('pyscript.document',message);js_import=None\n\tsync=polyscript.xworker.sync\n\tdef current_target():return polyscript.target\nelse:\n\timport _pyscript;from _pyscript import PyWorker,js_import;window=globalThis;document=globalThis.document;sync=NotSupported('pyscript.sync','pyscript.sync works only when running in a worker')\n\tdef current_target():return _pyscript.target",
11
- "media.py": "from pyscript import window\nfrom pyscript.ffi import to_js\nclass Device:\n\tdef __init__(A,device):A._dom_element=device\n\t@property\n\tdef id(self):return self._dom_element.deviceId\n\t@property\n\tdef group(self):return self._dom_element.groupId\n\t@property\n\tdef kind(self):return self._dom_element.kind\n\t@property\n\tdef label(self):return self._dom_element.label\n\tdef __getitem__(A,key):return getattr(A,key)\n\t@classmethod\n\tasync def load(E,audio=False,video=True):\n\t\tB=video;A=window.Object.new();A.audio=audio\n\t\tif isinstance(B,bool):A.video=B\n\t\telse:\n\t\t\tA.video=window.Object.new()\n\t\t\tfor C in B:setattr(A.video,C,to_js(B[C]))\n\t\tD=await window.navigator.mediaDevices.getUserMedia(A);return D\n\tasync def get_stream(A):B=A.kind.replace('input','').replace('output','');C={B:{'deviceId':{'exact':A.id}}};return await A.load(**C)\nasync def list_devices():return[Device(A)for A in await window.navigator.mediaDevices.enumerateDevices()]",
12
- "storage.py": "_C='memoryview'\n_B='bytearray'\n_A='generic'\nfrom polyscript import storage as _storage\nfrom pyscript.flatted import parse as _parse\nfrom pyscript.flatted import stringify as _stringify\ndef _to_idb(value):\n\tA=value\n\tif A is None:return _stringify(['null',0])\n\tif isinstance(A,(bool,float,int,str,list,dict,tuple)):return _stringify([_A,A])\n\tif isinstance(A,bytearray):return _stringify([_B,[A for A in A]])\n\tif isinstance(A,memoryview):return _stringify([_C,[A for A in A]])\n\traise TypeError(f\"Unexpected value: {A}\")\ndef _from_idb(value):\n\tC=value;A,B=_parse(C)\n\tif A=='null':return\n\tif A==_A:return B\n\tif A==_B:return bytearray(B)\n\tif A==_C:return memoryview(bytearray(B))\n\treturn C\nclass Storage(dict):\n\tdef __init__(B,store):A=store;super().__init__({A:_from_idb(B)for(A,B)in A.entries()});B.__store__=A\n\tdef __delitem__(A,attr):A.__store__.delete(attr);super().__delitem__(attr)\n\tdef __setitem__(B,attr,value):A=value;B.__store__.set(attr,_to_idb(A));super().__setitem__(attr,A)\n\tdef clear(A):A.__store__.clear();super().clear()\n\tasync def sync(A):await A.__store__.sync()\nasync def storage(name='',storage_class=Storage):\n\tif not name:raise ValueError('The storage name must be defined')\n\treturn storage_class(await _storage(f\"@pyscript/{name}\"))",
13
- "util.py": "import js\ndef as_bytearray(buffer):\n\tA=js.Uint8Array.new(buffer);B=A.length;C=bytearray(B)\n\tfor D in range(0,B):C[D]=A[D]\n\treturn C\nclass NotSupported:\n\tdef __init__(A,name,error):object.__setattr__(A,'name',name);object.__setattr__(A,'error',error)\n\tdef __repr__(A):return f\"<NotSupported {A.name} [{A.error}]>\"\n\tdef __getattr__(A,attr):raise AttributeError(A.error)\n\tdef __setattr__(A,attr,value):raise AttributeError(A.error)\n\tdef __call__(A,*B):raise TypeError(A.error)",
14
- "web.py": "_A=None\nfrom pyscript import document,when\ndef wrap_dom_element(dom_element):return Element.wrap_dom_element(dom_element)\nclass Element:\n\telement_classes_by_tag_name={}\n\t@classmethod\n\tdef get_tag_name(A):return A.__name__.replace('_','')\n\t@classmethod\n\tdef register_element_classes(B,element_classes):\n\t\tfor A in element_classes:C=A.get_tag_name();B.element_classes_by_tag_name[C]=A\n\t@classmethod\n\tdef unregister_element_classes(A,element_classes):\n\t\tfor B in element_classes:C=B.get_tag_name();A.element_classes_by_tag_name.pop(C,_A)\n\t@classmethod\n\tdef wrap_dom_element(A,dom_element):B=dom_element;C=A.element_classes_by_tag_name.get(B.tagName.lower(),A);return C(dom_element=B)\n\tdef __init__(A,dom_element=_A,classes=_A,style=_A,**B):A._dom_element=dom_element or document.createElement(type(A).get_tag_name());A._classes=Classes(A);A._style=Style(A);A.update(classes=classes,style=style,**B)\n\tdef __eq__(A,obj):return isinstance(obj,Element)and obj._dom_element==A._dom_element\n\tdef __getitem__(B,key):\n\t\tA=key\n\t\tif isinstance(A,int)or isinstance(A,slice):return B.children[A]\n\t\treturn B.find(A)\n\tdef __getattr__(B,name):\n\t\tA=name\n\t\tif A.endswith('_'):A=A[:-1]\n\t\treturn getattr(B._dom_element,A)\n\tdef __setattr__(C,name,value):\n\t\tB=value;A=name\n\t\tif A.startswith('_'):super().__setattr__(A,B)\n\t\telse:\n\t\t\tif A.endswith('_'):A=A[:-1]\n\t\t\tsetattr(C._dom_element,A,B)\n\t@property\n\tdef children(self):return ElementCollection.wrap_dom_elements(self._dom_element.children)\n\t@property\n\tdef classes(self):return self._classes\n\t@property\n\tdef parent(self):\n\t\tif self._dom_element.parentElement is _A:return\n\t\treturn Element.wrap_dom_element(self._dom_element.parentElement)\n\t@property\n\tdef style(self):return self._style\n\tdef append(B,*C):\n\t\tfor A in C:\n\t\t\tif isinstance(A,Element):B._dom_element.appendChild(A._dom_element)\n\t\t\telif isinstance(A,ElementCollection):\n\t\t\t\tfor D in A:B._dom_element.appendChild(D._dom_element)\n\t\t\telif isinstance(A,list)or isinstance(A,tuple):\n\t\t\t\tfor E in A:B.append(E)\n\t\t\telse:\n\t\t\t\ttry:A.tagName;B._dom_element.appendChild(A)\n\t\t\t\texcept AttributeError:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tA.length\n\t\t\t\t\t\tfor F in A:B._dom_element.appendChild(F)\n\t\t\t\t\texcept AttributeError:raise TypeError(f'Element \"{A}\" is a proxy object, \"but not a valid element or a NodeList.')\n\tdef clone(B,clone_id=_A):A=Element.wrap_dom_element(B._dom_element.cloneNode(True));A.id=clone_id;return A\n\tdef find(A,selector):return ElementCollection.wrap_dom_elements(A._dom_element.querySelectorAll(selector))\n\tdef show_me(A):A._dom_element.scrollIntoView()\n\tdef update(A,classes=_A,style=_A,**D):\n\t\tC=style;B=classes\n\t\tif B:A.classes.add(B)\n\t\tif C:A.style.set(**C)\n\t\tfor(E,F)in D.items():setattr(A,E,F)\nclass Classes:\n\tdef __init__(A,element):A._element=element;A._class_list=A._element._dom_element.classList\n\tdef __contains__(A,item):return item in A._class_list\n\tdef __eq__(C,other):\n\t\tA=other\n\t\tif isinstance(A,Classes):B=list(A._class_list)\n\t\telse:\n\t\t\ttry:B=iter(A)\n\t\t\texcept TypeError:return False\n\t\treturn set(C._class_list)==set(B)\n\tdef __iter__(A):return iter(A._class_list)\n\tdef __len__(A):return A._class_list.length\n\tdef __repr__(A):return f\"Classes({\", \".join(A._class_list)})\"\n\tdef __str__(A):return' '.join(A._class_list)\n\tdef add(B,*C):\n\t\tfor A in C:\n\t\t\tif isinstance(A,list):\n\t\t\t\tfor D in A:B.add(D)\n\t\t\telse:B._class_list.add(A)\n\tdef contains(A,class_name):return class_name in A\n\tdef remove(B,*C):\n\t\tfor A in C:\n\t\t\tif isinstance(A,list):\n\t\t\t\tfor D in A:B.remove(D)\n\t\t\telse:B._class_list.remove(A)\n\tdef replace(A,old_class,new_class):A.remove(old_class);A.add(new_class)\n\tdef toggle(A,*C):\n\t\tfor B in C:\n\t\t\tif B in A:A.remove(B)\n\t\t\telse:A.add(B)\nclass HasOptions:\n\t@property\n\tdef options(self):\n\t\tA=self\n\t\tif not hasattr(A,'_options'):A._options=Options(A)\n\t\treturn A._options\nclass Options:\n\tdef __init__(A,element):A._element=element\n\tdef __getitem__(A,key):return A.options[key]\n\tdef __iter__(A):yield from A.options\n\tdef __len__(A):return len(A.options)\n\tdef __repr__(A):return f\"{A.__class__.__name__} (length: {len(A)}) {A.options}\"\n\t@property\n\tdef options(self):return[Element.wrap_dom_element(A)for A in self._element._dom_element.options]\n\t@property\n\tdef selected(self):return self.options[self._element._dom_element.selectedIndex]\n\tdef add(D,value=_A,html=_A,text=_A,before=_A,**B):\n\t\tC=value;A=before\n\t\tif C is not _A:B['value']=C\n\t\tif html is not _A:B['innerHTML']=html\n\t\tif text is not _A:B['text']=text\n\t\tE=option(**B)\n\t\tif A:\n\t\t\tif isinstance(A,Element):A=A._dom_element\n\t\tD._element._dom_element.add(E._dom_element,A)\n\tdef clear(A):\n\t\twhile len(A)>0:A.remove(0)\n\tdef remove(A,index):A._element._dom_element.remove(index)\nclass Style:\n\tdef __init__(A,element):A._element=element;A._style=A._element._dom_element.style\n\tdef __getitem__(A,key):return A._style.getPropertyValue(key)\n\tdef __setitem__(A,key,value):A._style.setProperty(key,value)\n\tdef remove(A,key):A._style.removeProperty(key)\n\tdef set(A,**B):\n\t\tfor(C,D)in B.items():A._element._dom_element.style.setProperty(C,D)\n\t@property\n\tdef visible(self):return self._element._dom_element.style.visibility\n\t@visible.setter\n\tdef visible(self,value):self._element._dom_element.style.visibility=value\nclass ContainerElement(Element):\n\tdef __init__(B,*C,children=_A,dom_element=_A,style=_A,classes=_A,**D):\n\t\tsuper().__init__(dom_element=dom_element,style=style,classes=classes,**D)\n\t\tfor A in list(C)+(children or[]):\n\t\t\tif isinstance(A,Element)or isinstance(A,ElementCollection):B.append(A)\n\t\t\telse:B._dom_element.insertAdjacentHTML('beforeend',A)\n\tdef __iter__(A):yield from A.children\nclass ClassesCollection:\n\tdef __init__(A,collection):A._collection=collection\n\tdef __contains__(A,class_name):\n\t\tfor B in A._collection:\n\t\t\tif class_name in B.classes:return True\n\t\treturn False\n\tdef __eq__(B,other):A=other;return isinstance(A,ClassesCollection)and B._collection==A._collection\n\tdef __iter__(A):\n\t\tfor B in A._all_class_names():yield B\n\tdef __len__(A):return len(A._all_class_names())\n\tdef __repr__(A):return f\"ClassesCollection({repr(A._collection)})\"\n\tdef __str__(A):return' '.join(A._all_class_names())\n\tdef add(A,*B):\n\t\tfor C in A._collection:C.classes.add(*B)\n\tdef contains(A,class_name):return class_name in A\n\tdef remove(A,*B):\n\t\tfor C in A._collection:C.classes.remove(*B)\n\tdef replace(A,old_class,new_class):\n\t\tfor B in A._collection:B.classes.replace(old_class,new_class)\n\tdef toggle(A,*B):\n\t\tfor C in A._collection:C.classes.toggle(*B)\n\tdef _all_class_names(B):\n\t\tA=set()\n\t\tfor C in B._collection:\n\t\t\tfor D in C.classes:A.add(D)\n\t\treturn A\nclass StyleCollection:\n\tdef __init__(A,collection):A._collection=collection\n\tdef __getitem__(A,key):return[A.style[key]for A in A._collection._elements]\n\tdef __setitem__(A,key,value):\n\t\tfor B in A._collection._elements:B.style[key]=value\n\tdef __repr__(A):return f\"StyleCollection({repr(A._collection)})\"\n\tdef remove(A,key):\n\t\tfor B in A._collection._elements:B.style.remove(key)\nclass ElementCollection:\n\t@classmethod\n\tdef wrap_dom_elements(A,dom_elements):return A([Element.wrap_dom_element(A)for A in dom_elements])\n\tdef __init__(A,elements):A._elements=elements;A._classes=ClassesCollection(A);A._style=StyleCollection(A)\n\tdef __eq__(A,obj):return isinstance(obj,ElementCollection)and obj._elements==A._elements\n\tdef __getitem__(B,key):\n\t\tA=key\n\t\tif isinstance(A,int):return B._elements[A]\n\t\telif isinstance(A,slice):return ElementCollection(B._elements[A])\n\t\treturn B.find(A)\n\tdef __iter__(A):yield from A._elements\n\tdef __len__(A):return len(A._elements)\n\tdef __repr__(A):return f\"{A.__class__.__name__} (length: {len(A._elements)}) {A._elements}\"\n\tdef __getattr__(A,name):return[getattr(A,name)for A in A._elements]\n\tdef __setattr__(C,name,value):\n\t\tB=value;A=name\n\t\tif A.startswith('_'):super().__setattr__(A,B)\n\t\telse:\n\t\t\tfor D in C._elements:setattr(D,A,B)\n\t@property\n\tdef classes(self):return self._classes\n\t@property\n\tdef elements(self):return self._elements\n\t@property\n\tdef style(self):return self._style\n\tdef find(B,selector):\n\t\tA=[]\n\t\tfor C in B._elements:A.extend(C.find(selector))\n\t\treturn ElementCollection(A)\nclass a(ContainerElement):0\nclass abbr(ContainerElement):0\nclass address(ContainerElement):0\nclass area(Element):0\nclass article(ContainerElement):0\nclass aside(ContainerElement):0\nclass audio(ContainerElement):0\nclass b(ContainerElement):0\nclass base(Element):0\nclass blockquote(ContainerElement):0\nclass body(ContainerElement):0\nclass br(Element):0\nclass button(ContainerElement):0\nclass canvas(ContainerElement):\n\tdef download(A,filename='snapped.png'):B=a(download=filename,href=A._dom_element.toDataURL());A.append(B);B._dom_element.click()\n\tdef draw(E,what,width=_A,height=_A):\n\t\tC=height;B=width;A=what\n\t\tif isinstance(A,Element):A=A._dom_element\n\t\tD=E._dom_element.getContext('2d')\n\t\tif B or C:D.drawImage(A,0,0,B,C)\n\t\telse:D.drawImage(A,0,0)\nclass caption(ContainerElement):0\nclass cite(ContainerElement):0\nclass code(ContainerElement):0\nclass col(Element):0\nclass colgroup(ContainerElement):0\nclass data(ContainerElement):0\nclass datalist(ContainerElement,HasOptions):0\nclass dd(ContainerElement):0\nclass del_(ContainerElement):0\nclass details(ContainerElement):0\nclass dialog(ContainerElement):0\nclass div(ContainerElement):0\nclass dl(ContainerElement):0\nclass dt(ContainerElement):0\nclass em(ContainerElement):0\nclass embed(Element):0\nclass fieldset(ContainerElement):0\nclass figcaption(ContainerElement):0\nclass figure(ContainerElement):0\nclass footer(ContainerElement):0\nclass form(ContainerElement):0\nclass h1(ContainerElement):0\nclass h2(ContainerElement):0\nclass h3(ContainerElement):0\nclass h4(ContainerElement):0\nclass h5(ContainerElement):0\nclass h6(ContainerElement):0\nclass head(ContainerElement):0\nclass header(ContainerElement):0\nclass hgroup(ContainerElement):0\nclass hr(Element):0\nclass html(ContainerElement):0\nclass i(ContainerElement):0\nclass iframe(ContainerElement):0\nclass img(Element):0\nclass input_(Element):0\nclass ins(ContainerElement):0\nclass kbd(ContainerElement):0\nclass label(ContainerElement):0\nclass legend(ContainerElement):0\nclass li(ContainerElement):0\nclass link(Element):0\nclass main(ContainerElement):0\nclass map_(ContainerElement):0\nclass mark(ContainerElement):0\nclass menu(ContainerElement):0\nclass meta(ContainerElement):0\nclass meter(ContainerElement):0\nclass nav(ContainerElement):0\nclass object_(ContainerElement):0\nclass ol(ContainerElement):0\nclass optgroup(ContainerElement,HasOptions):0\nclass option(ContainerElement):0\nclass output(ContainerElement):0\nclass p(ContainerElement):0\nclass param(ContainerElement):0\nclass picture(ContainerElement):0\nclass pre(ContainerElement):0\nclass progress(ContainerElement):0\nclass q(ContainerElement):0\nclass s(ContainerElement):0\nclass script(ContainerElement):0\nclass section(ContainerElement):0\nclass select(ContainerElement,HasOptions):0\nclass small(ContainerElement):0\nclass source(Element):0\nclass span(ContainerElement):0\nclass strong(ContainerElement):0\nclass style(ContainerElement):0\nclass sub(ContainerElement):0\nclass summary(ContainerElement):0\nclass sup(ContainerElement):0\nclass table(ContainerElement):0\nclass tbody(ContainerElement):0\nclass td(ContainerElement):0\nclass template(ContainerElement):0\nclass textarea(ContainerElement):0\nclass tfoot(ContainerElement):0\nclass th(ContainerElement):0\nclass thead(ContainerElement):0\nclass time(ContainerElement):0\nclass title(ContainerElement):0\nclass tr(ContainerElement):0\nclass track(Element):0\nclass u(ContainerElement):0\nclass ul(ContainerElement):0\nclass var(ContainerElement):0\nclass video(ContainerElement):\n\tdef snap(D,to=_A,width=_A,height=_A):\n\t\tG='CANVAS';F='Element to snap to must be a canvas.';C=height;B=width;A=to;B=B if B is not _A else D.videoWidth;C=C if C is not _A else D.videoHeight\n\t\tif A is _A:A=canvas(width=B,height=C)\n\t\telif isinstance(A,Element):\n\t\t\tif A.tag!='canvas':raise TypeError(F)\n\t\telif getattr(A,'tagName','')==G:A=canvas(dom_element=A)\n\t\telif isinstance(A,str):\n\t\t\tE=document.querySelectorAll(A)\n\t\t\tif E.length==0:raise TypeError('No element with selector {to} to snap to.')\n\t\t\tif E[0].tagName!=G:raise TypeError(F)\n\t\t\tA=canvas(dom_element=E[0])\n\t\tA.draw(D,B,C);return A\nclass wbr(Element):0\nELEMENT_CLASSES=[a,abbr,address,area,article,aside,audio,b,base,blockquote,body,br,button,canvas,caption,cite,code,col,colgroup,data,datalist,dd,del_,details,dialog,div,dl,dt,em,embed,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,i,iframe,img,input_,ins,kbd,label,legend,li,link,main,map_,mark,menu,meta,meter,nav,object_,ol,optgroup,option,output,p,param,picture,pre,progress,q,s,script,section,select,small,source,span,strong,style,sub,summary,sup,table,tbody,td,template,textarea,tfoot,th,thead,time,title,tr,track,u,ul,var,video,wbr]\nElement.register_element_classes(ELEMENT_CLASSES)\nclass Page:\n\tdef __init__(A):A.html=Element.wrap_dom_element(document.documentElement);A.body=Element.wrap_dom_element(document.body);A.head=Element.wrap_dom_element(document.head)\n\tdef __getitem__(A,selector):return A.find(selector)\n\t@property\n\tdef title(self):return document.title\n\t@title.setter\n\tdef title(self,value):document.title=value\n\tdef append(A,*B):A.body.append(*B)\n\tdef find(A,selector):return ElementCollection.wrap_dom_elements(document.querySelectorAll(selector))\npage=Page()",
15
- "websocket.py": "import js\nfrom pyscript.ffi import create_proxy\nfrom pyscript.util import as_bytearray\ncode='code'\nprotocols='protocols'\nreason='reason'\nmethods=['onclose','onerror','onmessage','onopen']\nclass EventMessage:\n\tdef __init__(A,event):A._event=event\n\tdef __getattr__(B,attr):\n\t\tA=getattr(B._event,attr)\n\t\tif attr=='data'and not isinstance(A,str):\n\t\t\tif hasattr(A,'to_py'):return A.to_py()\n\t\t\treturn memoryview(as_bytearray(A))\n\t\treturn A\nclass WebSocket:\n\tCONNECTING=0;OPEN=1;CLOSING=2;CLOSED=3\n\tdef __init__(E,**A):\n\t\tD=A['url']\n\t\tif protocols in A:B=js.WebSocket.new(D,A[protocols])\n\t\telse:B=js.WebSocket.new(D)\n\t\tobject.__setattr__(E,'_ws',B)\n\t\tfor C in methods:\n\t\t\tif C in A:setattr(B,C,create_proxy(A[C]))\n\tdef __getattr__(A,attr):return getattr(A._ws,attr)\n\tdef __setattr__(B,attr,value):\n\t\tC=value;A=attr\n\t\tif A in methods:D=lambda e:C(EventMessage(e));setattr(B._ws,A,create_proxy(D))\n\t\telse:setattr(B._ws,A,C)\n\tdef close(B,**A):\n\t\tif code in A and reason in A:B._ws.close(A[code],A[reason])\n\t\telif code in A:B._ws.close(A[code])\n\t\telse:B._ws.close()\n\tdef send(B,data):\n\t\tA=data\n\t\tif isinstance(A,str):B._ws.send(A)\n\t\telse:\n\t\t\tC=js.Uint8Array.new(len(A))\n\t\t\tfor(D,E)in enumerate(A):C[D]=E\n\t\t\tB._ws.send(C)",
16
- "workers.py": "import js as _js\nfrom polyscript import workers as _workers\n_get=_js.Reflect.get\ndef _set(script,name,value=''):script.setAttribute(name,value)\nclass _ReadOnlyProxy:\n\tdef __getitem__(A,name):return _get(_workers,name)\n\tdef __getattr__(A,name):return _get(_workers,name)\nworkers=_ReadOnlyProxy()\nasync def create_named_worker(src='',name='',config=None,type='py'):\n\tC=name;B=config;from json import dumps\n\tif not src:raise ValueError('Named workers require src')\n\tif not C:raise ValueError('Named workers require a name')\n\tA=_js.document.createElement('script');A.type=type;A.src=src;_set(A,'worker');_set(A,'name',C)\n\tif B:_set(A,'config',isinstance(B,str)and B or dumps(B))\n\t_js.document.body.append(A);return await workers[C]"
4
+ "__init__.py": "# Some notes about the naming conventions and the relationship between various\n# similar-but-different names.\n#\n# import pyscript\n# this package contains the main user-facing API offered by pyscript. All\n# the names which are supposed be used by end users should be made\n# available in pyscript/__init__.py (i.e., this file)\n#\n# import _pyscript\n# this is an internal module implemented in JS. It is used internally by\n# the pyscript package, end users should not use it directly. For its\n# implementation, grep for `interpreter.registerJsModule(\"_pyscript\",\n# ...)` in core.js\n#\n# import js\n# this is the JS globalThis, as exported by pyodide and/or micropython's\n# FFIs. As such, it contains different things in the main thread or in a\n# worker.\n#\n# import pyscript.magic_js\n# this submodule abstracts away some of the differences between the main\n# thread and the worker. In particular, it defines `window` and `document`\n# in such a way that these names work in both cases: in the main thread,\n# they are the \"real\" objects, in the worker they are proxies which work\n# thanks to coincident.\n#\n# from pyscript import window, document\n# these are just the window and document objects as defined by\n# pyscript.magic_js. This is the blessed way to access them from pyscript,\n# as it works transparently in both the main thread and worker cases.\n\nfrom polyscript import lazy_py_modules as py_import\nfrom pyscript.display import HTML, display\nfrom pyscript.fetch import fetch\nfrom pyscript.magic_js import (\n RUNNING_IN_WORKER,\n PyWorker,\n config,\n current_target,\n document,\n js_import,\n js_modules,\n sync,\n window,\n)\nfrom pyscript.storage import Storage, storage\nfrom pyscript.websocket import WebSocket\n\nif not RUNNING_IN_WORKER:\n from pyscript.workers import create_named_worker, workers\n\ntry:\n from pyscript.event_handling import when\nexcept:\n # TODO: should we remove this? Or at the very least, we should capture\n # the traceback otherwise it's very hard to debug\n from pyscript.util import NotSupported\n\n when = NotSupported(\n \"pyscript.when\", \"pyscript.when currently not available with this interpreter\"\n )\n",
5
+ "display.py": "import base64\nimport html\nimport io\nimport re\n\nfrom pyscript.magic_js import current_target, document, window\n\n_MIME_METHODS = {\n \"savefig\": \"image/png\",\n \"_repr_javascript_\": \"application/javascript\",\n \"_repr_json_\": \"application/json\",\n \"_repr_latex\": \"text/latex\",\n \"_repr_png_\": \"image/png\",\n \"_repr_jpeg_\": \"image/jpeg\",\n \"_repr_pdf_\": \"application/pdf\",\n \"_repr_svg_\": \"image/svg+xml\",\n \"_repr_markdown_\": \"text/markdown\",\n \"_repr_html_\": \"text/html\",\n \"__repr__\": \"text/plain\",\n}\n\n\ndef _render_image(mime, value, meta):\n # If the image value is using bytes we should convert it to base64\n # otherwise it will return raw bytes and the browser will not be able to\n # render it.\n if isinstance(value, bytes):\n value = base64.b64encode(value).decode(\"utf-8\")\n\n # This is the pattern of base64 strings\n base64_pattern = re.compile(\n r\"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$\"\n )\n # If value doesn't match the base64 pattern we should encode it to base64\n if len(value) > 0 and not base64_pattern.match(value):\n value = base64.b64encode(value.encode(\"utf-8\")).decode(\"utf-8\")\n\n data = f\"data:{mime};charset=utf-8;base64,{value}\"\n attrs = \" \".join(['{k}=\"{v}\"' for k, v in meta.items()])\n return f'<img src=\"{data}\" {attrs}></img>'\n\n\ndef _identity(value, meta):\n return value\n\n\n_MIME_RENDERERS = {\n \"text/plain\": html.escape,\n \"text/html\": _identity,\n \"image/png\": lambda value, meta: _render_image(\"image/png\", value, meta),\n \"image/jpeg\": lambda value, meta: _render_image(\"image/jpeg\", value, meta),\n \"image/svg+xml\": _identity,\n \"application/json\": _identity,\n \"application/javascript\": lambda value, meta: f\"<script>{value}<\\\\/script>\",\n}\n\n\nclass HTML:\n \"\"\"\n Wrap a string so that display() can render it as plain HTML\n \"\"\"\n\n def __init__(self, html):\n self._html = html\n\n def _repr_html_(self):\n return self._html\n\n\ndef _eval_formatter(obj, print_method):\n \"\"\"\n Evaluates a formatter method.\n \"\"\"\n if print_method == \"__repr__\":\n return repr(obj)\n elif hasattr(obj, print_method):\n if print_method == \"savefig\":\n buf = io.BytesIO()\n obj.savefig(buf, format=\"png\")\n buf.seek(0)\n return base64.b64encode(buf.read()).decode(\"utf-8\")\n return getattr(obj, print_method)()\n elif print_method == \"_repr_mimebundle_\":\n return {}, {}\n return None\n\n\ndef _format_mime(obj):\n \"\"\"\n Formats object using _repr_x_ methods.\n \"\"\"\n if isinstance(obj, str):\n return html.escape(obj), \"text/plain\"\n\n mimebundle = _eval_formatter(obj, \"_repr_mimebundle_\")\n if isinstance(mimebundle, tuple):\n format_dict, _ = mimebundle\n else:\n format_dict = mimebundle\n\n output, not_available = None, []\n for method, mime_type in _MIME_METHODS.items():\n if mime_type in format_dict:\n output = format_dict[mime_type]\n else:\n output = _eval_formatter(obj, method)\n\n if output is None:\n continue\n elif mime_type not in _MIME_RENDERERS:\n not_available.append(mime_type)\n continue\n break\n if output is None:\n if not_available:\n window.console.warn(\n f\"Rendered object requested unavailable MIME renderers: {not_available}\"\n )\n output = repr(output)\n mime_type = \"text/plain\"\n elif isinstance(output, tuple):\n output, meta = output\n else:\n meta = {}\n return _MIME_RENDERERS[mime_type](output, meta), mime_type\n\n\ndef _write(element, value, append=False):\n html, mime_type = _format_mime(value)\n if html == \"\\\\n\":\n return\n\n if append:\n out_element = document.createElement(\"div\")\n element.append(out_element)\n else:\n out_element = element.lastElementChild\n if out_element is None:\n out_element = element\n\n if mime_type in (\"application/javascript\", \"text/html\"):\n script_element = document.createRange().createContextualFragment(html)\n out_element.append(script_element)\n else:\n out_element.innerHTML = html\n\n\ndef display(*values, target=None, append=True):\n if target is None:\n target = current_target()\n elif not isinstance(target, str):\n raise TypeError(f\"target must be str or None, not {target.__class__.__name__}\")\n elif target == \"\":\n raise ValueError(\"Cannot have an empty target\")\n elif target.startswith(\"#\"):\n # note: here target is str and not None!\n # align with @when behavior\n target = target[1:]\n\n element = document.getElementById(target)\n\n # If target cannot be found on the page, a ValueError is raised\n if element is None:\n raise ValueError(\n f\"Invalid selector with id={target}. Cannot be found in the page.\"\n )\n\n # if element is a <script type=\"py\">, it has a 'target' attribute which\n # points to the visual element holding the displayed values. In that case,\n # use that.\n if element.tagName == \"SCRIPT\" and hasattr(element, \"target\"):\n element = element.target\n\n for v in values:\n if not append:\n element.replaceChildren()\n _write(element, v, append=append)\n",
6
+ "event_handling.py": "import inspect\n\ntry:\n from pyodide.ffi.wrappers import add_event_listener\n\nexcept ImportError:\n\n def add_event_listener(el, event_type, func):\n el.addEventListener(event_type, func)\n\n\nfrom pyscript.magic_js import document\n\n\ndef when(event_type=None, selector=None):\n \"\"\"\n Decorates a function and passes py-* events to the decorated function\n The events might or not be an argument of the decorated function\n \"\"\"\n\n def decorator(func):\n\n from pyscript.web import Element, ElementCollection\n\n if isinstance(selector, str):\n elements = document.querySelectorAll(selector)\n # TODO: This is a hack that will be removed when pyscript becomes a package\n # and we can better manage the imports without circular dependencies\n elif isinstance(selector, Element):\n elements = [selector._dom_element]\n elif isinstance(selector, ElementCollection):\n elements = [el._dom_element for el in selector]\n else:\n if isinstance(selector, list):\n elements = selector\n else:\n elements = [selector]\n\n try:\n sig = inspect.signature(func)\n # Function doesn't receive events\n if not sig.parameters:\n\n # Function is async: must be awaited\n if inspect.iscoroutinefunction(func):\n\n async def wrapper(*args, **kwargs):\n await func()\n\n else:\n\n def wrapper(*args, **kwargs):\n func()\n\n else:\n wrapper = func\n\n except AttributeError:\n # TODO: this is very ugly hack to get micropython working because inspect.signature\n # doesn't exist, but we need to actually properly replace inspect.signature.\n # It may be actually better to not try any magic for now and raise the error\n def wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except TypeError as e:\n if \"takes\" in str(e) and \"positional arguments\" in str(e):\n return func()\n\n raise\n\n for el in elements:\n add_event_listener(el, event_type, wrapper)\n\n return func\n\n return decorator\n",
7
+ "fetch.py": "import json\n\nimport js\nfrom pyscript.util import as_bytearray\n\n\n### wrap the response to grant Pythonic results\nclass _Response:\n def __init__(self, response):\n self._response = response\n\n # grant access to response.ok and other fields\n def __getattr__(self, attr):\n return getattr(self._response, attr)\n\n # exposed methods with Pythonic results\n async def arrayBuffer(self):\n buffer = await self._response.arrayBuffer()\n # works in Pyodide\n if hasattr(buffer, \"to_py\"):\n return buffer.to_py()\n # shims in MicroPython\n return memoryview(as_bytearray(buffer))\n\n async def blob(self):\n return await self._response.blob()\n\n async def bytearray(self):\n buffer = await self._response.arrayBuffer()\n return as_bytearray(buffer)\n\n async def json(self):\n return json.loads(await self.text())\n\n async def text(self):\n return await self._response.text()\n\n\n### allow direct await to _Response methods\nclass _DirectResponse:\n @staticmethod\n def setup(promise, response):\n promise._response = _Response(response)\n return promise._response\n\n def __init__(self, promise):\n self._promise = promise\n promise._response = None\n promise.arrayBuffer = self.arrayBuffer\n promise.blob = self.blob\n promise.bytearray = self.bytearray\n promise.json = self.json\n promise.text = self.text\n\n async def _response(self):\n if not self._promise._response:\n await self._promise\n return self._promise._response\n\n async def arrayBuffer(self):\n response = await self._response()\n return await response.arrayBuffer()\n\n async def blob(self):\n response = await self._response()\n return await response.blob()\n\n async def bytearray(self):\n response = await self._response()\n return await response.bytearray()\n\n async def json(self):\n response = await self._response()\n return await response.json()\n\n async def text(self):\n response = await self._response()\n return await response.text()\n\n\ndef fetch(url, **kw):\n # workaround Pyodide / MicroPython dict <-> js conversion\n options = js.JSON.parse(json.dumps(kw))\n awaited = lambda response, *args: _DirectResponse.setup(promise, response)\n promise = js.fetch(url, options).then(awaited)\n _DirectResponse(promise)\n return promise\n",
8
+ "ffi.py": "try:\n import js\n from pyodide.ffi import create_proxy as _cp\n from pyodide.ffi import to_js as _py_tjs\n\n from_entries = js.Object.fromEntries\n\n def _tjs(value, **kw):\n if not hasattr(kw, \"dict_converter\"):\n kw[\"dict_converter\"] = from_entries\n return _py_tjs(value, **kw)\n\nexcept:\n from jsffi import create_proxy as _cp\n from jsffi import to_js as _tjs\n\ncreate_proxy = _cp\nto_js = _tjs\n",
9
+ "flatted.py": "# https://www.npmjs.com/package/flatted\n\nimport json as _json\n\n\nclass _Known:\n def __init__(self):\n self.key = []\n self.value = []\n\n\nclass _String:\n def __init__(self, value):\n self.value = value\n\n\ndef _array_keys(value):\n keys = []\n i = 0\n for _ in value:\n keys.append(i)\n i += 1\n return keys\n\n\ndef _object_keys(value):\n keys = []\n for key in value:\n keys.append(key)\n return keys\n\n\ndef _is_array(value):\n return isinstance(value, list) or isinstance(value, tuple)\n\n\ndef _is_object(value):\n return isinstance(value, dict)\n\n\ndef _is_string(value):\n return isinstance(value, str)\n\n\ndef _index(known, input, value):\n input.append(value)\n index = str(len(input) - 1)\n known.key.append(value)\n known.value.append(index)\n return index\n\n\ndef _loop(keys, input, known, output):\n for key in keys:\n value = output[key]\n if isinstance(value, _String):\n _ref(key, input[int(value.value)], input, known, output)\n\n return output\n\n\ndef _ref(key, value, input, known, output):\n if _is_array(value) and not value in known:\n known.append(value)\n value = _loop(_array_keys(value), input, known, value)\n elif _is_object(value) and not value in known:\n known.append(value)\n value = _loop(_object_keys(value), input, known, value)\n\n output[key] = value\n\n\ndef _relate(known, input, value):\n if _is_string(value) or _is_array(value) or _is_object(value):\n try:\n return known.value[known.key.index(value)]\n except:\n return _index(known, input, value)\n\n return value\n\n\ndef _transform(known, input, value):\n if _is_array(value):\n output = []\n for val in value:\n output.append(_relate(known, input, val))\n return output\n\n if _is_object(value):\n obj = {}\n for key in value:\n obj[key] = _relate(known, input, value[key])\n return obj\n\n return value\n\n\ndef _wrap(value):\n if _is_string(value):\n return _String(value)\n\n if _is_array(value):\n i = 0\n for val in value:\n value[i] = _wrap(val)\n i += 1\n\n elif _is_object(value):\n for key in value:\n value[key] = _wrap(value[key])\n\n return value\n\n\ndef parse(value, *args, **kwargs):\n json = _json.loads(value, *args, **kwargs)\n wrapped = []\n for value in json:\n wrapped.append(_wrap(value))\n\n input = []\n for value in wrapped:\n if isinstance(value, _String):\n input.append(value.value)\n else:\n input.append(value)\n\n value = input[0]\n\n if _is_array(value):\n return _loop(_array_keys(value), input, [value], value)\n\n if _is_object(value):\n return _loop(_object_keys(value), input, [value], value)\n\n return value\n\n\ndef stringify(value, *args, **kwargs):\n known = _Known()\n input = []\n output = []\n i = int(_index(known, input, value))\n while i < len(input):\n output.append(_transform(known, input, input[i]))\n i += 1\n return _json.dumps(output, *args, **kwargs)\n",
10
+ "magic_js.py": "import json\nimport sys\n\nimport js as globalThis\nfrom polyscript import config as _config\nfrom polyscript import js_modules\nfrom pyscript.util import NotSupported\n\nRUNNING_IN_WORKER = not hasattr(globalThis, \"document\")\n\nconfig = json.loads(globalThis.JSON.stringify(_config))\n\nif \"MicroPython\" in sys.version:\n config[\"type\"] = \"mpy\"\nelse:\n config[\"type\"] = \"py\"\n\n\n# allow `from pyscript.js_modules.xxx import yyy`\nclass JSModule:\n def __init__(self, name):\n self.name = name\n\n def __getattr__(self, field):\n # avoid pyodide looking for non existent fields\n if not field.startswith(\"_\"):\n return getattr(getattr(js_modules, self.name), field)\n\n\n# generate N modules in the system that will proxy the real value\nfor name in globalThis.Reflect.ownKeys(js_modules):\n sys.modules[f\"pyscript.js_modules.{name}\"] = JSModule(name)\nsys.modules[\"pyscript.js_modules\"] = js_modules\n\nif RUNNING_IN_WORKER:\n import polyscript\n\n PyWorker = NotSupported(\n \"pyscript.PyWorker\",\n \"pyscript.PyWorker works only when running in the main thread\",\n )\n\n try:\n import js\n\n window = polyscript.xworker.window\n document = window.document\n js.document = document\n # this is the same as js_import on main and it lands modules on main\n js_import = window.Function(\n \"return (...urls) => Promise.all(urls.map((url) => import(url)))\"\n )()\n except:\n message = \"Unable to use `window` or `document` -> https://docs.pyscript.net/latest/faq/#sharedarraybuffer\"\n globalThis.console.warn(message)\n window = NotSupported(\"pyscript.window\", message)\n document = NotSupported(\"pyscript.document\", message)\n js_import = None\n\n sync = polyscript.xworker.sync\n\n # in workers the display does not have a default ID\n # but there is a sync utility from xworker\n def current_target():\n return polyscript.target\n\nelse:\n import _pyscript\n from _pyscript import PyWorker, js_import\n\n window = globalThis\n document = globalThis.document\n sync = NotSupported(\n \"pyscript.sync\", \"pyscript.sync works only when running in a worker\"\n )\n\n # in MAIN the current element target exist, just use it\n def current_target():\n return _pyscript.target\n",
11
+ "media.py": "from pyscript import window\nfrom pyscript.ffi import to_js\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._dom_element = device\n\n @property\n def id(self):\n return self._dom_element.deviceId\n\n @property\n def group(self):\n return self._dom_element.groupId\n\n @property\n def kind(self):\n return self._dom_element.kind\n\n @property\n def label(self):\n return self._dom_element.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(options.video, k, to_js(video[k]))\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
+ "storage.py": "from polyscript import storage as _storage\nfrom pyscript.flatted import parse as _parse\nfrom pyscript.flatted import stringify as _stringify\n\n\n# convert a Python value into an IndexedDB compatible entry\ndef _to_idb(value):\n if value is None:\n return _stringify([\"null\", 0])\n if isinstance(value, (bool, float, int, str, list, dict, tuple)):\n return _stringify([\"generic\", value])\n if isinstance(value, bytearray):\n return _stringify([\"bytearray\", [v for v in value]])\n if isinstance(value, memoryview):\n return _stringify([\"memoryview\", [v for v in value]])\n raise TypeError(f\"Unexpected value: {value}\")\n\n\n# convert an IndexedDB compatible entry into a Python value\ndef _from_idb(value):\n (\n kind,\n result,\n ) = _parse(value)\n if kind == \"null\":\n return None\n if kind == \"generic\":\n return result\n if kind == \"bytearray\":\n return bytearray(result)\n if kind == \"memoryview\":\n return memoryview(bytearray(result))\n return value\n\n\nclass Storage(dict):\n def __init__(self, store):\n super().__init__({k: _from_idb(v) for k, v in store.entries()})\n self.__store__ = store\n\n def __delitem__(self, attr):\n self.__store__.delete(attr)\n super().__delitem__(attr)\n\n def __setitem__(self, attr, value):\n self.__store__.set(attr, _to_idb(value))\n super().__setitem__(attr, value)\n\n def clear(self):\n self.__store__.clear()\n super().clear()\n\n async def sync(self):\n await self.__store__.sync()\n\n\nasync def storage(name=\"\", storage_class=Storage):\n if not name:\n raise ValueError(\"The storage name must be defined\")\n return storage_class(await _storage(f\"@pyscript/{name}\"))\n",
13
+ "util.py": "import js\n\n\ndef as_bytearray(buffer):\n ui8a = js.Uint8Array.new(buffer)\n size = ui8a.length\n ba = bytearray(size)\n for i in range(0, size):\n ba[i] = ui8a[i]\n return ba\n\n\nclass 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",
14
+ "web.py": "\"\"\"Lightweight interface to the DOM and HTML elements.\"\"\"\n\n# `when` is not used in this module. It is imported here save the user an additional\n# import (i.e. they can get what they need from `pyscript.web`).\nfrom pyscript import document, when # NOQA\n\n\ndef wrap_dom_element(dom_element):\n \"\"\"Wrap an existing DOM element in an instance of a subclass of `Element`.\n\n This is just a convenience function to avoid having to import the `Element` class\n and use its class method.\n \"\"\"\n\n return Element.wrap_dom_element(dom_element)\n\n\nclass Element:\n # A lookup table to get an `Element` subclass by tag name. Used when wrapping an\n # existing DOM element.\n element_classes_by_tag_name = {}\n\n @classmethod\n def get_tag_name(cls):\n \"\"\"Return the HTML tag name for the class.\n\n For classes that have a trailing underscore (because they clash with a Python\n keyword or built-in), we remove it to get the tag name. e.g. for the `input_`\n class, the tag name is `input`.\n\n \"\"\"\n return cls.__name__.replace(\"_\", \"\")\n\n @classmethod\n def register_element_classes(cls, element_classes):\n \"\"\"Register an iterable of element classes.\"\"\"\n for element_class in element_classes:\n tag_name = element_class.get_tag_name()\n cls.element_classes_by_tag_name[tag_name] = element_class\n\n @classmethod\n def unregister_element_classes(cls, element_classes):\n \"\"\"Unregister an iterable of element classes.\"\"\"\n for element_class in element_classes:\n tag_name = element_class.get_tag_name()\n cls.element_classes_by_tag_name.pop(tag_name, None)\n\n @classmethod\n def wrap_dom_element(cls, dom_element):\n \"\"\"Wrap an existing DOM element in an instance of a subclass of `Element`.\n\n We look up the `Element` subclass by the DOM element's tag name. For any unknown\n elements (custom tags etc.) use *this* class (`Element`).\n \"\"\"\n element_cls = cls.element_classes_by_tag_name.get(\n dom_element.tagName.lower(), cls\n )\n\n return element_cls(dom_element=dom_element)\n\n def __init__(self, dom_element=None, classes=None, style=None, **kwargs):\n \"\"\"Create a new, or wrap an existing DOM element.\n\n If `dom_element` is None we are being called to *create* a new element.\n Otherwise, we are being called to *wrap* an existing DOM element.\n \"\"\"\n self._dom_element = dom_element or document.createElement(\n type(self).get_tag_name()\n )\n\n # A set-like interface to the element's `classList`.\n self._classes = Classes(self)\n\n # A dict-like interface to the element's `style` attribute.\n self._style = Style(self)\n\n # Set any specified classes, styles, and DOM properties.\n self.update(classes=classes, style=style, **kwargs)\n\n def __eq__(self, obj):\n \"\"\"Check for equality by comparing the underlying DOM element.\"\"\"\n return isinstance(obj, Element) and obj._dom_element == self._dom_element\n\n def __getitem__(self, key):\n \"\"\"Get an item within the element's children.\n\n If `key` is an integer or a slice we use it to index/slice the element's\n children. Otherwise, we use `key` as a query selector.\n \"\"\"\n if isinstance(key, int) or isinstance(key, slice):\n return self.children[key]\n\n return self.find(key)\n\n def __getattr__(self, name):\n # This allows us to get attributes on the underlying DOM element that clash\n # with Python keywords or built-ins (e.g. the output element has an\n # attribute `for` which is a Python keyword, so you can access it on the\n # Element instance via `for_`).\n if name.endswith(\"_\"):\n name = name[:-1]\n\n return getattr(self._dom_element, name)\n\n def __setattr__(self, name, value):\n # This class overrides `__setattr__` to delegate \"public\" attributes to the\n # underlying DOM element. BUT, we don't use the usual Python pattern where\n # we set attributes on the element itself via `self.__dict__` as that is not\n # yet supported in our build of MicroPython. Instead, we handle it here by\n # using super for all \"private\" attributes (those starting with an underscore).\n if name.startswith(\"_\"):\n super().__setattr__(name, value)\n\n else:\n # This allows us to set attributes on the underlying DOM element that clash\n # with Python keywords or built-ins (e.g. the output element has an\n # attribute `for` which is a Python keyword, so you can access it on the\n # Element instance via `for_`).\n if name.endswith(\"_\"):\n name = name[:-1]\n\n setattr(self._dom_element, name, value)\n\n @property\n def children(self):\n \"\"\"Return the element's children as an `ElementCollection`.\"\"\"\n return ElementCollection.wrap_dom_elements(self._dom_element.children)\n\n @property\n def classes(self):\n \"\"\"Return the element's `classList` as a `Classes` instance.\"\"\"\n return self._classes\n\n @property\n def parent(self):\n \"\"\"Return the element's `parent `Element`.\"\"\"\n if self._dom_element.parentElement is None:\n return None\n\n return Element.wrap_dom_element(self._dom_element.parentElement)\n\n @property\n def style(self):\n \"\"\"Return the element's `style` attribute as a `Style` instance.\"\"\"\n return self._style\n\n def append(self, *items):\n \"\"\"Append the specified items to the element.\"\"\"\n for item in items:\n if isinstance(item, Element):\n self._dom_element.appendChild(item._dom_element)\n\n elif isinstance(item, ElementCollection):\n for element in item:\n self._dom_element.appendChild(element._dom_element)\n\n # We check for list/tuple here and NOT for any iterable as it will match\n # a JS Nodelist which is handled explicitly below.\n # NodeList.\n elif isinstance(item, list) or isinstance(item, tuple):\n for child in item:\n self.append(child)\n\n else:\n # In this case we know it's not an Element or an ElementCollection, so\n # we guess that it's either a DOM element or NodeList returned via the\n # ffi.\n try:\n # First, we try to see if it's an element by accessing the 'tagName'\n # attribute.\n item.tagName\n self._dom_element.appendChild(item)\n\n except AttributeError:\n try:\n # Ok, it's not an element, so let's see if it's a NodeList by\n # accessing the 'length' attribute.\n item.length\n for element_ in item:\n self._dom_element.appendChild(element_)\n\n except AttributeError:\n # Nope! This is not an element or a NodeList.\n raise TypeError(\n f'Element \"{item}\" is a proxy object, \"'\n f\"but not a valid element or a NodeList.\"\n )\n\n def clone(self, clone_id=None):\n \"\"\"Make a clone of the element (clones the underlying DOM object too).\"\"\"\n clone = Element.wrap_dom_element(self._dom_element.cloneNode(True))\n clone.id = clone_id\n return clone\n\n def find(self, selector):\n \"\"\"Find all elements that match the specified selector.\n\n Return the results as a (possibly empty) `ElementCollection`.\n \"\"\"\n return ElementCollection.wrap_dom_elements(\n self._dom_element.querySelectorAll(selector)\n )\n\n def show_me(self):\n \"\"\"Convenience method for 'element.scrollIntoView()'.\"\"\"\n self._dom_element.scrollIntoView()\n\n def update(self, classes=None, style=None, **kwargs):\n \"\"\"Update the element with the specified classes, styles, and DOM properties.\"\"\"\n\n if classes:\n self.classes.add(classes)\n\n if style:\n self.style.set(**style)\n\n for name, value in kwargs.items():\n setattr(self, name, value)\n\n\nclass Classes:\n \"\"\"A set-like interface to an element's `classList`.\"\"\"\n\n def __init__(self, element: Element):\n self._element = element\n self._class_list = self._element._dom_element.classList\n\n def __contains__(self, item):\n return item in self._class_list\n\n def __eq__(self, other):\n # We allow comparison with either another `Classes` instance...\n if isinstance(other, Classes):\n compare_with = list(other._class_list)\n\n # ...or iterables of strings.\n else:\n # TODO: Check MP for existence of better iterable test.\n try:\n compare_with = iter(other)\n\n except TypeError:\n return False\n\n return set(self._class_list) == set(compare_with)\n\n def __iter__(self):\n return iter(self._class_list)\n\n def __len__(self):\n return self._class_list.length\n\n def __repr__(self):\n return f\"Classes({', '.join(self._class_list)})\"\n\n def __str__(self):\n return \" \".join(self._class_list)\n\n def add(self, *class_names):\n \"\"\"Add one or more classes to the element.\"\"\"\n for class_name in class_names:\n if isinstance(class_name, list):\n for item in class_name:\n self.add(item)\n\n else:\n self._class_list.add(class_name)\n\n def contains(self, class_name):\n \"\"\"Check if the element has the specified class.\"\"\"\n return class_name in self\n\n def remove(self, *class_names):\n \"\"\"Remove one or more classes from the element.\"\"\"\n for class_name in class_names:\n if isinstance(class_name, list):\n for item in class_name:\n self.remove(item)\n\n else:\n self._class_list.remove(class_name)\n\n def replace(self, old_class, new_class):\n \"\"\"Replace one of the element's classes with another.\"\"\"\n self.remove(old_class)\n self.add(new_class)\n\n def toggle(self, *class_names):\n \"\"\"Toggle one or more of the element's classes.\"\"\"\n for class_name in class_names:\n if class_name in self:\n self.remove(class_name)\n\n else:\n self.add(class_name)\n\n\nclass HasOptions:\n \"\"\"Mix-in for elements that have an options attribute.\n\n The elements that support options are: <datalist>, <optgroup>, and <select>.\n \"\"\"\n\n @property\n def options(self):\n \"\"\"Return the element's options as an `Options\"\"\"\n if not hasattr(self, \"_options\"):\n self._options = Options(self)\n\n return self._options\n\n\nclass Options:\n \"\"\"This class represents the <option>s of a <datalist>, <optgroup> or <select>.\n\n It allows access to add and remove <option>s by using the `add`, `remove` and\n `clear` methods.\n \"\"\"\n\n def __init__(self, element):\n self._element = element\n\n def __getitem__(self, key):\n return self.options[key]\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 @property\n def options(self):\n \"\"\"Return the list of options.\"\"\"\n return [Element.wrap_dom_element(o) for o in self._element._dom_element.options]\n\n @property\n def selected(self):\n \"\"\"Return the selected option.\"\"\"\n return self.options[self._element._dom_element.selectedIndex]\n\n def add(self, value=None, html=None, text=None, before=None, **kwargs):\n \"\"\"Add a new option to the element\"\"\"\n if value is not None:\n kwargs[\"value\"] = value\n\n if html is not None:\n kwargs[\"innerHTML\"] = html\n\n if text is not None:\n kwargs[\"text\"] = text\n\n new_option = option(**kwargs)\n\n if before:\n if isinstance(before, Element):\n before = before._dom_element\n\n self._element._dom_element.add(new_option._dom_element, before)\n\n def clear(self):\n \"\"\"Remove all options.\"\"\"\n while len(self) > 0:\n self.remove(0)\n\n def remove(self, index):\n \"\"\"Remove the option at the specified index.\"\"\"\n self._element._dom_element.remove(index)\n\n\nclass Style:\n \"\"\"A dict-like interface to an element's `style` attribute.\"\"\"\n\n def __init__(self, element: Element):\n self._element = element\n self._style = self._element._dom_element.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 \"\"\"Remove a CSS property from the element.\"\"\"\n self._style.removeProperty(key)\n\n def set(self, **kwargs):\n \"\"\"Set one or more CSS properties on the element.\"\"\"\n for key, value in kwargs.items():\n self._element._dom_element.style.setProperty(key, value)\n\n # CSS Properties\n # Reference: https://github.com/microsoft/TypeScript/blob/main/src/lib/dom.generated.d.ts#L3799C1-L5005C2\n # Following properties automatically generated from the above reference using\n # tools/codegen_css_proxy.py\n @property\n def visible(self):\n return self._element._dom_element.style.visibility\n\n @visible.setter\n def visible(self, value):\n self._element._dom_element.style.visibility = value\n\n\nclass ContainerElement(Element):\n \"\"\"Base class for elements that can contain other elements.\"\"\"\n\n def __init__(\n self, *args, children=None, dom_element=None, style=None, classes=None, **kwargs\n ):\n super().__init__(\n dom_element=dom_element, style=style, classes=classes, **kwargs\n )\n\n for child in list(args) + (children or []):\n if isinstance(child, Element) or isinstance(child, ElementCollection):\n self.append(child)\n\n else:\n self._dom_element.insertAdjacentHTML(\"beforeend\", child)\n\n def __iter__(self):\n yield from self.children\n\n\nclass ClassesCollection:\n \"\"\"A set-like interface to the classes of the elements in a collection.\"\"\"\n\n def __init__(self, collection):\n self._collection = collection\n\n def __contains__(self, class_name):\n for element in self._collection:\n if class_name in element.classes:\n return True\n\n return False\n\n def __eq__(self, other):\n return (\n isinstance(other, ClassesCollection)\n and self._collection == other._collection\n )\n\n def __iter__(self):\n for class_name in self._all_class_names():\n yield class_name\n\n def __len__(self):\n return len(self._all_class_names())\n\n def __repr__(self):\n return f\"ClassesCollection({repr(self._collection)})\"\n\n def __str__(self):\n return \" \".join(self._all_class_names())\n\n def add(self, *class_names):\n \"\"\"Add one or more classes to the elements in the collection.\"\"\"\n for element in self._collection:\n element.classes.add(*class_names)\n\n def contains(self, class_name):\n \"\"\"Check if any element in the collection has the specified class.\"\"\"\n return class_name in self\n\n def remove(self, *class_names):\n \"\"\"Remove one or more classes from the elements in the collection.\"\"\"\n\n for element in self._collection:\n element.classes.remove(*class_names)\n\n def replace(self, old_class, new_class):\n \"\"\"Replace one of the classes in the elements in the collection with another.\"\"\"\n for element in self._collection:\n element.classes.replace(old_class, new_class)\n\n def toggle(self, *class_names):\n \"\"\"Toggle one or more classes on the elements in the collection.\"\"\"\n for element in self._collection:\n element.classes.toggle(*class_names)\n\n def _all_class_names(self):\n all_class_names = set()\n for element in self._collection:\n for class_name in element.classes:\n all_class_names.add(class_name)\n\n return all_class_names\n\n\nclass StyleCollection:\n \"\"\"A dict-like interface to the styles of the elements in a collection.\"\"\"\n\n def __init__(self, collection):\n self._collection = collection\n\n def __getitem__(self, key):\n return [element.style[key] for element in self._collection._elements]\n\n def __setitem__(self, key, value):\n for element in self._collection._elements:\n element.style[key] = value\n\n def __repr__(self):\n return f\"StyleCollection({repr(self._collection)})\"\n\n def remove(self, key):\n \"\"\"Remove a CSS property from the elements in the collection.\"\"\"\n for element in self._collection._elements:\n element.style.remove(key)\n\n\nclass ElementCollection:\n @classmethod\n def wrap_dom_elements(cls, dom_elements):\n \"\"\"Wrap an iterable of dom_elements in an `ElementCollection`.\"\"\"\n\n return cls(\n [Element.wrap_dom_element(dom_element) for dom_element in dom_elements]\n )\n\n def __init__(self, elements: [Element]):\n self._elements = elements\n self._classes = ClassesCollection(self)\n self._style = StyleCollection(self)\n\n def __eq__(self, obj):\n \"\"\"Check for equality by comparing the underlying DOM elements.\"\"\"\n return isinstance(obj, ElementCollection) and obj._elements == self._elements\n\n def __getitem__(self, key):\n \"\"\"Get an item in the collection.\n\n If `key` is an integer or a slice we use it to index/slice the collection.\n Otherwise, we use `key` as a query selector.\n \"\"\"\n if isinstance(key, int):\n return self._elements[key]\n\n elif isinstance(key, slice):\n return ElementCollection(self._elements[key])\n\n return self.find(key)\n\n def __iter__(self):\n yield from self._elements\n\n def __len__(self):\n return len(self._elements)\n\n def __repr__(self):\n return (\n f\"{self.__class__.__name__} (length: {len(self._elements)}) \"\n f\"{self._elements}\"\n )\n\n def __getattr__(self, name):\n return [getattr(element, name) for element in self._elements]\n\n def __setattr__(self, name, value):\n # This class overrides `__setattr__` to delegate \"public\" attributes to the\n # elements in the collection. BUT, we don't use the usual Python pattern where\n # we set attributes on the collection itself via `self.__dict__` as that is not\n # yet supported in our build of MicroPython. Instead, we handle it here by\n # using super for all \"private\" attributes (those starting with an underscore).\n if name.startswith(\"_\"):\n super().__setattr__(name, value)\n\n else:\n for element in self._elements:\n setattr(element, name, value)\n\n @property\n def classes(self):\n \"\"\"Return the classes of the elements in the collection as a `ClassesCollection`.\"\"\"\n return self._classes\n\n @property\n def elements(self):\n \"\"\"Return the elements in the collection as a list.\"\"\"\n return self._elements\n\n @property\n def style(self):\n \"\"\"\"\"\"\n return self._style\n\n def find(self, selector):\n \"\"\"Find all elements that match the specified selector.\n\n Return the results as a (possibly empty) `ElementCollection`.\n \"\"\"\n elements = []\n for element in self._elements:\n elements.extend(element.find(selector))\n\n return ElementCollection(elements)\n\n\n# Classes for every HTML element. If the element tag name (e.g. \"input\") clashes with\n# either a Python keyword or common symbol, then we suffix the class name with an \"_\"\n# (e.g. the class for the \"input\" element is \"input_\").\n\n\nclass a(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a\"\"\"\n\n\nclass abbr(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/abbr\"\"\"\n\n\nclass address(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/address\"\"\"\n\n\nclass area(Element):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/area\"\"\"\n\n\nclass article(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/article\"\"\"\n\n\nclass aside(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/aside\"\"\"\n\n\nclass audio(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio\"\"\"\n\n\nclass b(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/b\"\"\"\n\n\nclass base(Element):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base\"\"\"\n\n\nclass blockquote(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/blockquote\"\"\"\n\n\nclass body(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/body\"\"\"\n\n\nclass br(Element):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/br\"\"\"\n\n\nclass button(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button\"\"\"\n\n\nclass canvas(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas\"\"\"\n\n def download(self, filename: str = \"snapped.png\"):\n \"\"\"Download the current element with the filename provided in input.\n\n Inputs:\n * filename (str): name of the file being downloaded\n\n Output:\n None\n \"\"\"\n download_link = a(download=filename, href=self._dom_element.toDataURL())\n\n # Adding the link to the DOM is recommended for browser compatibility to make\n # sure that the click works.\n self.append(download_link)\n\n download_link._dom_element.click()\n\n def draw(self, what, width=None, height=None):\n \"\"\"Draw `what` on the current element\n\n Inputs:\n\n * what (canvas image source): An element to draw into the context. The\n specification permits any canvas image source, specifically, an\n HTMLImageElement, an SVGImageElement, an HTMLVideoElement,\n an HTMLCanvasElement, an ImageBitmap, an OffscreenCanvas, or a\n VideoFrame.\n \"\"\"\n if isinstance(what, Element):\n what = what._dom_element\n\n # https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage\n ctx = self._dom_element.getContext(\"2d\")\n if width or height:\n ctx.drawImage(what, 0, 0, width, height)\n\n else:\n ctx.drawImage(what, 0, 0)\n\n\nclass caption(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption\"\"\"\n\n\nclass cite(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/cite\"\"\"\n\n\nclass code(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/code\"\"\"\n\n\nclass col(Element):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/col\"\"\"\n\n\nclass colgroup(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/colgroup\"\"\"\n\n\nclass data(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/data\"\"\"\n\n\nclass datalist(ContainerElement, HasOptions):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist\"\"\"\n\n\nclass dd(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dd\"\"\"\n\n\nclass del_(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/del\"\"\"\n\n\nclass details(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details\"\"\"\n\n\nclass dialog(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog\"\"\"\n\n\nclass div(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/div\"\"\"\n\n\nclass dl(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dl\"\"\"\n\n\nclass dt(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dt\"\"\"\n\n\nclass em(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/em\"\"\"\n\n\nclass embed(Element):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/embed\"\"\"\n\n\nclass fieldset(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset\"\"\"\n\n\nclass figcaption(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figcaption\"\"\"\n\n\nclass figure(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figure\"\"\"\n\n\nclass footer(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/footer\"\"\"\n\n\nclass form(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form\"\"\"\n\n\nclass h1(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h1\"\"\"\n\n\nclass h2(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h2\"\"\"\n\n\nclass h3(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h3\"\"\"\n\n\nclass h4(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h4\"\"\"\n\n\nclass h5(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h5\"\"\"\n\n\nclass h6(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/h6\"\"\"\n\n\nclass head(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head\"\"\"\n\n\nclass header(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/header\"\"\"\n\n\nclass hgroup(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/hgroup\"\"\"\n\n\nclass hr(Element):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/hr\"\"\"\n\n\nclass html(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/html\"\"\"\n\n\nclass i(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/i\"\"\"\n\n\nclass iframe(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe\"\"\"\n\n\nclass img(Element):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img\"\"\"\n\n\nclass input_(Element):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input\"\"\"\n\n\nclass ins(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ins\"\"\"\n\n\nclass kbd(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/kbd\"\"\"\n\n\nclass label(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label\"\"\"\n\n\nclass legend(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/legend\"\"\"\n\n\nclass li(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/li\"\"\"\n\n\nclass link(Element):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link\"\"\"\n\n\nclass main(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/main\"\"\"\n\n\nclass map_(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/map\"\"\"\n\n\nclass mark(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/mark\"\"\"\n\n\nclass menu(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/menu\"\"\"\n\n\nclass meta(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta\"\"\"\n\n\nclass meter(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meter\"\"\"\n\n\nclass nav(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/nav\"\"\"\n\n\nclass object_(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/object\"\"\"\n\n\nclass ol(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol\"\"\"\n\n\nclass optgroup(ContainerElement, HasOptions):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/optgroup\"\"\"\n\n\nclass option(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option\"\"\"\n\n\nclass output(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/output\"\"\"\n\n\nclass p(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p\"\"\"\n\n\nclass param(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/param\"\"\"\n\n\nclass picture(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture\"\"\"\n\n\nclass pre(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/pre\"\"\"\n\n\nclass progress(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress\"\"\"\n\n\nclass q(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/q\"\"\"\n\n\nclass s(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/s\"\"\"\n\n\nclass script(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script\"\"\"\n\n\nclass section(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/section\"\"\"\n\n\nclass select(ContainerElement, HasOptions):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select\"\"\"\n\n\nclass small(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/small\"\"\"\n\n\nclass source(Element):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/source\"\"\"\n\n\nclass span(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/span\"\"\"\n\n\nclass strong(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/strong\"\"\"\n\n\nclass style(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style\"\"\"\n\n\nclass sub(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sub\"\"\"\n\n\nclass summary(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/summary\"\"\"\n\n\nclass sup(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sup\"\"\"\n\n\nclass table(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table\"\"\"\n\n\nclass tbody(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tbody\"\"\"\n\n\nclass td(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td\"\"\"\n\n\nclass template(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template\"\"\"\n\n\nclass textarea(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea\"\"\"\n\n\nclass tfoot(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tfoot\"\"\"\n\n\nclass th(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/th\"\"\"\n\n\nclass thead(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/thead\"\"\"\n\n\nclass time(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/time\"\"\"\n\n\nclass title(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/title\"\"\"\n\n\nclass tr(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr\"\"\"\n\n\nclass track(Element):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track\"\"\"\n\n\nclass u(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/u\"\"\"\n\n\nclass ul(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul\"\"\"\n\n\nclass var(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/var\"\"\"\n\n\nclass video(ContainerElement):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video\"\"\"\n\n def snap(\n self,\n to: Element | str = None,\n width: int | None = None,\n height: int | None = None,\n ):\n \"\"\"\n Capture a snapshot (i.e. a single frame) of a video to a canvas.\n\n Inputs:\n\n * to: the canvas to save the video frame to (if None, one is created).\n * width: width of the snapshot (defaults to the video width).\n * height: height of the snapshot (defaults to the video height).\n\n Output:\n (Element) canvas element where the video frame snapshot was drawn into\n \"\"\"\n width = width if width is not None else self.videoWidth\n height = height if height is not None else self.videoHeight\n\n if to is None:\n to = canvas(width=width, height=height)\n\n elif isinstance(to, Element):\n if to.tag != \"canvas\":\n raise TypeError(\"Element to snap to must be a canvas.\")\n\n elif getattr(to, \"tagName\", \"\") == \"CANVAS\":\n to = canvas(dom_element=to)\n\n # If 'to' is a string, then assume it is a query selector.\n elif isinstance(to, str):\n nodelist = document.querySelectorAll(to) # NOQA\n if nodelist.length == 0:\n raise TypeError(\"No element with selector {to} to snap to.\")\n\n if nodelist[0].tagName != \"CANVAS\":\n raise TypeError(\"Element to snap to must be a canvas.\")\n\n to = canvas(dom_element=nodelist[0])\n\n to.draw(self, width, height)\n\n return to\n\n\nclass wbr(Element):\n \"\"\"Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/wbr\"\"\"\n\n\n# fmt: off\nELEMENT_CLASSES = [\n a, abbr, address, area, article, aside, audio,\n b, base, blockquote, body, br, button,\n canvas, caption, cite, code, col, colgroup,\n data, datalist, dd, del_, details, dialog, div, dl, dt,\n em, embed,\n fieldset, figcaption, figure, footer, form,\n h1, h2, h3, h4, h5, h6, head, header, hgroup, hr, html,\n i, iframe, img, input_, ins,\n kbd,\n label, legend, li, link,\n main, map_, mark, menu, meta, meter,\n nav,\n object_, ol, optgroup, option, output,\n p, param, picture, pre, progress,\n q,\n s, script, section, select, small, source, span, strong, style, sub, summary, sup,\n table, tbody, td, template, textarea, tfoot, th, thead, time, title, tr, track,\n u, ul,\n var, video,\n wbr,\n]\n# fmt: on\n\n\n# Register all the default (aka \"built-in\") Element classes.\nElement.register_element_classes(ELEMENT_CLASSES)\n\n\nclass Page:\n \"\"\"Represents the whole page.\"\"\"\n\n def __init__(self):\n self.html = Element.wrap_dom_element(document.documentElement)\n self.body = Element.wrap_dom_element(document.body)\n self.head = Element.wrap_dom_element(document.head)\n\n def __getitem__(self, selector):\n \"\"\"Get an item on the page.\n\n We don't index/slice the page like we do with `Element` and `ElementCollection`\n as it is a bit muddier what the ideal behavior should be. Instead, we simply\n use this as a convenience method to `find` elements on the page.\n \"\"\"\n return self.find(selector)\n\n @property\n def title(self):\n \"\"\"Return the page title.\"\"\"\n return document.title\n\n @title.setter\n def title(self, value):\n \"\"\"Set the page title.\"\"\"\n document.title = value\n\n def append(self, *items):\n \"\"\"Shortcut for `page.body.append`.\"\"\"\n self.body.append(*items)\n\n def find(self, selector): # NOQA\n \"\"\"Find all elements that match the specified selector.\n\n Return the results as a (possibly empty) `ElementCollection`.\n \"\"\"\n return ElementCollection.wrap_dom_elements(document.querySelectorAll(selector))\n\n\npage = Page()\n",
15
+ "websocket.py": "import js\nfrom pyscript.ffi import create_proxy\nfrom pyscript.util import as_bytearray\n\ncode = \"code\"\nprotocols = \"protocols\"\nreason = \"reason\"\nmethods = [\"onclose\", \"onerror\", \"onmessage\", \"onopen\"]\n\n\nclass EventMessage:\n def __init__(self, event):\n self._event = event\n\n def __getattr__(self, attr):\n value = getattr(self._event, attr)\n\n if attr == \"data\" and not isinstance(value, str):\n if hasattr(value, \"to_py\"):\n return value.to_py()\n # shims in MicroPython\n return memoryview(as_bytearray(value))\n\n return value\n\n\nclass WebSocket(object):\n CONNECTING = 0\n OPEN = 1\n CLOSING = 2\n CLOSED = 3\n\n def __init__(self, **kw):\n url = kw[\"url\"]\n if protocols in kw:\n socket = js.WebSocket.new(url, kw[protocols])\n else:\n socket = js.WebSocket.new(url)\n object.__setattr__(self, \"_ws\", socket)\n\n for t in methods:\n if t in kw:\n # Pyodide fails at setting socket[t] directly\n setattr(socket, t, create_proxy(kw[t]))\n\n def __getattr__(self, attr):\n return getattr(self._ws, attr)\n\n def __setattr__(self, attr, value):\n if attr in methods:\n m = lambda e: value(EventMessage(e))\n setattr(self._ws, attr, create_proxy(m))\n else:\n setattr(self._ws, attr, value)\n\n def close(self, **kw):\n if code in kw and reason in kw:\n self._ws.close(kw[code], kw[reason])\n elif code in kw:\n self._ws.close(kw[code])\n else:\n self._ws.close()\n\n def send(self, data):\n if isinstance(data, str):\n self._ws.send(data)\n else:\n buffer = js.Uint8Array.new(len(data))\n for pos, b in enumerate(data):\n buffer[pos] = b\n self._ws.send(buffer)\n",
16
+ "workers.py": "import js as _js\nfrom polyscript import workers as _workers\n\n_get = _js.Reflect.get\n\n\ndef _set(script, name, value=\"\"):\n script.setAttribute(name, value)\n\n\n# this solves an inconsistency between Pyodide and MicroPython\n# @see https://github.com/pyscript/pyscript/issues/2106\nclass _ReadOnlyProxy:\n def __getitem__(self, name):\n return _get(_workers, name)\n\n def __getattr__(self, name):\n return _get(_workers, name)\n\n\nworkers = _ReadOnlyProxy()\n\n\nasync def create_named_worker(src=\"\", name=\"\", config=None, type=\"py\"):\n from json import dumps\n\n if not src:\n raise ValueError(\"Named workers require src\")\n\n if not name:\n raise ValueError(\"Named workers require a name\")\n\n s = _js.document.createElement(\"script\")\n s.type = type\n s.src = src\n _set(s, \"worker\")\n _set(s, \"name\", name)\n\n if config:\n _set(s, \"config\", isinstance(config, str) and config or dumps(config))\n\n _js.document.body.append(s)\n return await workers[name]\n"
17
17
  }
18
18
  };
@@ -1,2 +0,0 @@
1
- import{V as e,a as t,E as i,b as s,c as n,r as o,h as r,W as a,d as l,e as c,f as h,i as d,j as u,m as f,n as m,o as p,k as g}from"./codemirror_view-aIuSN42d.js";import{codePointAt as v,fromCodePoint as x,codePointSize as b,StateEffect as w,Facet as y,combineConfig as k,CharCategory as S,EditorSelection as M,Prec as C,StateField as A,EditorState as L,findClusterBreak as q,RangeSetBuilder as R}from"./codemirror_state-1d1uncXx.js";import{k as D,l as W,m as F,n as I,o as P,p as E}from"./codemirror_language-4kk4Aqm3.js";import{history as $,defaultKeymap as O,historyKeymap as T}from"./codemirror_commands-CvnouHng.js";import{a as z,b as B,d as j,e as _}from"./index-DqgFLybq.js";function V(){var e=arguments[0];"string"==typeof e&&(e=document.createElement(e));var t=1,i=arguments[1];if(i&&"object"==typeof i&&null==i.nodeType&&!Array.isArray(i)){for(var s in i)if(Object.prototype.hasOwnProperty.call(i,s)){var n=i[s];"string"==typeof n?e.setAttribute(s,n):null!=n&&(e[s]=n)}t++}for(;t<arguments.length;t++)H(e,arguments[t]);return e}function H(e,t){if("string"==typeof t)e.appendChild(document.createTextNode(t));else if(null==t);else if(null!=t.nodeType)e.appendChild(t);else{if(!Array.isArray(t))throw new RangeError("Unsupported child node: "+t);for(var i=0;i<t.length;i++)H(e,t[i])}}const N="function"==typeof String.prototype.normalize?e=>e.normalize("NFKD"):e=>e;class U{constructor(e,t,i=0,s=e.length,n,o){this.test=o,this.value={from:0,to:0},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=e.iterRange(i,s),this.bufferStart=i,this.normalize=n?e=>n(N(e)):N,this.query=this.normalize(t)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return v(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let e=this.peek();if(e<0)return this.done=!0,this;let t=x(e),i=this.bufferStart+this.bufferPos;this.bufferPos+=b(e);let s=this.normalize(t);for(let e=0,n=i;;e++){let o=s.charCodeAt(e),r=this.match(o,n,this.bufferPos+this.bufferStart);if(e==s.length-1){if(r)return this.value=r,this;break}n==i&&e<t.length&&t.charCodeAt(e)==o&&n++}}}match(e,t,i){let s=null;for(let t=0;t<this.matches.length;t+=2){let n=this.matches[t],o=!1;this.query.charCodeAt(n)==e&&(n==this.query.length-1?s={from:this.matches[t+1],to:i}:(this.matches[t]++,o=!0)),o||(this.matches.splice(t,2),t-=2)}return this.query.charCodeAt(0)==e&&(1==this.query.length?s={from:t,to:i}:this.matches.push(1,t)),s&&this.test&&!this.test(s.from,s.to,this.buffer,this.bufferStart)&&(s=null),s}}"undefined"!=typeof Symbol&&(U.prototype[Symbol.iterator]=function(){return this});const K={from:-1,to:-1,match:/.*/.exec("")},Q="gm"+(null==/x/.unicode?"":"u");class G{constructor(e,t,i,s=0,n=e.length){if(this.text=e,this.to=n,this.curLine="",this.done=!1,this.value=K,/\\[sWDnr]|\n|\r|\[\^/.test(t))return new J(e,t,i,s,n);this.re=new RegExp(t,Q+((null==i?void 0:i.ignoreCase)?"i":"")),this.test=null==i?void 0:i.test,this.iter=e.iter();let o=e.lineAt(s);this.curLineStart=o.from,this.matchPos=X(e,s),this.getLine(this.curLineStart)}getLine(e){this.iter.next(e),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let e=this.matchPos-this.curLineStart;;){this.re.lastIndex=e;let t=this.matchPos<=this.to&&this.re.exec(this.curLine);if(t){let i=this.curLineStart+t.index,s=i+t[0].length;if(this.matchPos=X(this.text,s+(i==s?1:0)),i==this.curLineStart+this.curLine.length&&this.nextLine(),(i<s||i>this.value.to)&&(!this.test||this.test(i,s,t)))return this.value={from:i,to:s,match:t},this;e=this.matchPos-this.curLineStart}else{if(!(this.curLineStart+this.curLine.length<this.to))return this.done=!0,this;this.nextLine(),e=0}}}}const Y=new WeakMap;class Z{constructor(e,t){this.from=e,this.text=t}get to(){return this.from+this.text.length}static get(e,t,i){let s=Y.get(e);if(!s||s.from>=i||s.to<=t){let s=new Z(t,e.sliceString(t,i));return Y.set(e,s),s}if(s.from==t&&s.to==i)return s;let{text:n,from:o}=s;return o>t&&(n=e.sliceString(t,o)+n,o=t),s.to<i&&(n+=e.sliceString(s.to,i)),Y.set(e,new Z(o,n)),new Z(t,n.slice(t-o,i-o))}}class J{constructor(e,t,i,s,n){this.text=e,this.to=n,this.done=!1,this.value=K,this.matchPos=X(e,s),this.re=new RegExp(t,Q+((null==i?void 0:i.ignoreCase)?"i":"")),this.test=null==i?void 0:i.test,this.flat=Z.get(e,s,this.chunkEnd(s+5e3))}chunkEnd(e){return e>=this.to?this.to:this.text.lineAt(e).to}next(){for(;;){let e=this.re.lastIndex=this.matchPos-this.flat.from,t=this.re.exec(this.flat.text);if(t&&!t[0]&&t.index==e&&(this.re.lastIndex=e+1,t=this.re.exec(this.flat.text)),t){let e=this.flat.from+t.index,i=e+t[0].length;if((this.flat.to>=this.to||t.index+t[0].length<=this.flat.text.length-10)&&(!this.test||this.test(e,i,t)))return this.value={from:e,to:i,match:t},this.matchPos=X(this.text,i+(e==i?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=Z.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+2*this.flat.text.length))}}}function X(e,t){if(t>=e.length)return t;let i,s=e.lineAt(t);for(;t<s.to&&(i=s.text.charCodeAt(t-s.from))>=56320&&i<57344;)t++;return t}function ee(e){let t=V("input",{class:"cm-textfield",name:"line",value:String(e.state.doc.lineAt(e.state.selection.main.head).number)});function s(){let s=/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(t.value);if(!s)return;let{state:n}=e,o=n.doc.lineAt(n.selection.main.head),[,r,a,l,c]=s,h=l?+l.slice(1):0,d=a?+a:o.number;if(a&&c){let e=d/100;r&&(e=e*("-"==r?-1:1)+o.number/n.doc.lines),d=Math.round(n.doc.lines*e)}else a&&r&&(d=d*("-"==r?-1:1)+o.number);let u=n.doc.line(Math.max(1,Math.min(n.doc.lines,d))),f=M.cursor(u.from+Math.max(0,Math.min(h,u.length)));e.dispatch({effects:[te.of(!1),i.scrollIntoView(f.from,{y:"center"})],selection:f}),e.focus()}return{dom:V("form",{class:"cm-gotoLine",onkeydown:t=>{27==t.keyCode?(t.preventDefault(),e.dispatch({effects:te.of(!1)}),e.focus()):13==t.keyCode&&(t.preventDefault(),s())},onsubmit:e=>{e.preventDefault(),s()}},V("label",e.state.phrase("Go to line"),": ",t)," ",V("button",{class:"cm-button",type:"submit"},e.state.phrase("go")))}}"undefined"!=typeof Symbol&&(G.prototype[Symbol.iterator]=J.prototype[Symbol.iterator]=function(){return this});const te=w.define(),ie=A.define({create:()=>!0,update(e,t){for(let i of t.effects)i.is(te)&&(e=i.value);return e},provide:e=>n.from(e,(e=>e?ee:null))}),se=i.baseTheme({".cm-panel.cm-gotoLine":{padding:"2px 6px 4px","& label":{fontSize:"80%"}}}),ne={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},oe=y.define({combine:e=>k(e,ne,{highlightWordAroundCursor:(e,t)=>e||t,minSelectionLength:Math.min,maxMatches:Math.min})});const re=t.mark({class:"cm-selectionMatch"}),ae=t.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function le(e,t,i,s){return!(0!=i&&e(t.sliceDoc(i-1,i))==S.Word||s!=t.doc.length&&e(t.sliceDoc(s,s+1))==S.Word)}const ce=e.fromClass(class{constructor(e){this.decorations=this.getDeco(e)}update(e){(e.selectionSet||e.docChanged||e.viewportChanged)&&(this.decorations=this.getDeco(e.view))}getDeco(e){let i=e.state.facet(oe),{state:s}=e,n=s.selection;if(n.ranges.length>1)return t.none;let o,r=n.main,a=null;if(r.empty){if(!i.highlightWordAroundCursor)return t.none;let e=s.wordAt(r.head);if(!e)return t.none;a=s.charCategorizer(r.head),o=s.sliceDoc(e.from,e.to)}else{let e=r.to-r.from;if(e<i.minSelectionLength||e>200)return t.none;if(i.wholeWords){if(o=s.sliceDoc(r.from,r.to),a=s.charCategorizer(r.head),!le(a,s,r.from,r.to)||!function(e,t,i,s){return e(t.sliceDoc(i,i+1))==S.Word&&e(t.sliceDoc(s-1,s))==S.Word}(a,s,r.from,r.to))return t.none}else if(o=s.sliceDoc(r.from,r.to),!o)return t.none}let l=[];for(let n of e.visibleRanges){let e=new U(s.doc,o,n.from,n.to);for(;!e.next().done;){let{from:n,to:o}=e.value;if((!a||le(a,s,n,o))&&(r.empty&&n<=r.from&&o>=r.to?l.push(ae.range(n,o)):(n>=r.to||o<=r.from)&&l.push(re.range(n,o)),l.length>i.maxMatches))return t.none}}return t.set(l)}},{decorations:e=>e.decorations}),he=i.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}});const de=y.define({combine:e=>k(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:e=>new Be(e),scrollToMatch:e=>i.scrollIntoView(e)})});class ue{constructor(e){this.search=e.search,this.caseSensitive=!!e.caseSensitive,this.literal=!!e.literal,this.regexp=!!e.regexp,this.replace=e.replace||"",this.valid=!!this.search&&(!this.regexp||function(e){try{return new RegExp(e,Q),!0}catch(e){return!1}}(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!e.wholeWord}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,((e,t)=>"n"==t?"\n":"r"==t?"\r":"t"==t?"\t":"\\"))}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord}create(){return this.regexp?new be(this):new pe(this)}getCursor(e,t=0,i){let s=e.doc?e:L.create({doc:e});return null==i&&(i=s.doc.length),this.regexp?ge(this,s,t,i):me(this,s,t,i)}}class fe{constructor(e){this.spec=e}}function me(e,t,i,s){return new U(t.doc,e.unquoted,i,s,e.caseSensitive?void 0:e=>e.toLowerCase(),e.wholeWord?(n=t.doc,o=t.charCategorizer(t.selection.main.head),(e,t,i,s)=>((s>e||s+i.length<t)&&(s=Math.max(0,e-2),i=n.sliceString(s,Math.min(n.length,t+2))),!(o(ve(i,e-s))==S.Word&&o(xe(i,e-s))==S.Word||o(xe(i,t-s))==S.Word&&o(ve(i,t-s))==S.Word))):void 0);var n,o}class pe extends fe{constructor(e){super(e)}nextMatch(e,t,i){let s=me(this.spec,e,i,e.doc.length).nextOverlapping();return s.done&&(s=me(this.spec,e,0,t).nextOverlapping()),s.done?null:s.value}prevMatchInRange(e,t,i){for(let s=i;;){let i=Math.max(t,s-1e4-this.spec.unquoted.length),n=me(this.spec,e,i,s),o=null;for(;!n.nextOverlapping().done;)o=n.value;if(o)return o;if(i==t)return null;s-=1e4}}prevMatch(e,t,i){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,i,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace)}matchAll(e,t){let i=me(this.spec,e,0,e.doc.length),s=[];for(;!i.next().done;){if(s.length>=t)return null;s.push(i.value)}return s}highlight(e,t,i,s){let n=me(this.spec,e,Math.max(0,t-this.spec.unquoted.length),Math.min(i+this.spec.unquoted.length,e.doc.length));for(;!n.next().done;)s(n.value.from,n.value.to)}}function ge(e,t,i,s){return new G(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:e.wholeWord?(n=t.charCategorizer(t.selection.main.head),(e,t,i)=>!i[0].length||(n(ve(i.input,i.index))!=S.Word||n(xe(i.input,i.index))!=S.Word)&&(n(xe(i.input,i.index+i[0].length))!=S.Word||n(ve(i.input,i.index+i[0].length))!=S.Word)):void 0},i,s);var n}function ve(e,t){return e.slice(q(e,t,!1),t)}function xe(e,t){return e.slice(t,q(e,t))}class be extends fe{nextMatch(e,t,i){let s=ge(this.spec,e,i,e.doc.length).next();return s.done&&(s=ge(this.spec,e,0,t).next()),s.done?null:s.value}prevMatchInRange(e,t,i){for(let s=1;;s++){let n=Math.max(t,i-1e4*s),o=ge(this.spec,e,n,i),r=null;for(;!o.next().done;)r=o.value;if(r&&(n==t||r.from>n+10))return r;if(n==t)return null}}prevMatch(e,t,i){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,i,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace).replace(/\$([$&\d+])/g,((t,i)=>"$"==i?"$":"&"==i?e.match[0]:"0"!=i&&+i<e.match.length?e.match[i]:t))}matchAll(e,t){let i=ge(this.spec,e,0,e.doc.length),s=[];for(;!i.next().done;){if(s.length>=t)return null;s.push(i.value)}return s}highlight(e,t,i,s){let n=ge(this.spec,e,Math.max(0,t-250),Math.min(i+250,e.doc.length));for(;!n.next().done;)s(n.value.from,n.value.to)}}const we=w.define(),ye=w.define(),ke=A.define({create:e=>new Se(Pe(e).create(),null),update(e,t){for(let i of t.effects)i.is(we)?e=new Se(i.value.create(),e.panel):i.is(ye)&&(e=new Se(e.query,i.value?Ie:null));return e},provide:e=>n.from(e,(e=>e.panel))});class Se{constructor(e,t){this.query=e,this.panel=t}}const Me=t.mark({class:"cm-searchMatch"}),Ce=t.mark({class:"cm-searchMatch cm-searchMatch-selected"}),Ae=e.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(ke))}update(e){let t=e.state.field(ke);(t!=e.startState.field(ke)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:i}){if(!i||!e.spec.valid)return t.none;let{view:s}=this,n=new R;for(let t=0,i=s.visibleRanges,o=i.length;t<o;t++){let{from:r,to:a}=i[t];for(;t<o-1&&a>i[t+1].from-500;)a=i[++t].to;e.highlight(s.state,r,a,((e,t)=>{let i=s.state.selection.ranges.some((i=>i.from==e&&i.to==t));n.add(e,t,i?Ce:Me)}))}return n.finish()}},{decorations:e=>e.decorations});function Le(e){return t=>{let i=t.state.field(ke,!1);return i&&i.query.spec.valid?e(t,i):Oe(t)}}const qe=Le(((e,{query:t})=>{let{to:i}=e.state.selection.main,s=t.nextMatch(e.state,i,i);if(!s)return!1;let n=M.single(s.from,s.to),o=e.state.facet(de);return e.dispatch({selection:n,effects:[He(e,s),o.scrollToMatch(n.main,e)],userEvent:"select.search"}),$e(e),!0})),Re=Le(((e,{query:t})=>{let{state:i}=e,{from:s}=i.selection.main,n=t.prevMatch(i,s,s);if(!n)return!1;let o=M.single(n.from,n.to),r=e.state.facet(de);return e.dispatch({selection:o,effects:[He(e,n),r.scrollToMatch(o.main,e)],userEvent:"select.search"}),$e(e),!0})),De=Le(((e,{query:t})=>{let i=t.matchAll(e.state,1e3);return!(!i||!i.length)&&(e.dispatch({selection:M.create(i.map((e=>M.range(e.from,e.to)))),userEvent:"select.search.matches"}),!0)})),We=Le(((e,{query:t})=>{let{state:s}=e,{from:n,to:o}=s.selection.main;if(s.readOnly)return!1;let r=t.nextMatch(s,n,n);if(!r)return!1;let a,l,c=[],h=[];if(r.from==n&&r.to==o&&(l=s.toText(t.getReplacement(r)),c.push({from:r.from,to:r.to,insert:l}),r=t.nextMatch(s,r.from,r.to),h.push(i.announce.of(s.phrase("replaced match on line $",s.doc.lineAt(n).number)+"."))),r){let t=0==c.length||c[0].from>=r.to?0:r.to-r.from-l.length;a=M.single(r.from-t,r.to-t),h.push(He(e,r)),h.push(s.facet(de).scrollToMatch(a.main,e))}return e.dispatch({changes:c,selection:a,effects:h,userEvent:"input.replace"}),!0})),Fe=Le(((e,{query:t})=>{if(e.state.readOnly)return!1;let s=t.matchAll(e.state,1e9).map((e=>{let{from:i,to:s}=e;return{from:i,to:s,insert:t.getReplacement(e)}}));if(!s.length)return!1;let n=e.state.phrase("replaced $ matches",s.length)+".";return e.dispatch({changes:s,effects:i.announce.of(n),userEvent:"input.replace.all"}),!0}));function Ie(e){return e.state.facet(de).createPanel(e)}function Pe(e,t){var i,s,n,o,r;let a=e.selection.main,l=a.empty||a.to>a.from+100?"":e.sliceDoc(a.from,a.to);if(t&&!l)return t;let c=e.facet(de);return new ue({search:(null!==(i=null==t?void 0:t.literal)&&void 0!==i?i:c.literal)?l:l.replace(/\n/g,"\\n"),caseSensitive:null!==(s=null==t?void 0:t.caseSensitive)&&void 0!==s?s:c.caseSensitive,literal:null!==(n=null==t?void 0:t.literal)&&void 0!==n?n:c.literal,regexp:null!==(o=null==t?void 0:t.regexp)&&void 0!==o?o:c.regexp,wholeWord:null!==(r=null==t?void 0:t.wholeWord)&&void 0!==r?r:c.wholeWord})}function Ee(e){let t=s(e,Ie);return t&&t.dom.querySelector("[main-field]")}function $e(e){let t=Ee(e);t&&t==e.root.activeElement&&t.select()}const Oe=e=>{let t=e.state.field(ke,!1);if(t&&t.panel){let i=Ee(e);if(i&&i!=e.root.activeElement){let s=Pe(e.state,t.query.spec);s.valid&&e.dispatch({effects:we.of(s)}),i.focus(),i.select()}}else e.dispatch({effects:[ye.of(!0),t?we.of(Pe(e.state,t.query.spec)):w.appendConfig.of(Ue)]});return!0},Te=e=>{let t=e.state.field(ke,!1);if(!t||!t.panel)return!1;let i=s(e,Ie);return i&&i.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:ye.of(!1)}),!0},ze=[{key:"Mod-f",run:Oe,scope:"editor search-panel"},{key:"F3",run:qe,shift:Re,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:qe,shift:Re,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:Te,scope:"editor search-panel"},{key:"Mod-Shift-l",run:({state:e,dispatch:t})=>{let i=e.selection;if(i.ranges.length>1||i.main.empty)return!1;let{from:s,to:n}=i.main,o=[],r=0;for(let t=new U(e.doc,e.sliceDoc(s,n));!t.next().done;){if(o.length>1e3)return!1;t.value.from==s&&(r=o.length),o.push(M.range(t.value.from,t.value.to))}return t(e.update({selection:M.create(o,r),userEvent:"select.search.matches"})),!0}},{key:"Mod-Alt-g",run:e=>{let t=s(e,ee);if(!t){let i=[te.of(!0)];null==e.state.field(ie,!1)&&i.push(w.appendConfig.of([ie,se])),e.dispatch({effects:i}),t=s(e,ee)}return t&&t.dom.querySelector("input").select(),!0}},{key:"Mod-d",run:({state:e,dispatch:t})=>{let{ranges:s}=e.selection;if(s.some((e=>e.from===e.to)))return(({state:e,dispatch:t})=>{let{selection:i}=e,s=M.create(i.ranges.map((t=>e.wordAt(t.head)||M.cursor(t.head))),i.mainIndex);return!s.eq(i)&&(t(e.update({selection:s})),!0)})({state:e,dispatch:t});let n=e.sliceDoc(s[0].from,s[0].to);if(e.selection.ranges.some((t=>e.sliceDoc(t.from,t.to)!=n)))return!1;let o=function(e,t){let{main:i,ranges:s}=e.selection,n=e.wordAt(i.head),o=n&&n.from==i.from&&n.to==i.to;for(let i=!1,n=new U(e.doc,t,s[s.length-1].to);;){if(n.next(),!n.done){if(i&&s.some((e=>e.from==n.value.from)))continue;if(o){let t=e.wordAt(n.value.from);if(!t||t.from!=n.value.from||t.to!=n.value.to)continue}return n.value}if(i)return null;n=new U(e.doc,t,0,Math.max(0,s[s.length-1].from-1)),i=!0}}(e,n);return!!o&&(t(e.update({selection:e.selection.addRange(M.range(o.from,o.to),!1),effects:i.scrollIntoView(o.to)})),!0)},preventDefault:!0}];class Be{constructor(e){this.view=e;let t=this.query=e.state.field(ke).query.spec;function i(e,t,i){return V("button",{class:"cm-button",name:e,onclick:t,type:"button"},i)}this.commit=this.commit.bind(this),this.searchField=V("input",{value:t.search,placeholder:je(e,"Find"),"aria-label":je(e,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=V("input",{value:t.replace,placeholder:je(e,"Replace"),"aria-label":je(e,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=V("input",{type:"checkbox",name:"case",form:"",checked:t.caseSensitive,onchange:this.commit}),this.reField=V("input",{type:"checkbox",name:"re",form:"",checked:t.regexp,onchange:this.commit}),this.wordField=V("input",{type:"checkbox",name:"word",form:"",checked:t.wholeWord,onchange:this.commit}),this.dom=V("div",{onkeydown:e=>this.keydown(e),class:"cm-search"},[this.searchField,i("next",(()=>qe(e)),[je(e,"next")]),i("prev",(()=>Re(e)),[je(e,"previous")]),i("select",(()=>De(e)),[je(e,"all")]),V("label",null,[this.caseField,je(e,"match case")]),V("label",null,[this.reField,je(e,"regexp")]),V("label",null,[this.wordField,je(e,"by word")]),...e.state.readOnly?[]:[V("br"),this.replaceField,i("replace",(()=>We(e)),[je(e,"replace")]),i("replaceAll",(()=>Fe(e)),[je(e,"replace all")])],V("button",{name:"close",onclick:()=>Te(e),"aria-label":je(e,"close"),type:"button"},["×"])])}commit(){let e=new ue({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});e.eq(this.query)||(this.query=e,this.view.dispatch({effects:we.of(e)}))}keydown(e){o(this.view,e,"search-panel")?e.preventDefault():13==e.keyCode&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?Re:qe)(this.view)):13==e.keyCode&&e.target==this.replaceField&&(e.preventDefault(),We(this.view))}update(e){for(let t of e.transactions)for(let e of t.effects)e.is(we)&&!e.value.eq(this.query)&&this.setQuery(e.value)}setQuery(e){this.query=e,this.searchField.value=e.search,this.replaceField.value=e.replace,this.caseField.checked=e.caseSensitive,this.reField.checked=e.regexp,this.wordField.checked=e.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(de).top}}function je(e,t){return e.state.phrase(t)}const _e=30,Ve=/[\s\.,:;?!]/;function He(e,{from:t,to:s}){let n=e.state.doc.lineAt(t),o=e.state.doc.lineAt(s).to,r=Math.max(n.from,t-_e),a=Math.min(o,s+_e),l=e.state.sliceDoc(r,a);if(r!=n.from)for(let e=0;e<_e;e++)if(!Ve.test(l[e+1])&&Ve.test(l[e])){l=l.slice(e);break}if(a!=o)for(let e=l.length-1;e>l.length-_e;e--)if(!Ve.test(l[e-1])&&Ve.test(l[e])){l=l.slice(0,e);break}return i.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${n.number}.`)}const Ne=i.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),Ue=[ke,C.low(Ae),Ne];class Ke{constructor(e,t,i){this.from=e,this.to=t,this.diagnostic=i}}class Qe{constructor(e,t,i){this.diagnostics=e,this.panel=t,this.selected=i}static init(e,i,s){let n=e,o=s.facet(ot).markerFilter;o&&(n=o(n,s));let r=t.set(n.map((e=>e.from==e.to||e.from==e.to-1&&s.doc.lineAt(e.from).to==e.from?t.widget({widget:new lt(e),diagnostic:e}).range(e.from):t.mark({attributes:{class:"cm-lintRange cm-lintRange-"+e.severity+(e.markClass?" "+e.markClass:"")},diagnostic:e}).range(e.from,e.to))),!0);return new Qe(r,i,Ge(r))}}function Ge(e,t=null,i=0){let s=null;return e.between(i,1e9,((e,i,{spec:n})=>{if(!t||n.diagnostic==t)return s=new Ke(e,i,n.diagnostic),!1})),s}const Ye=w.define(),Ze=w.define(),Je=w.define(),Xe=A.define({create:()=>new Qe(t.none,null,null),update(e,t){if(t.docChanged&&e.diagnostics.size){let i=e.diagnostics.map(t.changes),s=null,n=e.panel;if(e.selected){let n=t.changes.mapPos(e.selected.from,1);s=Ge(i,e.selected.diagnostic,n)||Ge(i,null,n)}!i.size&&n&&t.state.facet(ot).autoPanel&&(n=null),e=new Qe(i,n,s)}for(let i of t.effects)if(i.is(Ye)){let s=t.state.facet(ot).autoPanel?i.value.length?ht.open:null:e.panel;e=Qe.init(i.value,s,t.state)}else i.is(Ze)?e=new Qe(e.diagnostics,i.value?ht.open:null,e.selected):i.is(Je)&&(e=new Qe(e.diagnostics,e.panel,i.value));return e},provide:e=>[n.from(e,(e=>e.panel)),i.decorations.from(e,(e=>e.diagnostics))]}),et=t.mark({class:"cm-lintRange cm-lintRange-active"});function tt(e,t,i){let{diagnostics:s}=e.state.field(Xe),n=[],o=2e8,r=0;s.between(t-(i<0?1:0),t+(i>0?1:0),((e,s,{spec:a})=>{t>=e&&t<=s&&(e==s||(t>e||i>0)&&(t<s||i<0))&&(n.push(a.diagnostic),o=Math.min(e,o),r=Math.max(s,r))}));let a=e.state.facet(ot).tooltipFilter;return a&&(n=a(n,e.state)),n.length?{pos:o,end:r,above:e.state.doc.lineAt(o).to<r,create:()=>({dom:it(e,n)})}:null}function it(e,t){return V("ul",{class:"cm-tooltip-lint"},t.map((t=>at(e,t,!1))))}const st=e=>{let t=e.state.field(Xe,!1);return!(!t||!t.panel)&&(e.dispatch({effects:Ze.of(!1)}),!0)},nt=[{key:"Mod-Shift-m",run:e=>{let t=e.state.field(Xe,!1);var i,n;t&&t.panel||e.dispatch({effects:(i=e.state,n=[Ze.of(!0)],i.field(Xe,!1)?n:n.concat(w.appendConfig.of(ft)))});let o=s(e,ht.open);return o&&o.dom.querySelector(".cm-panel-lint ul").focus(),!0},preventDefault:!0},{key:"F8",run:e=>{let t=e.state.field(Xe,!1);if(!t)return!1;let i=e.state.selection.main,s=t.diagnostics.iter(i.to+1);return!(!s.value&&(s=t.diagnostics.iter(0),!s.value||s.from==i.from&&s.to==i.to))&&(e.dispatch({selection:{anchor:s.from,head:s.to},scrollIntoView:!0}),!0)}}],ot=y.define({combine:e=>Object.assign({sources:e.map((e=>e.source)).filter((e=>null!=e))},k(e.map((e=>e.config)),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{needsRefresh:(e,t)=>e?t?i=>e(i)||t(i):e:t}))});function rt(e){let t=[];if(e)e:for(let{name:i}of e){for(let e=0;e<i.length;e++){let s=i[e];if(/[a-zA-Z]/.test(s)&&!t.some((e=>e.toLowerCase()==s.toLowerCase()))){t.push(s);continue e}}t.push("")}return t}function at(e,t,i){var s;let n=i?rt(t.actions):[];return V("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},V("span",{class:"cm-diagnosticText"},t.renderMessage?t.renderMessage(e):t.message),null===(s=t.actions)||void 0===s?void 0:s.map(((i,s)=>{let o=!1,r=s=>{if(s.preventDefault(),o)return;o=!0;let n=Ge(e.state.field(Xe).diagnostics,t);n&&i.apply(e,n.from,n.to)},{name:a}=i,l=n[s]?a.indexOf(n[s]):-1,c=l<0?a:[a.slice(0,l),V("u",a.slice(l,l+1)),a.slice(l+1)];return V("button",{type:"button",class:"cm-diagnosticAction",onclick:r,onmousedown:r,"aria-label":` Action: ${a}${l<0?"":` (access key "${n[s]})"`}.`},c)})),t.source&&V("div",{class:"cm-diagnosticSource"},t.source))}class lt extends a{constructor(e){super(),this.diagnostic=e}eq(e){return e.diagnostic==this.diagnostic}toDOM(){return V("span",{class:"cm-lintPoint cm-lintPoint-"+this.diagnostic.severity})}}class ct{constructor(e,t){this.diagnostic=t,this.id="item_"+Math.floor(4294967295*Math.random()).toString(16),this.dom=at(e,t,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class ht{constructor(e){this.view=e,this.items=[];this.list=V("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:t=>{if(27==t.keyCode)st(this.view),this.view.focus();else if(38==t.keyCode||33==t.keyCode)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(40==t.keyCode||34==t.keyCode)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(36==t.keyCode)this.moveSelection(0);else if(35==t.keyCode)this.moveSelection(this.items.length-1);else if(13==t.keyCode)this.view.focus();else{if(!(t.keyCode>=65&&t.keyCode<=90&&this.selectedIndex>=0))return;{let{diagnostic:i}=this.items[this.selectedIndex],s=rt(i.actions);for(let n=0;n<s.length;n++)if(s[n].toUpperCase().charCodeAt(0)==t.keyCode){let t=Ge(this.view.state.field(Xe).diagnostics,i);t&&i.actions[n].apply(e,t.from,t.to)}}}t.preventDefault()},onclick:e=>{for(let t=0;t<this.items.length;t++)this.items[t].dom.contains(e.target)&&this.moveSelection(t)}}),this.dom=V("div",{class:"cm-panel-lint"},this.list,V("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>st(this.view)},"×")),this.update()}get selectedIndex(){let e=this.view.state.field(Xe).selected;if(!e)return-1;for(let t=0;t<this.items.length;t++)if(this.items[t].diagnostic==e.diagnostic)return t;return-1}update(){let{diagnostics:e,selected:t}=this.view.state.field(Xe),i=0,s=!1,n=null;for(e.between(0,this.view.state.doc.length,((e,o,{spec:r})=>{let a,l=-1;for(let e=i;e<this.items.length;e++)if(this.items[e].diagnostic==r.diagnostic){l=e;break}l<0?(a=new ct(this.view,r.diagnostic),this.items.splice(i,0,a),s=!0):(a=this.items[l],l>i&&(this.items.splice(i,l-i),s=!0)),t&&a.diagnostic==t.diagnostic?a.dom.hasAttribute("aria-selected")||(a.dom.setAttribute("aria-selected","true"),n=a):a.dom.hasAttribute("aria-selected")&&a.dom.removeAttribute("aria-selected"),i++}));i<this.items.length&&!(1==this.items.length&&this.items[0].diagnostic.from<0);)s=!0,this.items.pop();0==this.items.length&&(this.items.push(new ct(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),s=!0),n?(this.list.setAttribute("aria-activedescendant",n.id),this.view.requestMeasure({key:this,read:()=>({sel:n.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:e,panel:t})=>{let i=t.height/this.list.offsetHeight;e.top<t.top?this.list.scrollTop-=(t.top-e.top)/i:e.bottom>t.bottom&&(this.list.scrollTop+=(e.bottom-t.bottom)/i)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let e=this.list.firstChild;function t(){let t=e;e=t.nextSibling,t.remove()}for(let i of this.items)if(i.dom.parentNode==this.list){for(;e!=i.dom;)t();e=i.dom.nextSibling}else this.list.insertBefore(i.dom,e);for(;e;)t()}moveSelection(e){if(this.selectedIndex<0)return;let t=Ge(this.view.state.field(Xe).diagnostics,this.items[e].diagnostic);t&&this.view.dispatch({selection:{anchor:t.from,head:t.to},scrollIntoView:!0,effects:Je.of(t)})}static open(e){return new ht(e)}}function dt(e){return function(e,t='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${t}>${encodeURIComponent(e)}</svg>')`}(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${e}" fill="none" stroke-width=".7"/>`,'width="6" height="3"')}const ut=i.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:dt("#d11")},".cm-lintRange-warning":{backgroundImage:dt("orange")},".cm-lintRange-info":{backgroundImage:dt("#999")},".cm-lintRange-hint":{backgroundImage:dt("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}}),ft=[Xe,i.decorations.compute([Xe],(e=>{let{selected:i,panel:s}=e.field(Xe);return i&&s&&i.from!=i.to?t.set([et.range(i.from,i.to)]):t.none})),r(tt,{hideOn:function(e,t){let i=t.pos,s=t.end||i,n=e.state.facet(ot).hideOn(e,i,s);if(null!=n)return n;let o=e.startState.doc.lineAt(t.pos);return!(!e.effects.some((e=>e.is(Ye)))&&!e.changes.touchesRange(o.from,Math.max(o.to,s)))}}),ut],mt=(()=>[l(),c(),h(),$(),D(),d(),u(),L.allowMultipleSelections.of(!0),W(),F(I,{fallback:!0}),P(),z(),B(),f(),m(),p(),[he,ce],g.of([...j,...O,...ze,...T,...E,..._,...nt])])(),pt=(()=>[h(),$(),d(),F(I,{fallback:!0}),g.of([...O,...T])])();export{i as EditorView,mt as basicSetup,pt as minimalSetup};
2
- //# sourceMappingURL=codemirror-BFaBdIfQ.js.map
@@ -1,2 +0,0 @@
1
- import{Annotation as e,Facet as t,EditorSelection as n,Text as r,findClusterBreak as o,countColumn as l,combineConfig as s,StateField as a,Transaction as i,ChangeSet as c,ChangeDesc as f,StateEffect as u,CharCategory as h}from"./codemirror_state-1d1uncXx.js";import{E as m,D as d}from"./codemirror_view-aIuSN42d.js";import{q as p,r as g,u as y,v,s as A,w as k,b as w,i as S}from"./codemirror_language-4kk4Aqm3.js";const D=e=>{let{state:t}=e,n=t.doc.lineAt(t.selection.main.from),r=I(e.state,n.from);return r.line?M(e):!!r.block&&T(e)};function x(e,t){return({state:n,dispatch:r})=>{if(n.readOnly)return!1;let o=e(t,n);return!!o&&(r(n.update(o)),!0)}}const M=x(L,0),B=x(L,1),C=x(L,2),E=x(R,0),O=x(R,1),b=x(R,2),T=x(((e,t)=>R(e,t,function(e){let t=[];for(let n of e.selection.ranges){let r=e.doc.lineAt(n.from),o=n.to<=r.to?r:e.doc.lineAt(n.to),l=t.length-1;l>=0&&t[l].to>r.from?t[l].to=o.to:t.push({from:r.from+/^\s*/.exec(r.text)[0].length,to:o.to})}return t}(t))),0);function I(e,t){let n=e.languageDataAt("commentTokens",t);return n.length?n[0]:{}}const V=50;function R(e,t,n=t.selection.ranges){let r=n.map((e=>I(t,e.from).block));if(!r.every((e=>e)))return null;let o=n.map(((e,n)=>function(e,{open:t,close:n},r,o){let l,s,a=e.sliceDoc(r-V,r),i=e.sliceDoc(o,o+V),c=/\s*$/.exec(a)[0].length,f=/^\s*/.exec(i)[0].length,u=a.length-c;if(a.slice(u-t.length,u)==t&&i.slice(f,f+n.length)==n)return{open:{pos:r-c,margin:c&&1},close:{pos:o+f,margin:f&&1}};o-r<=2*V?l=s=e.sliceDoc(r,o):(l=e.sliceDoc(r,r+V),s=e.sliceDoc(o-V,o));let h=/^\s*/.exec(l)[0].length,m=/\s*$/.exec(s)[0].length,d=s.length-m-n.length;return l.slice(h,h+t.length)==t&&s.slice(d,d+n.length)==n?{open:{pos:r+h+t.length,margin:/\s/.test(l.charAt(h+t.length))?1:0},close:{pos:o-m-n.length,margin:/\s/.test(s.charAt(d-1))?1:0}}:null}(t,r[n],e.from,e.to)));if(2!=e&&!o.every((e=>e)))return{changes:t.changes(n.map(((e,t)=>o[t]?[]:[{from:e.from,insert:r[t].open+" "},{from:e.to,insert:" "+r[t].close}])))};if(1!=e&&o.some((e=>e))){let e=[];for(let t,n=0;n<o.length;n++)if(t=o[n]){let o=r[n],{open:l,close:s}=t;e.push({from:l.pos-o.open.length,to:l.pos+l.margin},{from:s.pos-s.margin,to:s.pos+o.close.length})}return{changes:e}}return null}function L(e,t,n=t.selection.ranges){let r=[],o=-1;for(let{from:e,to:l}of n){let n=r.length,s=1e9,a=I(t,e).line;if(a){for(let n=e;n<=l;){let i=t.doc.lineAt(n);if(i.from>o&&(e==l||l>i.from)){o=i.from;let e=/^\s*/.exec(i.text)[0].length,t=e==i.length,n=i.text.slice(e,e+a.length)==a?e:-1;e<i.text.length&&e<s&&(s=e),r.push({line:i,comment:n,token:a,indent:e,empty:t,single:!1})}n=i.to+1}if(s<1e9)for(let e=n;e<r.length;e++)r[e].indent<r[e].line.text.length&&(r[e].indent=s);r.length==n+1&&(r[n].single=!0)}}if(2!=e&&r.some((e=>e.comment<0&&(!e.empty||e.single)))){let e=[];for(let{line:t,token:n,indent:o,empty:l,single:s}of r)!s&&l||e.push({from:t.from+o,insert:n+" "});let n=t.changes(e);return{changes:n,selection:t.selection.map(n,1)}}if(1!=e&&r.some((e=>e.comment>=0))){let e=[];for(let{line:t,comment:n,token:o}of r)if(n>=0){let r=t.from+n,l=r+o.length;" "==t.text[l-t.from]&&l++,e.push({from:r,to:l})}return{changes:e}}return null}const J=e.define(),N=e.define(),H=t.define(),U=t.define({combine:e=>s(e,{minDepth:100,newGroupDelay:500,joinToEvent:(e,t)=>t},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,t)=>(n,r)=>e(n,r)||t(n,r)})}),z=a.define({create:()=>ae.empty,update(e,t){let n=t.state.facet(U),r=t.annotation(J);if(r){let o=X.fromTransaction(t,r.selection),l=r.side,s=0==l?e.undone:e.done;return s=o?Y(s,s.length,n.minDepth,o):ne(s,t.startState.selection),new ae(0==l?r.rest:s,0==l?s:r.rest)}let o=t.annotation(N);if("full"!=o&&"before"!=o||(e=e.isolate()),!1===t.annotation(i.addToHistory))return t.changes.empty?e:e.addMapping(t.changes.desc);let l=X.fromTransaction(t),s=t.annotation(i.time),a=t.annotation(i.userEvent);return l?e=e.addChanges(l,s,a,n,t):t.selection&&(e=e.addSelection(t.startState.selection,s,a,n.newGroupDelay)),"full"!=o&&"after"!=o||(e=e.isolate()),e},toJSON:e=>({done:e.done.map((e=>e.toJSON())),undone:e.undone.map((e=>e.toJSON()))}),fromJSON:e=>new ae(e.done.map(X.fromJSON),e.undone.map(X.fromJSON))});function j(e={}){return[z,U.of(e),m.domEventHandlers({beforeinput(e,t){let n="historyUndo"==e.inputType?P:"historyRedo"==e.inputType?W:null;return!!n&&(e.preventDefault(),n(t))}})]}const q=z;function G(e,t){return function({state:n,dispatch:r}){if(!t&&n.readOnly)return!1;let o=n.field(z,!1);if(!o)return!1;let l=o.pop(e,n,t);return!!l&&(r(l),!0)}}const P=G(0,!1),W=G(1,!1),$=G(0,!0),_=G(1,!0);function F(e){return function(t){let n=t.field(z,!1);if(!n)return 0;let r=0==e?n.done:n.undone;return r.length-(r.length&&!r[0].changes?1:0)}}const K=F(0),Q=F(1);class X{constructor(e,t,n,r,o){this.changes=e,this.effects=t,this.mapped=n,this.startSelection=r,this.selectionsAfter=o}setSelAfter(e){return new X(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,t,n;return{changes:null===(e=this.changes)||void 0===e?void 0:e.toJSON(),mapped:null===(t=this.mapped)||void 0===t?void 0:t.toJSON(),startSelection:null===(n=this.startSelection)||void 0===n?void 0:n.toJSON(),selectionsAfter:this.selectionsAfter.map((e=>e.toJSON()))}}static fromJSON(e){return new X(e.changes&&c.fromJSON(e.changes),[],e.mapped&&f.fromJSON(e.mapped),e.startSelection&&n.fromJSON(e.startSelection),e.selectionsAfter.map(n.fromJSON))}static fromTransaction(e,t){let n=ee;for(let t of e.startState.facet(H)){let r=t(e);r.length&&(n=n.concat(r))}return!n.length&&e.changes.empty?null:new X(e.changes.invert(e.startState.doc),n,void 0,t||e.startState.selection,ee)}static selection(e){return new X(void 0,ee,void 0,void 0,e)}}function Y(e,t,n,r){let o=t+1>n+20?t-n-1:0,l=e.slice(o,t);return l.push(r),l}function Z(e,t){return e.length?t.length?e.concat(t):e:t}const ee=[],te=200;function ne(e,t){if(e.length){let n=e[e.length-1],r=n.selectionsAfter.slice(Math.max(0,n.selectionsAfter.length-te));return r.length&&r[r.length-1].eq(t)?e:(r.push(t),Y(e,e.length-1,1e9,n.setSelAfter(r)))}return[X.selection([t])]}function re(e){let t=e[e.length-1],n=e.slice();return n[e.length-1]=t.setSelAfter(t.selectionsAfter.slice(0,t.selectionsAfter.length-1)),n}function oe(e,t){if(!e.length)return e;let n=e.length,r=ee;for(;n;){let o=le(e[n-1],t,r);if(o.changes&&!o.changes.empty||o.effects.length){let t=e.slice(0,n);return t[n-1]=o,t}t=o.mapped,n--,r=o.selectionsAfter}return r.length?[X.selection(r)]:ee}function le(e,t,n){let r=Z(e.selectionsAfter.length?e.selectionsAfter.map((e=>e.map(t))):ee,n);if(!e.changes)return X.selection(r);let o=e.changes.map(t),l=t.mapDesc(e.changes,!0),s=e.mapped?e.mapped.composeDesc(l):l;return new X(o,u.mapEffects(e.effects,t),s,e.startSelection.map(l),r)}const se=/^(input\.type|delete)($|\.)/;class ae{constructor(e,t,n=0,r=void 0){this.done=e,this.undone=t,this.prevTime=n,this.prevUserEvent=r}isolate(){return this.prevTime?new ae(this.done,this.undone):this}addChanges(e,t,n,r,o){let l=this.done,s=l[l.length-1];return l=s&&s.changes&&!s.changes.empty&&e.changes&&(!n||se.test(n))&&(!s.selectionsAfter.length&&t-this.prevTime<r.newGroupDelay&&r.joinToEvent(o,function(e,t){let n=[],r=!1;return e.iterChangedRanges(((e,t)=>n.push(e,t))),t.iterChangedRanges(((e,t,o,l)=>{for(let e=0;e<n.length;){let t=n[e++],s=n[e++];l>=t&&o<=s&&(r=!0)}})),r}(s.changes,e.changes))||"input.type.compose"==n)?Y(l,l.length-1,r.minDepth,new X(e.changes.compose(s.changes),Z(u.mapEffects(e.effects,s.changes),s.effects),s.mapped,s.startSelection,ee)):Y(l,l.length,r.minDepth,e),new ae(l,ee,t,n)}addSelection(e,t,n,r){let o=this.done.length?this.done[this.done.length-1].selectionsAfter:ee;return o.length>0&&t-this.prevTime<r&&n==this.prevUserEvent&&n&&/^select($|\.)/.test(n)&&(l=o[o.length-1],s=e,l.ranges.length==s.ranges.length&&0===l.ranges.filter(((e,t)=>e.empty!=s.ranges[t].empty)).length)?this:new ae(ne(this.done,e),this.undone,t,n);var l,s}addMapping(e){return new ae(oe(this.done,e),oe(this.undone,e),this.prevTime,this.prevUserEvent)}pop(e,t,n){let r=0==e?this.done:this.undone;if(0==r.length)return null;let o=r[r.length-1],l=o.selectionsAfter[0]||t.selection;if(n&&o.selectionsAfter.length)return t.update({selection:o.selectionsAfter[o.selectionsAfter.length-1],annotations:J.of({side:e,rest:re(r),selection:l}),userEvent:0==e?"select.undo":"select.redo",scrollIntoView:!0});if(o.changes){let n=1==r.length?ee:r.slice(0,r.length-1);return o.mapped&&(n=oe(n,o.mapped)),t.update({changes:o.changes,selection:o.startSelection,effects:o.effects,annotations:J.of({side:e,rest:n,selection:l}),filter:!1,userEvent:0==e?"undo":"redo",scrollIntoView:!0})}return null}}ae.empty=new ae(ee,ee);const ie=[{key:"Mod-z",run:P,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:W,preventDefault:!0},{linux:"Ctrl-Shift-z",run:W,preventDefault:!0},{key:"Mod-u",run:$,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:_,preventDefault:!0}];function ce(e,t){return n.create(e.ranges.map(t),e.mainIndex)}function fe(e,t){return e.update({selection:t,scrollIntoView:!0,userEvent:"select"})}function ue({state:e,dispatch:t},n){let r=ce(e.selection,n);return!r.eq(e.selection,!0)&&(t(fe(e,r)),!0)}function he(e,t){return n.cursor(t?e.to:e.from)}function me(e,t){return ue(e,(n=>n.empty?e.moveByChar(n,t):he(n,t)))}function de(e){return e.textDirectionAt(e.state.selection.main.head)==d.LTR}const pe=e=>me(e,!de(e)),ge=e=>me(e,de(e)),ye=e=>me(e,!0),ve=e=>me(e,!1);function Ae(e,t,r){let l=t.head,s=e.doc.lineAt(l);return l=l==(r?s.to:s.from)?r?Math.min(e.doc.length,s.to+1):Math.max(0,s.from-1):s.from+o(s.text,l-s.from,r),n.cursor(l,r?-1:1)}function ke(e,t){return ue(e,(n=>n.empty?Ae(e.state,n,t):he(n,t)))}const we=e=>ke(e,!0),Se=e=>ke(e,!1);function De(e,t){return ue(e,(n=>n.empty?e.moveByGroup(n,t):he(n,t)))}const xe=e=>De(e,!de(e)),Me=e=>De(e,de(e)),Be=e=>De(e,!0),Ce=e=>De(e,!1),Ee="undefined"!=typeof Intl&&Intl.Segmenter?new Intl.Segmenter(void 0,{granularity:"word"}):null;function Oe(e,t,r){let o=e.state.charCategorizer(t.from),l=h.Space,s=t.from,a=0,i=!1,c=!1,f=!1,u=t=>{if(i)return!1;s+=r?t.length:-t.length;let n,u=o(t);if(u==h.Word&&t.charCodeAt(0)<128&&/[\W_]/.test(t)&&(u=-1),l==h.Space&&(l=u),l!=u)return!1;if(l==h.Word)if(t.toLowerCase()==t){if(!r&&c)return!1;f=!0}else if(f){if(r)return!1;i=!0}else{if(c&&r&&o(n=e.state.sliceDoc(s,s+1))==h.Word&&n.toLowerCase()==n)return!1;c=!0}return a++,!0},m=e.moveByChar(t,r,(e=>(u(e),u)));if(Ee&&l==h.Word&&m.from==t.from+a*(r?1:-1)){let o=Math.min(t.head,m.head),l=Math.max(t.head,m.head),s=e.state.sliceDoc(o,l);if(s.length>1&&/[\u4E00-\uffff]/.test(s)){let e=Array.from(Ee.segment(s));if(e.length>1)return r?n.cursor(t.head+e[1].index,-1):n.cursor(m.head+e[e.length-1].index,1)}}return m}function be(e,t){return ue(e,(n=>n.empty?Oe(e,n,t):he(n,t)))}const Te=e=>be(e,!0),Ie=e=>be(e,!1);function Ve(e,t,n){if(t.type.prop(n))return!0;let r=t.to-t.from;return r&&(r>2||/[^\s,.;:]/.test(e.sliceDoc(t.from,t.to)))||t.firstChild}function Re(e,t,r){let o,l,s=A(e).resolveInner(t.head),a=r?w.closedBy:w.openedBy;for(let n=t.head;;){let t=r?s.childAfter(n):s.childBefore(n);if(!t)break;Ve(e,t,a)?s=t:n=r?t.to:t.from}return l=s.type.prop(a)&&(o=r?v(e,s.from,1):v(e,s.to,-1))&&o.matched?r?o.end.to:o.end.from:r?s.to:s.from,n.cursor(l,r?-1:1)}const Le=e=>ue(e,(t=>Re(e.state,t,!de(e)))),Je=e=>ue(e,(t=>Re(e.state,t,de(e))));function Ne(e,t){return ue(e,(n=>{if(!n.empty)return he(n,t);let r=e.moveVertically(n,t);return r.head!=n.head?r:e.moveToLineBoundary(n,t)}))}const He=e=>Ne(e,!1),Ue=e=>Ne(e,!0);function ze(e){let t,n=e.scrollDOM.clientHeight<e.scrollDOM.scrollHeight-2,r=0,o=0;if(n){for(let t of e.state.facet(m.scrollMargins)){let n=t(e);(null==n?void 0:n.top)&&(r=Math.max(null==n?void 0:n.top,r)),(null==n?void 0:n.bottom)&&(o=Math.max(null==n?void 0:n.bottom,o))}t=e.scrollDOM.clientHeight-r-o}else t=(e.dom.ownerDocument.defaultView||window).innerHeight;return{marginTop:r,marginBottom:o,selfScroll:n,height:Math.max(e.defaultLineHeight,t-5)}}function je(e,t){let n,r=ze(e),{state:o}=e,l=ce(o.selection,(n=>n.empty?e.moveVertically(n,t,r.height):he(n,t)));if(l.eq(o.selection))return!1;if(r.selfScroll){let t=e.coordsAtPos(o.selection.main.head),s=e.scrollDOM.getBoundingClientRect(),a=s.top+r.marginTop,i=s.bottom-r.marginBottom;t&&t.top>a&&t.bottom<i&&(n=m.scrollIntoView(l.main.head,{y:"start",yMargin:t.top-a}))}return e.dispatch(fe(o,l),{effects:n}),!0}const qe=e=>je(e,!1),Ge=e=>je(e,!0);function Pe(e,t,r){let o=e.lineBlockAt(t.head),l=e.moveToLineBoundary(t,r);if(l.head==t.head&&l.head!=(r?o.to:o.from)&&(l=e.moveToLineBoundary(t,r,!1)),!r&&l.head==o.from&&o.length){let r=/^\s*/.exec(e.state.sliceDoc(o.from,Math.min(o.from+100,o.to)))[0].length;r&&t.head!=o.from+r&&(l=n.cursor(o.from+r))}return l}const We=e=>ue(e,(t=>Pe(e,t,!0))),$e=e=>ue(e,(t=>Pe(e,t,!1))),_e=e=>ue(e,(t=>Pe(e,t,!de(e)))),Fe=e=>ue(e,(t=>Pe(e,t,de(e)))),Ke=e=>ue(e,(t=>n.cursor(e.lineBlockAt(t.head).from,1))),Qe=e=>ue(e,(t=>n.cursor(e.lineBlockAt(t.head).to,-1)));function Xe(e,t,r){let o=!1,l=ce(e.selection,(t=>{let l=v(e,t.head,-1)||v(e,t.head,1)||t.head>0&&v(e,t.head-1,1)||t.head<e.doc.length&&v(e,t.head+1,-1);if(!l||!l.end)return t;o=!0;let s=l.start.from==t.head?l.end.to:l.end.from;return r?n.range(t.anchor,s):n.cursor(s)}));return!!o&&(t(fe(e,l)),!0)}const Ye=({state:e,dispatch:t})=>Xe(e,t,!1),Ze=({state:e,dispatch:t})=>Xe(e,t,!0);function et(e,t){let r=ce(e.state.selection,(e=>{let r=t(e);return n.range(e.anchor,r.head,r.goalColumn,r.bidiLevel||void 0)}));return!r.eq(e.state.selection)&&(e.dispatch(fe(e.state,r)),!0)}function tt(e,t){return et(e,(n=>e.moveByChar(n,t)))}const nt=e=>tt(e,!de(e)),rt=e=>tt(e,de(e)),ot=e=>tt(e,!0),lt=e=>tt(e,!1),st=e=>et(e,(t=>Ae(e.state,t,!0))),at=e=>et(e,(t=>Ae(e.state,t,!1)));function it(e,t){return et(e,(n=>e.moveByGroup(n,t)))}const ct=e=>it(e,!de(e)),ft=e=>it(e,de(e)),ut=e=>it(e,!0),ht=e=>it(e,!1);function mt(e,t){return et(e,(n=>Oe(e,n,t)))}const dt=e=>mt(e,!0),pt=e=>mt(e,!1),gt=e=>et(e,(t=>Re(e.state,t,!de(e)))),yt=e=>et(e,(t=>Re(e.state,t,de(e))));function vt(e,t){return et(e,(n=>e.moveVertically(n,t)))}const At=e=>vt(e,!1),kt=e=>vt(e,!0);function wt(e,t){return et(e,(n=>e.moveVertically(n,t,ze(e).height)))}const St=e=>wt(e,!1),Dt=e=>wt(e,!0),xt=e=>et(e,(t=>Pe(e,t,!0))),Mt=e=>et(e,(t=>Pe(e,t,!1))),Bt=e=>et(e,(t=>Pe(e,t,!de(e)))),Ct=e=>et(e,(t=>Pe(e,t,de(e)))),Et=e=>et(e,(t=>n.cursor(e.lineBlockAt(t.head).from))),Ot=e=>et(e,(t=>n.cursor(e.lineBlockAt(t.head).to))),bt=({state:e,dispatch:t})=>(t(fe(e,{anchor:0})),!0),Tt=({state:e,dispatch:t})=>(t(fe(e,{anchor:e.doc.length})),!0),It=({state:e,dispatch:t})=>(t(fe(e,{anchor:e.selection.main.anchor,head:0})),!0),Vt=({state:e,dispatch:t})=>(t(fe(e,{anchor:e.selection.main.anchor,head:e.doc.length})),!0),Rt=({state:e,dispatch:t})=>(t(e.update({selection:{anchor:0,head:e.doc.length},userEvent:"select"})),!0),Lt=({state:e,dispatch:t})=>{let r=en(e).map((({from:t,to:r})=>n.range(t,Math.min(r+1,e.doc.length))));return t(e.update({selection:n.create(r),userEvent:"select"})),!0},Jt=({state:e,dispatch:t})=>{let r=ce(e.selection,(t=>{let r=A(e),o=r.resolveStack(t.from,1);if(t.empty){let e=r.resolveStack(t.from,-1);e.node.from>=o.node.from&&e.node.to<=o.node.to&&(o=e)}for(let e=o;e;e=e.next){let{node:r}=e;if((r.from<t.from&&r.to>=t.to||r.to>t.to&&r.from<=t.from)&&e.next)return n.range(r.to,r.from)}return t}));return!r.eq(e.selection)&&(t(fe(e,r)),!0)},Nt=({state:e,dispatch:t})=>{let r=e.selection,o=null;return r.ranges.length>1?o=n.create([r.main]):r.main.empty||(o=n.create([n.cursor(r.main.head)])),!!o&&(t(fe(e,o)),!0)};function Ht(e,t){if(e.state.readOnly)return!1;let r="delete.selection",{state:o}=e,l=o.changeByRange((o=>{let{from:l,to:s}=o;if(l==s){let n=t(o);n<l?(r="delete.backward",n=Ut(e,n,!1)):n>l&&(r="delete.forward",n=Ut(e,n,!0)),l=Math.min(l,n),s=Math.max(s,n)}else l=Ut(e,l,!1),s=Ut(e,s,!0);return l==s?{range:o}:{changes:{from:l,to:s},range:n.cursor(l,l<o.head?-1:1)}}));return!l.changes.empty&&(e.dispatch(o.update(l,{scrollIntoView:!0,userEvent:r,effects:"delete.selection"==r?m.announce.of(o.phrase("Selection deleted")):void 0})),!0)}function Ut(e,t,n){if(e instanceof m)for(let r of e.state.facet(m.atomicRanges).map((t=>t(e))))r.between(t,t,((e,r)=>{e<t&&r>t&&(t=n?r:e)}));return t}const zt=(e,t,n)=>Ht(e,(r=>{let s,a,i=r.from,{state:c}=e,f=c.doc.lineAt(i);if(n&&!t&&i>f.from&&i<f.from+200&&!/[^ \t]/.test(s=f.text.slice(0,i-f.from))){if("\t"==s[s.length-1])return i-1;let e=l(s,c.tabSize)%k(c)||k(c);for(let t=0;t<e&&" "==s[s.length-1-t];t++)i--;a=i}else a=o(f.text,i-f.from,t,t)+f.from,a==i&&f.number!=(t?c.doc.lines:1)?a+=t?1:-1:!t&&/[\ufe00-\ufe0f]/.test(f.text.slice(a-f.from,i-f.from))&&(a=o(f.text,a-f.from,!1,!1)+f.from);return a})),jt=e=>zt(e,!1,!0),qt=e=>zt(e,!1,!1),Gt=e=>zt(e,!0,!1),Pt=(e,t)=>Ht(e,(n=>{let r=n.head,{state:l}=e,s=l.doc.lineAt(r),a=l.charCategorizer(r);for(let e=null;;){if(r==(t?s.to:s.from)){r==n.head&&s.number!=(t?l.doc.lines:1)&&(r+=t?1:-1);break}let i=o(s.text,r-s.from,t)+s.from,c=s.text.slice(Math.min(r,i)-s.from,Math.max(r,i)-s.from),f=a(c);if(null!=e&&f!=e)break;" "==c&&r==n.head||(e=f),r=i}return r})),Wt=e=>Pt(e,!1),$t=e=>Pt(e,!0),_t=e=>Ht(e,(t=>{let n=e.lineBlockAt(t.head).to;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)})),Ft=e=>Ht(e,(t=>{let n=e.lineBlockAt(t.head).from;return t.head>n?n:Math.max(0,t.head-1)})),Kt=e=>Ht(e,(t=>{let n=e.moveToLineBoundary(t,!1).head;return t.head>n?n:Math.max(0,t.head-1)})),Qt=e=>Ht(e,(t=>{let n=e.moveToLineBoundary(t,!0).head;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)})),Xt=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=[];for(let t=0,r="",o=e.doc.iter();;){if(o.next(),o.lineBreak||o.done){let e=r.search(/\s+$/);if(e>-1&&n.push({from:t-(r.length-e),to:t}),o.done)break;r=""}else r=o.value;t+=o.value.length}return!!n.length&&(t(e.update({changes:n,userEvent:"delete"})),!0)},Yt=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let o=e.changeByRange((e=>({changes:{from:e.from,to:e.to,insert:r.of(["",""])},range:n.cursor(e.from)})));return t(e.update(o,{scrollIntoView:!0,userEvent:"input"})),!0},Zt=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let r=e.changeByRange((t=>{if(!t.empty||0==t.from||t.from==e.doc.length)return{range:t};let r=t.from,l=e.doc.lineAt(r),s=r==l.from?r-1:o(l.text,r-l.from,!1)+l.from,a=r==l.to?r+1:o(l.text,r-l.from,!0)+l.from;return{changes:{from:s,to:a,insert:e.doc.slice(r,a).append(e.doc.slice(s,r))},range:n.cursor(a)}}));return!r.changes.empty&&(t(e.update(r,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function en(e){let t=[],n=-1;for(let r of e.selection.ranges){let o=e.doc.lineAt(r.from),l=e.doc.lineAt(r.to);if(r.empty||r.to!=l.from||(l=e.doc.lineAt(r.to-1)),n>=o.number){let e=t[t.length-1];e.to=l.to,e.ranges.push(r)}else t.push({from:o.from,to:l.to,ranges:[r]});n=l.number+1}return t}function tn(e,t,r){if(e.readOnly)return!1;let o=[],l=[];for(let t of en(e)){if(r?t.to==e.doc.length:0==t.from)continue;let s=e.doc.lineAt(r?t.to+1:t.from-1),a=s.length+1;if(r){o.push({from:t.to,to:s.to},{from:t.from,insert:s.text+e.lineBreak});for(let r of t.ranges)l.push(n.range(Math.min(e.doc.length,r.anchor+a),Math.min(e.doc.length,r.head+a)))}else{o.push({from:s.from,to:t.from},{from:t.to,insert:e.lineBreak+s.text});for(let e of t.ranges)l.push(n.range(e.anchor-a,e.head-a))}}return!!o.length&&(t(e.update({changes:o,scrollIntoView:!0,selection:n.create(l,e.selection.mainIndex),userEvent:"move.line"})),!0)}const nn=({state:e,dispatch:t})=>tn(e,t,!1),rn=({state:e,dispatch:t})=>tn(e,t,!0);function on(e,t,n){if(e.readOnly)return!1;let r=[];for(let t of en(e))n?r.push({from:t.from,insert:e.doc.slice(t.from,t.to)+e.lineBreak}):r.push({from:t.to,insert:e.lineBreak+e.doc.slice(t.from,t.to)});return t(e.update({changes:r,scrollIntoView:!0,userEvent:"input.copyline"})),!0}const ln=({state:e,dispatch:t})=>on(e,t,!1),sn=({state:e,dispatch:t})=>on(e,t,!0),an=e=>{if(e.state.readOnly)return!1;let{state:t}=e,n=t.changes(en(t).map((({from:e,to:n})=>(e>0?e--:n<t.doc.length&&n++,{from:e,to:n})))),r=ce(t.selection,(t=>{let n;if(e.lineWrapping){let r=e.lineBlockAt(t.head),o=e.coordsAtPos(t.head,t.assoc||1);o&&(n=r.bottom+e.documentTop-o.bottom+e.defaultLineHeight/2)}return e.moveVertically(t,!0,n)})).map(n);return e.dispatch({changes:n,selection:r,scrollIntoView:!0,userEvent:"delete.line"}),!0},cn=({state:e,dispatch:t})=>(t(e.update(e.replaceSelection(e.lineBreak),{scrollIntoView:!0,userEvent:"input"})),!0),fn=({state:e,dispatch:t})=>(t(e.update(e.changeByRange((t=>{let r=/^\s*/.exec(e.doc.lineAt(t.from).text)[0];return{changes:{from:t.from,to:t.to,insert:e.lineBreak+r},range:n.cursor(t.from+r.length+1)}})),{scrollIntoView:!0,userEvent:"input"})),!0);const un=mn(!1),hn=mn(!0);function mn(e){return({state:t,dispatch:o})=>{if(t.readOnly)return!1;let s=t.changeByRange((o=>{let{from:s,to:a}=o,i=t.doc.lineAt(s),c=!e&&s==a&&function(e,t){if(/\(\)|\[\]|\{\}/.test(e.sliceDoc(t-1,t+1)))return{from:t,to:t};let n,r=A(e).resolveInner(t),o=r.childBefore(t),l=r.childAfter(t);return o&&l&&o.to<=t&&l.from>=t&&(n=o.type.prop(w.closedBy))&&n.indexOf(l.name)>-1&&e.doc.lineAt(o.to).from==e.doc.lineAt(l.from).from&&!/\S/.test(e.sliceDoc(o.to,l.from))?{from:o.to,to:l.from}:null}(t,s);e&&(s=a=(a<=i.to?i:t.doc.lineAt(a)).to);let f=new p(t,{simulateBreak:s,simulateDoubleBreak:!!c}),u=g(f,s);for(null==u&&(u=l(/^\s*/.exec(t.doc.lineAt(s).text)[0],t.tabSize));a<i.to&&/\s/.test(i.text[a-i.from]);)a++;c?({from:s,to:a}=c):s>i.from&&s<i.from+100&&!/\S/.test(i.text.slice(0,s))&&(s=i.from);let h=["",y(t,u)];return c&&h.push(y(t,f.lineIndent(i.from,-1))),{changes:{from:s,to:a,insert:r.of(h)},range:n.cursor(s+1+h[1].length)}}));return o(t.update(s,{scrollIntoView:!0,userEvent:"input"})),!0}}function dn(e,t){let r=-1;return e.changeByRange((o=>{let l=[];for(let n=o.from;n<=o.to;){let s=e.doc.lineAt(n);s.number>r&&(o.empty||o.to>s.from)&&(t(s,l,o),r=s.number),n=s.to+1}let s=e.changes(l);return{changes:l,range:n.range(s.mapPos(o.anchor,1),s.mapPos(o.head,1))}}))}const pn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=Object.create(null),r=new p(e,{overrideIndentation:e=>{let t=n[e];return null==t?-1:t}}),o=dn(e,((t,o,l)=>{let s=g(r,t.from);if(null==s)return;/\S/.test(t.text)||(s=0);let a=/^\s*/.exec(t.text)[0],i=y(e,s);(a!=i||l.from<t.from+a.length)&&(n[t.from]=s,o.push({from:t.from,to:t.from+a.length,insert:i}))}));return o.changes.empty||t(e.update(o,{userEvent:"indent"})),!0},gn=({state:e,dispatch:t})=>!e.readOnly&&(t(e.update(dn(e,((t,n)=>{n.push({from:t.from,insert:e.facet(S)})})),{userEvent:"input.indent"})),!0),yn=({state:e,dispatch:t})=>!e.readOnly&&(t(e.update(dn(e,((t,n)=>{let r=/^\s*/.exec(t.text)[0];if(!r)return;let o=l(r,e.tabSize),s=0,a=y(e,Math.max(0,o-k(e)));for(;s<r.length&&s<a.length&&r.charCodeAt(s)==a.charCodeAt(s);)s++;n.push({from:t.from+s,to:t.from+r.length,insert:a.slice(s)})})),{userEvent:"delete.dedent"})),!0),vn=e=>(e.setTabFocusMode(),!0),An=e=>(e.setTabFocusMode(2e3),!0),kn=({state:e,dispatch:t})=>e.selection.ranges.some((e=>!e.empty))?gn({state:e,dispatch:t}):(t(e.update(e.replaceSelection("\t"),{scrollIntoView:!0,userEvent:"input"})),!0),wn=[{key:"Ctrl-b",run:pe,shift:nt,preventDefault:!0},{key:"Ctrl-f",run:ge,shift:rt},{key:"Ctrl-p",run:He,shift:At},{key:"Ctrl-n",run:Ue,shift:kt},{key:"Ctrl-a",run:Ke,shift:Et},{key:"Ctrl-e",run:Qe,shift:Ot},{key:"Ctrl-d",run:Gt},{key:"Ctrl-h",run:jt},{key:"Ctrl-k",run:_t},{key:"Ctrl-Alt-h",run:Wt},{key:"Ctrl-o",run:Yt},{key:"Ctrl-t",run:Zt},{key:"Ctrl-v",run:Ge}],Sn=[{key:"ArrowLeft",run:pe,shift:nt,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:xe,shift:ct,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:_e,shift:Bt,preventDefault:!0},{key:"ArrowRight",run:ge,shift:rt,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:Me,shift:ft,preventDefault:!0},{mac:"Cmd-ArrowRight",run:Fe,shift:Ct,preventDefault:!0},{key:"ArrowUp",run:He,shift:At,preventDefault:!0},{mac:"Cmd-ArrowUp",run:bt,shift:It},{mac:"Ctrl-ArrowUp",run:qe,shift:St},{key:"ArrowDown",run:Ue,shift:kt,preventDefault:!0},{mac:"Cmd-ArrowDown",run:Tt,shift:Vt},{mac:"Ctrl-ArrowDown",run:Ge,shift:Dt},{key:"PageUp",run:qe,shift:St},{key:"PageDown",run:Ge,shift:Dt},{key:"Home",run:$e,shift:Mt,preventDefault:!0},{key:"Mod-Home",run:bt,shift:It},{key:"End",run:We,shift:xt,preventDefault:!0},{key:"Mod-End",run:Tt,shift:Vt},{key:"Enter",run:un,shift:un},{key:"Mod-a",run:Rt},{key:"Backspace",run:jt,shift:jt},{key:"Delete",run:Gt},{key:"Mod-Backspace",mac:"Alt-Backspace",run:Wt},{key:"Mod-Delete",mac:"Alt-Delete",run:$t},{mac:"Mod-Backspace",run:Kt},{mac:"Mod-Delete",run:Qt}].concat(wn.map((e=>({mac:e.key,run:e.run,shift:e.shift})))),Dn=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:Le,shift:gt},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:Je,shift:yt},{key:"Alt-ArrowUp",run:nn},{key:"Shift-Alt-ArrowUp",run:ln},{key:"Alt-ArrowDown",run:rn},{key:"Shift-Alt-ArrowDown",run:sn},{key:"Escape",run:Nt},{key:"Mod-Enter",run:hn},{key:"Alt-l",mac:"Ctrl-l",run:Lt},{key:"Mod-i",run:Jt,preventDefault:!0},{key:"Mod-[",run:yn},{key:"Mod-]",run:gn},{key:"Mod-Alt-\\",run:pn},{key:"Shift-Mod-k",run:an},{key:"Shift-Mod-\\",run:Ye},{key:"Mod-/",run:D},{key:"Alt-A",run:E},{key:"Ctrl-m",mac:"Shift-Alt-m",run:vn}].concat(Sn),xn={key:"Tab",run:gn,shift:yn};export{O as blockComment,b as blockUncomment,sn as copyLineDown,ln as copyLineUp,ve as cursorCharBackward,Se as cursorCharBackwardLogical,ye as cursorCharForward,we as cursorCharForwardLogical,pe as cursorCharLeft,ge as cursorCharRight,Tt as cursorDocEnd,bt as cursorDocStart,Ce as cursorGroupBackward,Be as cursorGroupForward,xe as cursorGroupLeft,Me as cursorGroupRight,$e as cursorLineBoundaryBackward,We as cursorLineBoundaryForward,_e as cursorLineBoundaryLeft,Fe as cursorLineBoundaryRight,Ue as cursorLineDown,Qe as cursorLineEnd,Ke as cursorLineStart,He as cursorLineUp,Ye as cursorMatchingBracket,Ge as cursorPageDown,qe as cursorPageUp,Ie as cursorSubwordBackward,Te as cursorSubwordForward,Le as cursorSyntaxLeft,Je as cursorSyntaxRight,Dn as defaultKeymap,jt as deleteCharBackward,qt as deleteCharBackwardStrict,Gt as deleteCharForward,Wt as deleteGroupBackward,$t as deleteGroupForward,an as deleteLine,Kt as deleteLineBoundaryBackward,Qt as deleteLineBoundaryForward,_t as deleteToLineEnd,Ft as deleteToLineStart,Xt as deleteTrailingWhitespace,wn as emacsStyleKeymap,j as history,q as historyField,ie as historyKeymap,yn as indentLess,gn as indentMore,pn as indentSelection,xn as indentWithTab,hn as insertBlankLine,cn as insertNewline,un as insertNewlineAndIndent,fn as insertNewlineKeepIndent,kn as insertTab,H as invertedEffects,N as isolateHistory,B as lineComment,C as lineUncomment,rn as moveLineDown,nn as moveLineUp,W as redo,Q as redoDepth,_ as redoSelection,Rt as selectAll,lt as selectCharBackward,at as selectCharBackwardLogical,ot as selectCharForward,st as selectCharForwardLogical,nt as selectCharLeft,rt as selectCharRight,Vt as selectDocEnd,It as selectDocStart,ht as selectGroupBackward,ut as selectGroupForward,ct as selectGroupLeft,ft as selectGroupRight,Lt as selectLine,Mt as selectLineBoundaryBackward,xt as selectLineBoundaryForward,Bt as selectLineBoundaryLeft,Ct as selectLineBoundaryRight,kt as selectLineDown,Ot as selectLineEnd,Et as selectLineStart,At as selectLineUp,Ze as selectMatchingBracket,Dt as selectPageDown,St as selectPageUp,Jt as selectParentSyntax,pt as selectSubwordBackward,dt as selectSubwordForward,gt as selectSyntaxLeft,yt as selectSyntaxRight,Nt as simplifySelection,Yt as splitLine,Sn as standardKeymap,An as temporarilySetTabFocusMode,E as toggleBlockComment,T as toggleBlockCommentByLine,D as toggleComment,M as toggleLineComment,vn as toggleTabFocusMode,Zt as transposeChars,P as undo,K as undoDepth,$ as undoSelection};
2
- //# sourceMappingURL=codemirror_commands-CvnouHng.js.map