@pyscript/core 0.4.20 → 0.4.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/codemirror-Dr2Hgejs.js +2 -0
  2. package/dist/{codemirror-Da0uB6D0.js.map → codemirror-Dr2Hgejs.js.map} +1 -1
  3. package/dist/{codemirror_commands-Cda0Zxd7.js → codemirror_commands-MgxtVkrD.js} +2 -2
  4. package/dist/codemirror_commands-MgxtVkrD.js.map +1 -0
  5. package/dist/{codemirror_lang-python-DIyWB5tk.js → codemirror_lang-python-luVWQrEE.js} +2 -2
  6. package/dist/{codemirror_lang-python-DIyWB5tk.js.map → codemirror_lang-python-luVWQrEE.js.map} +1 -1
  7. package/dist/{codemirror_language-DCl5sMoK.js → codemirror_language-_XiX6II0.js} +2 -2
  8. package/dist/{codemirror_language-DCl5sMoK.js.map → codemirror_language-_XiX6II0.js.map} +1 -1
  9. package/dist/{codemirror_view-Bz8y6BoV.js → codemirror_view-C0PMO2z_.js} +2 -2
  10. package/dist/codemirror_view-C0PMO2z_.js.map +1 -0
  11. package/dist/core-BYYQYOhK.js +3 -0
  12. package/dist/core-BYYQYOhK.js.map +1 -0
  13. package/dist/core.js +1 -1
  14. package/dist/{deprecations-manager-Dj-XJTYm.js → deprecations-manager-CKkQd0VB.js} +2 -2
  15. package/dist/{deprecations-manager-Dj-XJTYm.js.map → deprecations-manager-CKkQd0VB.js.map} +1 -1
  16. package/dist/{error-CYOIlKpM.js → error-2Z4e847Z.js} +2 -2
  17. package/dist/{error-CYOIlKpM.js.map → error-2Z4e847Z.js.map} +1 -1
  18. package/dist/{index-2LL_kWLg.js → index-CTWZX_TW.js} +2 -2
  19. package/dist/{index-2LL_kWLg.js.map → index-CTWZX_TW.js.map} +1 -1
  20. package/dist/{py-editor-s2k8SC31.js → py-editor-CaZp_wYL.js} +2 -2
  21. package/dist/{py-editor-s2k8SC31.js.map → py-editor-CaZp_wYL.js.map} +1 -1
  22. package/dist/py-terminal-CvVsSZex.js +2 -0
  23. package/dist/py-terminal-CvVsSZex.js.map +1 -0
  24. package/dist/xterm_addon-web-links-Cnej-nJ6.js +2 -0
  25. package/dist/xterm_addon-web-links-Cnej-nJ6.js.map +1 -0
  26. package/dist/zip-BVYJ4_a2.js.map +1 -1
  27. package/dist.zip +0 -0
  28. package/package.json +9 -8
  29. package/src/3rd-party/xterm_addon-web-links.js +7 -0
  30. package/src/core.js +4 -4
  31. package/src/hooks.js +5 -4
  32. package/src/plugins/py-terminal.js +10 -5
  33. package/src/stdlib/pyscript/display.py +11 -11
  34. package/src/stdlib/pyscript.js +1 -1
  35. package/src/stdlib.js +30 -5
  36. package/types/3rd-party/xterm_addon-web-links.d.ts +4 -0
  37. package/types/core.d.ts +3 -2
  38. package/types/hooks.d.ts +1 -1
  39. package/types/stdlib.d.ts +2 -2
  40. package/dist/codemirror-Da0uB6D0.js +0 -2
  41. package/dist/codemirror_commands-Cda0Zxd7.js.map +0 -1
  42. package/dist/codemirror_view-Bz8y6BoV.js.map +0 -1
  43. package/dist/core-2NwtOg82.js +0 -3
  44. package/dist/core-2NwtOg82.js.map +0 -1
  45. package/dist/py-terminal-4lUBhmlJ.js +0 -2
  46. package/dist/py-terminal-4lUBhmlJ.js.map +0 -1
package/dist.zip ADDED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pyscript/core",
3
- "version": "0.4.20",
3
+ "version": "0.4.22",
4
4
  "type": "module",
5
5
  "description": "PyScript",
6
6
  "module": "./index.js",
@@ -42,31 +42,32 @@
42
42
  "dependencies": {
43
43
  "@ungap/with-resolvers": "^0.1.0",
44
44
  "basic-devtools": "^0.1.6",
45
- "polyscript": "^0.12.3",
45
+ "polyscript": "^0.12.5",
46
46
  "sticky-module": "^0.1.1",
47
47
  "to-json-callback": "^0.1.1",
48
48
  "type-checked-collections": "^0.1.7"
49
49
  },
50
50
  "devDependencies": {
51
- "@codemirror/commands": "^6.3.3",
51
+ "@codemirror/commands": "^6.5.0",
52
52
  "@codemirror/lang-python": "^6.1.5",
53
53
  "@codemirror/language": "^6.10.1",
54
54
  "@codemirror/state": "^6.4.1",
55
- "@codemirror/view": "^6.26.2",
56
- "@playwright/test": "^1.43.0",
55
+ "@codemirror/view": "^6.26.3",
56
+ "@playwright/test": "^1.43.1",
57
57
  "@rollup/plugin-commonjs": "^25.0.7",
58
58
  "@rollup/plugin-node-resolve": "^15.2.3",
59
59
  "@rollup/plugin-terser": "^0.4.4",
60
60
  "@webreflection/toml-j0.4": "^1.1.3",
61
61
  "@xterm/addon-fit": "^0.10.0",
62
+ "@xterm/addon-web-links": "^0.11.0",
62
63
  "chokidar": "^3.6.0",
63
64
  "codemirror": "^6.0.1",
64
- "eslint": "^9.0.0",
65
- "rollup": "^4.14.1",
65
+ "eslint": "^9.1.1",
66
+ "rollup": "^4.16.3",
66
67
  "rollup-plugin-postcss": "^4.0.2",
67
68
  "rollup-plugin-string": "^3.0.0",
68
69
  "static-handler": "^0.4.3",
69
- "typescript": "^5.4.4",
70
+ "typescript": "^5.4.5",
70
71
  "xterm": "^5.3.0",
71
72
  "xterm-readline": "^1.1.1"
72
73
  },
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Bundled by jsDelivr using Rollup v2.79.1 and Terser v5.19.2.
3
+ * Original file: /npm/@xterm/addon-web-links@0.11.0/lib/addon-web-links.js
4
+ *
5
+ * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
6
+ */
7
+ var e={exports:{}};self;var t=e.exports=(()=>{var e={6:(e,t)=>{function r(e){try{const t=new URL(e),r=t.password&&t.username?`${t.protocol}//${t.username}:${t.password}@${t.host}`:t.username?`${t.protocol}//${t.username}@${t.host}`:`${t.protocol}//${t.host}`;return e.toLocaleLowerCase().startsWith(r.toLocaleLowerCase())}catch(e){return!1}}Object.defineProperty(t,"__esModule",{value:!0}),t.LinkComputer=t.WebLinkProvider=void 0,t.WebLinkProvider=class{constructor(e,t,r,n={}){this._terminal=e,this._regex=t,this._handler=r,this._options=n}provideLinks(e,t){const r=n.computeLink(e,this._regex,this._terminal,this._handler);t(this._addCallbacks(r))}_addCallbacks(e){return e.map((e=>(e.leave=this._options.leave,e.hover=(t,r)=>{if(this._options.hover){const{range:n}=e;this._options.hover(t,r,n)}},e)))}};class n{static computeLink(e,t,o,s){const i=new RegExp(t.source,(t.flags||"")+"g"),[a,l]=n._getWindowedLineStrings(e-1,o),c=a.join("");let d;const p=[];for(;d=i.exec(c);){const e=d[0];if(!r(e))continue;const[t,i]=n._mapStrIdx(o,l,0,d.index),[a,c]=n._mapStrIdx(o,t,i,e.length);if(-1===t||-1===i||-1===a||-1===c)continue;const h={start:{x:i+1,y:t+1},end:{x:c,y:a+1}};p.push({range:h,text:e,activate:s})}return p}static _getWindowedLineStrings(e,t){let r,n=e,o=e,s=0,i="";const a=[];if(r=t.buffer.active.getLine(e)){const e=r.translateToString(!0);if(r.isWrapped&&" "!==e[0]){for(s=0;(r=t.buffer.active.getLine(--n))&&s<2048&&(i=r.translateToString(!0),s+=i.length,a.push(i),r.isWrapped&&-1===i.indexOf(" ")););a.reverse()}for(a.push(e),s=0;(r=t.buffer.active.getLine(++o))&&r.isWrapped&&s<2048&&(i=r.translateToString(!0),s+=i.length,a.push(i),-1===i.indexOf(" ")););}return[a,n]}static _mapStrIdx(e,t,r,n){const o=e.buffer.active,s=o.getNullCell();let i=r;for(;n;){const e=o.getLine(t);if(!e)return[-1,-1];for(let r=i;r<e.length;++r){e.getCell(r,s);const i=s.getChars();if(s.getWidth()&&(n-=i.length||1,r===e.length-1&&""===i)){const e=o.getLine(t+1);e&&e.isWrapped&&(e.getCell(0,s),2===s.getWidth()&&(n+=1))}if(n<0)return[t,r]}t++,i=0}return[t,i]}}t.LinkComputer=n}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n](s,s.exports,r),s.exports}var n={};return(()=>{var e=n;Object.defineProperty(e,"__esModule",{value:!0}),e.WebLinksAddon=void 0;const t=r(6),o=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\\^<>`]*[^\s"':,.!?{}|\\\^~\[\]`()<>]/;function s(e,t){const r=window.open();if(r){try{r.opener=null}catch{}r.location.href=t}else console.warn("Opening link blocked as opener could not be cleared")}e.WebLinksAddon=class{constructor(e=s,t={}){this._handler=e,this._options=t}activate(e){this._terminal=e;const r=this._options,n=r.urlRegex||o;this._linkProvider=this._terminal.registerLinkProvider(new t.WebLinkProvider(this._terminal,n,this._handler,r))}dispose(){this._linkProvider?.dispose()}}})(),n})(),r=e.exports.WebLinksAddon,n=e.exports.__esModule;export{r as WebLinksAddon,n as __esModule,t as default};
package/src/core.js CHANGED
@@ -26,8 +26,8 @@ import { ErrorCode } from "./exceptions.js";
26
26
  import { robustFetch as fetch, getText } from "./fetch.js";
27
27
  import { hooks, main, worker, codeFor, createFunction } from "./hooks.js";
28
28
 
29
- import stdlib from "./stdlib.js";
30
- export { stdlib };
29
+ import { stdlib, optional } from "./stdlib.js";
30
+ export { stdlib, optional };
31
31
 
32
32
  // generic helper to disambiguate between custom element and script
33
33
  const isScript = ({ tagName }) => tagName === "SCRIPT";
@@ -168,7 +168,7 @@ for (const [TYPE, interpreter] of TYPES) {
168
168
  // specific main and worker hooks
169
169
  const hooks = {
170
170
  main: {
171
- ...codeFor(main),
171
+ ...codeFor(main, TYPE),
172
172
  async onReady(wrap, element) {
173
173
  registerModule(wrap);
174
174
 
@@ -265,7 +265,7 @@ for (const [TYPE, interpreter] of TYPES) {
265
265
  },
266
266
  },
267
267
  worker: {
268
- ...codeFor(worker),
268
+ ...codeFor(worker, TYPE),
269
269
  // these are lazy getters that returns a composition
270
270
  // of the current hooks or undefined, if no hook is present
271
271
  get onReady() {
package/src/hooks.js CHANGED
@@ -2,7 +2,7 @@ import { typedSet } from "type-checked-collections";
2
2
  import { dedent } from "polyscript/exports";
3
3
  import toJSONCallback from "to-json-callback";
4
4
 
5
- import stdlib from "./stdlib.js";
5
+ import { stdlib, optional } from "./stdlib.js";
6
6
 
7
7
  export const main = (name) => hooks.main[name];
8
8
  export const worker = (name) => hooks.worker[name];
@@ -15,10 +15,11 @@ const code = (hooks, branch, key, lib) => {
15
15
  };
16
16
  };
17
17
 
18
- export const codeFor = (branch) => {
18
+ export const codeFor = (branch, type) => {
19
+ const pylib = type === "mpy" ? stdlib.replace(optional, "") : stdlib;
19
20
  const hooks = {};
20
- code(hooks, branch, `codeBeforeRun`, stdlib);
21
- code(hooks, branch, `codeBeforeRunAsync`, stdlib);
21
+ code(hooks, branch, `codeBeforeRun`, pylib);
22
+ code(hooks, branch, `codeBeforeRunAsync`, pylib);
22
23
  code(hooks, branch, `codeAfterRun`);
23
24
  code(hooks, branch, `codeAfterRunAsync`);
24
25
  return hooks;
@@ -134,11 +134,15 @@ const workerReady = ({ interpreter, io, run, type }, { sync }) => {
134
134
 
135
135
  const pyTerminal = async (element) => {
136
136
  // lazy load these only when a valid terminal is found
137
- const [{ Terminal }, { Readline }, { FitAddon }] = await Promise.all([
138
- import(/* webpackIgnore: true */ "../3rd-party/xterm.js"),
139
- import(/* webpackIgnore: true */ "../3rd-party/xterm-readline.js"),
140
- import(/* webpackIgnore: true */ "../3rd-party/xterm_addon-fit.js"),
141
- ]);
137
+ const [{ Terminal }, { Readline }, { FitAddon }, { WebLinksAddon }] =
138
+ await Promise.all([
139
+ import(/* webpackIgnore: true */ "../3rd-party/xterm.js"),
140
+ import(/* webpackIgnore: true */ "../3rd-party/xterm-readline.js"),
141
+ import(/* webpackIgnore: true */ "../3rd-party/xterm_addon-fit.js"),
142
+ import(
143
+ /* webpackIgnore: true */ "../3rd-party/xterm_addon-web-links.js"
144
+ ),
145
+ ]);
142
146
 
143
147
  const readline = new Readline();
144
148
 
@@ -167,6 +171,7 @@ const pyTerminal = async (element) => {
167
171
  const fitAddon = new FitAddon();
168
172
  terminal.loadAddon(fitAddon);
169
173
  terminal.loadAddon(readline);
174
+ terminal.loadAddon(new WebLinksAddon());
170
175
  terminal.open(target);
171
176
  fitAddon.fit();
172
177
  terminal.focus();
@@ -6,17 +6,17 @@ import re
6
6
  from pyscript.magic_js import current_target, document, window
7
7
 
8
8
  _MIME_METHODS = {
9
- "__repr__": "text/plain",
10
- "_repr_html_": "text/html",
11
- "_repr_markdown_": "text/markdown",
12
- "_repr_svg_": "image/svg+xml",
13
- "_repr_pdf_": "application/pdf",
14
- "_repr_jpeg_": "image/jpeg",
15
- "_repr_png_": "image/png",
16
- "_repr_latex": "text/latex",
17
- "_repr_json_": "application/json",
18
- "_repr_javascript_": "application/javascript",
19
9
  "savefig": "image/png",
10
+ "_repr_javascript_": "application/javascript",
11
+ "_repr_json_": "application/json",
12
+ "_repr_latex": "text/latex",
13
+ "_repr_png_": "image/png",
14
+ "_repr_jpeg_": "image/jpeg",
15
+ "_repr_pdf_": "application/pdf",
16
+ "_repr_svg_": "image/svg+xml",
17
+ "_repr_markdown_": "text/markdown",
18
+ "_repr_html_": "text/html",
19
+ "__repr__": "text/plain",
20
20
  }
21
21
 
22
22
 
@@ -99,7 +99,7 @@ def _format_mime(obj):
99
99
  format_dict = mimebundle
100
100
 
101
101
  output, not_available = None, []
102
- for method, mime_type in reversed(_MIME_METHODS.items()):
102
+ for method, mime_type in _MIME_METHODS.items():
103
103
  if mime_type in format_dict:
104
104
  output = format_dict[mime_type]
105
105
  else:
@@ -2,7 +2,7 @@
2
2
  export default {
3
3
  "pyscript": {
4
4
  "__init__.py": "# Some notes about the naming conventions and the relationship between various\n# similar-but-different names.\n#\n# import pyscript\n# this package contains the main user-facing API offered by pyscript. All\n# the names which are supposed be used by end users should be made\n# available in pyscript/__init__.py (i.e., this file)\n#\n# import _pyscript\n# this is an internal module implemented in JS. It is used internally by\n# the pyscript package, end users should not use it directly. For its\n# implementation, grep for `interpreter.registerJsModule(\"_pyscript\",\n# ...)` in core.js\n#\n# import js\n# this is the JS globalThis, as exported by pyodide and/or micropython's\n# FFIs. As such, it contains different things in the main thread or in a\n# worker.\n#\n# import pyscript.magic_js\n# this submodule abstracts away some of the differences between the main\n# thread and the worker. In particular, it defines `window` and `document`\n# in such a way that these names work in both cases: in the main thread,\n# they are the \"real\" objects, in the worker they are proxies which work\n# thanks to coincident.\n#\n# from pyscript import window, document\n# these are just the window and document objects as defined by\n# pyscript.magic_js. This is the blessed way to access them from pyscript,\n# as it works transparently in both the main thread and worker cases.\n\nfrom pyscript.display import HTML, display\nfrom pyscript.fetch import fetch\nfrom pyscript.magic_js import (\n RUNNING_IN_WORKER,\n PyWorker,\n current_target,\n document,\n js_modules,\n sync,\n window,\n)\n\ntry:\n from pyscript.event_handling import when\nexcept:\n # TODO: should we remove this? Or at the very least, we should capture\n # the traceback otherwise it's very hard to debug\n from pyscript.util import NotSupported\n\n when = NotSupported(\n \"pyscript.when\", \"pyscript.when currently not available with this interpreter\"\n )\n",
5
- "display.py": "import base64\nimport html\nimport io\nimport re\n\nfrom pyscript.magic_js import current_target, document, window\n\n_MIME_METHODS = {\n \"__repr__\": \"text/plain\",\n \"_repr_html_\": \"text/html\",\n \"_repr_markdown_\": \"text/markdown\",\n \"_repr_svg_\": \"image/svg+xml\",\n \"_repr_pdf_\": \"application/pdf\",\n \"_repr_jpeg_\": \"image/jpeg\",\n \"_repr_png_\": \"image/png\",\n \"_repr_latex\": \"text/latex\",\n \"_repr_json_\": \"application/json\",\n \"_repr_javascript_\": \"application/javascript\",\n \"savefig\": \"image/png\",\n}\n\n\ndef _render_image(mime, value, meta):\n # If the image value is using bytes we should convert it to base64\n # otherwise it will return raw bytes and the browser will not be able to\n # render it.\n if isinstance(value, bytes):\n value = base64.b64encode(value).decode(\"utf-8\")\n\n # This is the pattern of base64 strings\n base64_pattern = re.compile(\n r\"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$\"\n )\n # If value doesn't match the base64 pattern we should encode it to base64\n if len(value) > 0 and not base64_pattern.match(value):\n value = base64.b64encode(value.encode(\"utf-8\")).decode(\"utf-8\")\n\n data = f\"data:{mime};charset=utf-8;base64,{value}\"\n attrs = \" \".join(['{k}=\"{v}\"' for k, v in meta.items()])\n return f'<img src=\"{data}\" {attrs}></img>'\n\n\ndef _identity(value, meta):\n return value\n\n\n_MIME_RENDERERS = {\n \"text/plain\": html.escape,\n \"text/html\": _identity,\n \"image/png\": lambda value, meta: _render_image(\"image/png\", value, meta),\n \"image/jpeg\": lambda value, meta: _render_image(\"image/jpeg\", value, meta),\n \"image/svg+xml\": _identity,\n \"application/json\": _identity,\n \"application/javascript\": lambda value, meta: f\"<script>{value}<\\\\/script>\",\n}\n\n\nclass HTML:\n \"\"\"\n Wrap a string so that display() can render it as plain HTML\n \"\"\"\n\n def __init__(self, html):\n self._html = html\n\n def _repr_html_(self):\n return self._html\n\n\ndef _eval_formatter(obj, print_method):\n \"\"\"\n Evaluates a formatter method.\n \"\"\"\n if print_method == \"__repr__\":\n return repr(obj)\n elif hasattr(obj, print_method):\n if print_method == \"savefig\":\n buf = io.BytesIO()\n obj.savefig(buf, format=\"png\")\n buf.seek(0)\n return base64.b64encode(buf.read()).decode(\"utf-8\")\n return getattr(obj, print_method)()\n elif print_method == \"_repr_mimebundle_\":\n return {}, {}\n return None\n\n\ndef _format_mime(obj):\n \"\"\"\n Formats object using _repr_x_ methods.\n \"\"\"\n if isinstance(obj, str):\n return html.escape(obj), \"text/plain\"\n\n mimebundle = _eval_formatter(obj, \"_repr_mimebundle_\")\n if isinstance(mimebundle, tuple):\n format_dict, _ = mimebundle\n else:\n format_dict = mimebundle\n\n output, not_available = None, []\n for method, mime_type in reversed(_MIME_METHODS.items()):\n if mime_type in format_dict:\n output = format_dict[mime_type]\n else:\n output = _eval_formatter(obj, method)\n\n if output is None:\n continue\n elif mime_type not in _MIME_RENDERERS:\n not_available.append(mime_type)\n continue\n break\n if output is None:\n if not_available:\n window.console.warn(\n f\"Rendered object requested unavailable MIME renderers: {not_available}\"\n )\n output = repr(output)\n mime_type = \"text/plain\"\n elif isinstance(output, tuple):\n output, meta = output\n else:\n meta = {}\n return _MIME_RENDERERS[mime_type](output, meta), mime_type\n\n\ndef _write(element, value, append=False):\n html, mime_type = _format_mime(value)\n if html == \"\\\\n\":\n return\n\n if append:\n out_element = document.createElement(\"div\")\n element.append(out_element)\n else:\n out_element = element.lastElementChild\n if out_element is None:\n out_element = element\n\n if mime_type in (\"application/javascript\", \"text/html\"):\n script_element = document.createRange().createContextualFragment(html)\n out_element.append(script_element)\n else:\n out_element.innerHTML = html\n\n\ndef display(*values, target=None, append=True):\n if target is None:\n target = current_target()\n elif not isinstance(target, str):\n raise TypeError(f\"target must be str or None, not {target.__class__.__name__}\")\n elif target == \"\":\n raise ValueError(\"Cannot have an empty target\")\n elif target.startswith(\"#\"):\n # note: here target is str and not None!\n # align with @when behavior\n target = target[1:]\n\n element = document.getElementById(target)\n\n # If target cannot be found on the page, a ValueError is raised\n if element is None:\n raise ValueError(\n f\"Invalid selector with id={target}. Cannot be found in the page.\"\n )\n\n # if element is a <script type=\"py\">, it has a 'target' attribute which\n # points to the visual element holding the displayed values. In that case,\n # use that.\n if element.tagName == \"SCRIPT\" and hasattr(element, \"target\"):\n element = element.target\n\n for v in values:\n if not append:\n element.replaceChildren()\n _write(element, v, append=append)\n",
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
6
  "event_handling.py": "import inspect\n\ntry:\n from pyodide.ffi.wrappers import add_event_listener\n\nexcept ImportError:\n\n def add_event_listener(el, event_type, func):\n el.addEventListener(event_type, func)\n\n\nfrom pyscript.magic_js import document\n\n\ndef when(event_type=None, selector=None):\n \"\"\"\n Decorates a function and passes py-* events to the decorated function\n The events might or not be an argument of the decorated function\n \"\"\"\n\n def decorator(func):\n if isinstance(selector, str):\n elements = document.querySelectorAll(selector)\n else:\n # TODO: This is a hack that will be removed when pyscript becomes a package\n # and we can better manage the imports without circular dependencies\n from pyweb import pydom\n\n if isinstance(selector, pydom.Element):\n elements = [selector._js]\n elif isinstance(selector, pydom.ElementCollection):\n elements = [el._js for el in selector]\n else:\n raise ValueError(\n f\"Invalid selector: {selector}. Selector must\"\n \" be a string, a pydom.Element or a pydom.ElementCollection.\"\n )\n try:\n sig = inspect.signature(func)\n # Function doesn't receive events\n if not sig.parameters:\n\n def wrapper(*args, **kwargs):\n func()\n\n else:\n wrapper = func\n\n except AttributeError:\n # TODO: this is currently an quick hack to get micropython working but we need\n # to actually properly replace inspect.signature with something else\n def wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except TypeError as e:\n if \"takes 0 positional arguments\" in str(e):\n return func()\n\n raise\n\n for el in elements:\n add_event_listener(el, event_type, wrapper)\n\n return func\n\n return decorator\n",
7
7
  "fetch.py": "import json\n\nimport js\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 def _as_bytearray(self, 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 # 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(self._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 self._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
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",
package/src/stdlib.js CHANGED
@@ -8,6 +8,27 @@
8
8
 
9
9
  import pyscript from "./stdlib/pyscript.js";
10
10
 
11
+ class Ignore extends Array {
12
+ #add = false;
13
+ #paths;
14
+ #array;
15
+ constructor(array, ...paths) {
16
+ super();
17
+ this.#array = array;
18
+ this.#paths = paths;
19
+ }
20
+ push(...values) {
21
+ if (this.#add) super.push(...values);
22
+ return this.#array.push(...values);
23
+ }
24
+ path(path) {
25
+ for (const _path of this.#paths) {
26
+ // bails out at the first `true` value
27
+ if ((this.#add = path.startsWith(_path))) break;
28
+ }
29
+ }
30
+ }
31
+
11
32
  const { entries } = Object;
12
33
 
13
34
  const python = [
@@ -16,16 +37,19 @@ const python = [
16
37
  "_path = None",
17
38
  ];
18
39
 
40
+ const ignore = new Ignore(python, "./pyweb");
41
+
19
42
  const write = (base, literal) => {
20
43
  for (const [key, value] of entries(literal)) {
21
- python.push(`_path = _Path("${base}/${key}")`);
44
+ ignore.path(`${base}/${key}`);
45
+ ignore.push(`_path = _Path("${base}/${key}")`);
22
46
  if (typeof value === "string") {
23
47
  const code = JSON.stringify(value);
24
- python.push(`_path.write_text(${code},encoding="utf-8")`);
48
+ ignore.push(`_path.write_text(${code},encoding="utf-8")`);
25
49
  } else {
26
50
  // @see https://github.com/pyscript/pyscript/pull/1813#issuecomment-1781502909
27
- python.push(`if not _os.path.exists("${base}/${key}"):`);
28
- python.push(" _path.mkdir(parents=True, exist_ok=True)");
51
+ ignore.push(`if not _os.path.exists("${base}/${key}"):`);
52
+ ignore.push(" _path.mkdir(parents=True, exist_ok=True)");
29
53
  write(`${base}/${key}`, value);
30
54
  }
31
55
  }
@@ -42,4 +66,5 @@ python.push(
42
66
  );
43
67
  python.push("\n");
44
68
 
45
- export default python.join("\n");
69
+ export const stdlib = python.join("\n");
70
+ export const optional = ignore.join("\n");
@@ -0,0 +1,4 @@
1
+ declare var r: any;
2
+ declare var n: any;
3
+ declare var t: {};
4
+ export { r as WebLinksAddon, n as __esModule, t as default };
package/types/core.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import stdlib from "./stdlib.js";
1
+ import { stdlib } from "./stdlib.js";
2
+ import { optional } from "./stdlib.js";
2
3
  import TYPES from "./types.js";
3
4
  /**
4
5
  * A `Worker` facade able to bootstrap on the worker thread only a PyScript module.
@@ -51,4 +52,4 @@ declare const exportedHooks: {
51
52
  };
52
53
  declare const exportedConfig: {};
53
54
  declare const exportedWhenDefined: (type: string) => Promise<any>;
54
- export { stdlib, TYPES, exportedPyWorker as PyWorker, exportedMPWorker as MPWorker, exportedHooks as hooks, exportedConfig as config, exportedWhenDefined as whenDefined };
55
+ export { stdlib, optional, TYPES, exportedPyWorker as PyWorker, exportedMPWorker as MPWorker, exportedHooks as hooks, exportedConfig as config, exportedWhenDefined as whenDefined };
package/types/hooks.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export function main(name: any): any;
2
2
  export function worker(name: any): any;
3
- export function codeFor(branch: any): {};
3
+ export function codeFor(branch: any, type: any): {};
4
4
  export function createFunction(self: any, name: any): any;
5
5
  export namespace hooks {
6
6
  namespace main {
package/types/stdlib.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- declare const _default: string;
2
- export default _default;
1
+ export const stdlib: string;
2
+ export const optional: string;
@@ -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-Bz8y6BoV.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 C,Prec as M,StateField as A,EditorState as L,findClusterBreak as q,RangeSetBuilder as R}from"./codemirror_state-BKbyfKsm.js";import{k as D,l as W,m as F,n as I,o as P,p as E}from"./codemirror_language-DCl5sMoK.js";import{history as $,defaultKeymap as T,historyKeymap as O}from"./codemirror_commands-Cda0Zxd7.js";import{a as z,b as B,d as j,e as _}from"./index-2LL_kWLg.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=C.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})});function re(e){let t=[de,he];return e&&t.push(oe.of(e)),t}const ae=t.mark({class:"cm-selectionMatch"}),le=t.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function ce(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 he=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),!ce(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||ce(a,s,n,o))&&(r.empty&&n<=r.from&&o>=r.to?l.push(le.range(n,o)):(n>=r.to||o<=r.from)&&l.push(ae.range(n,o)),l.length>i.maxMatches))return t.none}}return t.set(l)}},{decorations:e=>e.decorations}),de=i.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}});const ue=y.define({combine:e=>k(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:e=>new je(e),scrollToMatch:e=>i.scrollIntoView(e)})});class fe{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 we(this):new ge(this)}getCursor(e,t=0,i){let s=e.doc?e:L.create({doc:e});return null==i&&(i=s.doc.length),this.regexp?ve(this,s,t,i):pe(this,s,t,i)}}class me{constructor(e){this.spec=e}}function pe(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(xe(i,e-s))==S.Word&&o(be(i,e-s))==S.Word||o(be(i,t-s))==S.Word&&o(xe(i,t-s))==S.Word))):void 0);var n,o}class ge extends me{constructor(e){super(e)}nextMatch(e,t,i){let s=pe(this.spec,e,i,e.doc.length).nextOverlapping();return s.done&&(s=pe(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=pe(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=pe(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=pe(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 ve(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(xe(i.input,i.index))!=S.Word||n(be(i.input,i.index))!=S.Word)&&(n(be(i.input,i.index+i[0].length))!=S.Word||n(xe(i.input,i.index+i[0].length))!=S.Word)):void 0},i,s);var n}function xe(e,t){return e.slice(q(e,t,!1),t)}function be(e,t){return e.slice(t,q(e,t))}class we extends me{nextMatch(e,t,i){let s=ve(this.spec,e,i,e.doc.length).next();return s.done&&(s=ve(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=ve(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=ve(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=ve(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 ye=w.define(),ke=w.define(),Se=A.define({create:e=>new Ce(Ee(e).create(),null),update(e,t){for(let i of t.effects)i.is(ye)?e=new Ce(i.value.create(),e.panel):i.is(ke)&&(e=new Ce(e.query,i.value?Pe:null));return e},provide:e=>n.from(e,(e=>e.panel))});class Ce{constructor(e,t){this.query=e,this.panel=t}}const Me=t.mark({class:"cm-searchMatch"}),Ae=t.mark({class:"cm-searchMatch cm-searchMatch-selected"}),Le=e.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Se))}update(e){let t=e.state.field(Se);(t!=e.startState.field(Se)||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?Ae:Me)}))}return n.finish()}},{decorations:e=>e.decorations});function qe(e){return t=>{let i=t.state.field(Se,!1);return i&&i.query.spec.valid?e(t,i):Oe(t)}}const Re=qe(((e,{query:t})=>{let{to:i}=e.state.selection.main,s=t.nextMatch(e.state,i,i);if(!s)return!1;let n=C.single(s.from,s.to),o=e.state.facet(ue);return e.dispatch({selection:n,effects:[Ne(e,s),o.scrollToMatch(n.main,e)],userEvent:"select.search"}),Te(e),!0})),De=qe(((e,{query:t})=>{let{state:i}=e,{from:s}=i.selection.main,n=t.prevMatch(i,s,s);if(!n)return!1;let o=C.single(n.from,n.to),r=e.state.facet(ue);return e.dispatch({selection:o,effects:[Ne(e,n),r.scrollToMatch(o.main,e)],userEvent:"select.search"}),Te(e),!0})),We=qe(((e,{query:t})=>{let i=t.matchAll(e.state,1e3);return!(!i||!i.length)&&(e.dispatch({selection:C.create(i.map((e=>C.range(e.from,e.to)))),userEvent:"select.search.matches"}),!0)})),Fe=qe(((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=C.single(r.from-t,r.to-t),h.push(Ne(e,r)),h.push(s.facet(ue).scrollToMatch(a.main,e))}return e.dispatch({changes:c,selection:a,effects:h,userEvent:"input.replace"}),!0})),Ie=qe(((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 Pe(e){return e.state.facet(ue).createPanel(e)}function Ee(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(ue);return new fe({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 $e(e){let t=s(e,Pe);return t&&t.dom.querySelector("[main-field]")}function Te(e){let t=$e(e);t&&t==e.root.activeElement&&t.select()}const Oe=e=>{let t=e.state.field(Se,!1);if(t&&t.panel){let i=$e(e);if(i&&i!=e.root.activeElement){let s=Ee(e.state,t.query.spec);s.valid&&e.dispatch({effects:ye.of(s)}),i.focus(),i.select()}}else e.dispatch({effects:[ke.of(!0),t?ye.of(Ee(e.state,t.query.spec)):w.appendConfig.of(Ke)]});return!0},ze=e=>{let t=e.state.field(Se,!1);if(!t||!t.panel)return!1;let i=s(e,Pe);return i&&i.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:ke.of(!1)}),!0},Be=[{key:"Mod-f",run:Oe,scope:"editor search-panel"},{key:"F3",run:Re,shift:De,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:Re,shift:De,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:ze,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(C.range(t.value.from,t.value.to))}return t(e.update({selection:C.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=C.create(i.ranges.map((t=>e.wordAt(t.head)||C.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(C.range(o.from,o.to),!1),effects:i.scrollIntoView(o.to)})),!0)},preventDefault:!0}];class je{constructor(e){this.view=e;let t=this.query=e.state.field(Se).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:_e(e,"Find"),"aria-label":_e(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:_e(e,"Replace"),"aria-label":_e(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",(()=>Re(e)),[_e(e,"next")]),i("prev",(()=>De(e)),[_e(e,"previous")]),i("select",(()=>We(e)),[_e(e,"all")]),V("label",null,[this.caseField,_e(e,"match case")]),V("label",null,[this.reField,_e(e,"regexp")]),V("label",null,[this.wordField,_e(e,"by word")]),...e.state.readOnly?[]:[V("br"),this.replaceField,i("replace",(()=>Fe(e)),[_e(e,"replace")]),i("replaceAll",(()=>Ie(e)),[_e(e,"replace all")])],V("button",{name:"close",onclick:()=>ze(e),"aria-label":_e(e,"close"),type:"button"},["×"])])}commit(){let e=new fe({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:ye.of(e)}))}keydown(e){o(this.view,e,"search-panel")?e.preventDefault():13==e.keyCode&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?De:Re)(this.view)):13==e.keyCode&&e.target==this.replaceField&&(e.preventDefault(),Fe(this.view))}update(e){for(let t of e.transactions)for(let e of t.effects)e.is(ye)&&!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(ue).top}}function _e(e,t){return e.state.phrase(t)}const Ve=30,He=/[\s\.,:;?!]/;function Ne(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-Ve),a=Math.min(o,s+Ve),l=e.state.sliceDoc(r,a);if(r!=n.from)for(let e=0;e<Ve;e++)if(!He.test(l[e+1])&&He.test(l[e])){l=l.slice(e);break}if(a!=o)for(let e=l.length-1;e>l.length-Ve;e--)if(!He.test(l[e-1])&&He.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 Ue=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"}}),Ke=[Se,M.low(Le),Ue];class Qe{constructor(e,t,i){this.from=e,this.to=t,this.diagnostic=i}}class Ge{constructor(e,t,i){this.diagnostics=e,this.panel=t,this.selected=i}static init(e,i,s){let n=e,o=s.facet(rt).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 ct(e),diagnostic:e}).range(e.from):t.mark({attributes:{class:"cm-lintRange cm-lintRange-"+e.severity+(e.markClass?" "+e.markClass:"")},diagnostic:e,inclusive:!0}).range(e.from,e.to))),!0);return new Ge(r,i,Ye(r))}}function Ye(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 Qe(e,i,n.diagnostic),!1})),s}const Ze=w.define(),Je=w.define(),Xe=w.define(),et=A.define({create:()=>new Ge(t.none,null,null),update(e,t){if(t.docChanged){let i=e.diagnostics.map(t.changes),s=null;if(e.selected){let n=t.changes.mapPos(e.selected.from,1);s=Ye(i,e.selected.diagnostic,n)||Ye(i,null,n)}e=new Ge(i,e.panel,s)}for(let i of t.effects)i.is(Ze)?e=Ge.init(i.value,e.panel,t.state):i.is(Je)?e=new Ge(e.diagnostics,i.value?dt.open:null,e.selected):i.is(Xe)&&(e=new Ge(e.diagnostics,e.panel,i.value));return e},provide:e=>[n.from(e,(e=>e.panel)),i.decorations.from(e,(e=>e.diagnostics))]}),tt=t.mark({class:"cm-lintRange cm-lintRange-active",inclusive:!0});function it(e,t,i){let{diagnostics:s}=e.state.field(et),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(rt).tooltipFilter;return a&&(n=a(n,e.state)),n.length?{pos:o,end:r,above:e.state.doc.lineAt(o).to<r,create:()=>({dom:st(e,n)})}:null}function st(e,t){return V("ul",{class:"cm-tooltip-lint"},t.map((t=>lt(e,t,!1))))}const nt=e=>{let t=e.state.field(et,!1);return!(!t||!t.panel)&&(e.dispatch({effects:Je.of(!1)}),!0)},ot=[{key:"Mod-Shift-m",run:e=>{let t=e.state.field(et,!1);var i,n;t&&t.panel||e.dispatch({effects:(i=e.state,n=[Je.of(!0)],i.field(et,!1)?n:n.concat(w.appendConfig.of(mt)))});let o=s(e,dt.open);return o&&o.dom.querySelector(".cm-panel-lint ul").focus(),!0},preventDefault:!0},{key:"F8",run:e=>{let t=e.state.field(et,!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)}}],rt=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},{needsRefresh:(e,t)=>e?t?i=>e(i)||t(i):e:t}))});function at(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 lt(e,t,i){var s;let n=i?at(t.actions):[];return V("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},V("span",{class:"cm-diagnosticText"},t.renderMessage?t.renderMessage():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=Ye(e.state.field(et).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 ct 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 ht{constructor(e,t){this.diagnostic=t,this.id="item_"+Math.floor(4294967295*Math.random()).toString(16),this.dom=lt(e,t,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class dt{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)nt(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=at(i.actions);for(let n=0;n<s.length;n++)if(s[n].toUpperCase().charCodeAt(0)==t.keyCode){let t=Ye(this.view.state.field(et).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:()=>nt(this.view)},"×")),this.update()}get selectedIndex(){let e=this.view.state.field(et).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(et),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 ht(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 ht(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=Ye(this.view.state.field(et).diagnostics,this.items[e].diagnostic);t&&this.view.dispatch({selection:{anchor:t.from,head:t.to},scrollIntoView:!0,effects:Xe.of(t)})}static open(e){return new dt(e)}}function ut(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 ft=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:ut("#d11")},".cm-lintRange-warning":{backgroundImage:ut("orange")},".cm-lintRange-info":{backgroundImage:ut("#999")},".cm-lintRange-hint":{backgroundImage:ut("#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}}}),mt=[et,i.decorations.compute([et],(e=>{let{selected:i,panel:s}=e.field(et);return i&&s&&i.from!=i.to?t.set([tt.range(i.from,i.to)]):t.none})),r(it,{hideOn:function(e,t){let i=e.startState.doc.lineAt(t.pos);return!(!e.effects.some((e=>e.is(Ze)))&&!e.changes.touchesRange(i.from,i.to))}}),ft],pt=(()=>[l(),c(),h(),$(),D(),d(),u(),L.allowMultipleSelections.of(!0),W(),F(I,{fallback:!0}),P(),z(),B(),f(),m(),p(),re(),g.of([...j,...T,...Be,...O,...E,..._,...ot])])(),gt=(()=>[h(),$(),d(),F(I,{fallback:!0}),g.of([...T,...O])])();export{i as EditorView,pt as basicSetup,gt as minimalSetup};
2
- //# sourceMappingURL=codemirror-Da0uB6D0.js.map