commit 40c09addfb781c1dfaf92b230257421166af39c4
parent 926c6dee60247284686049cb4810897cab870265
Author: James Eversole <james@eversole.co>
Date: Thu, 22 Oct 2026 09:35:17 -0500
Integrate CodeMirror editing and per-line import hash folding
Use one canonical editor document for source, selection and history. Replace declaration hit-box overlays with inline marks and retain explicit IO, revision checks, draft recovery and undoable imports.
Build the pinned editor sources and licenses through Nix. Cover hash projection, native clipboard/caret mapping, dynamic import undo/redo and editor parity in the browser suites.
Diffstat:
47 files changed, 1524 insertions(+), 705 deletions(-)
diff --git a/ext/demo-site/README.md b/ext/demo-site/README.md
@@ -60,17 +60,27 @@ and layout rules; compiler diagnostics resolve names and validate source.
A collapsed caret immediately beside `()`, `[]` or `{}` highlights its matching
partner. An unmatched delimiter gets a wavy underline. Strings and comments are
excluded, including non-nesting block comments. Range selections do not highlight
-a pair. There is no automatic bracket insertion, indentation rewriting or
-completion. Highlighting does not compile or execute programs.
-
-The local `syntax.ts` renderer decorates native textareas. Decorative
-mirrors are hidden from accessibility APIs and never interpret source as HTML.
-Selection, undo, resizing and scrolling remain native. During IME composition and
-in forced-colors mode, native text remains visible instead of the colored mirror.
-Programmatic source/preset changes explicitly refresh the decoration without
-synthesizing edits or starting compilation. Sources over 32,768 UTF-16 code units
-fall back to plain text, bounding decoration work without truncating source or
-changing execution limits. This also covers large read-only library sources.
+a pair. Enter inserts a plain newline, preserving explicit indentation. Highlighting
+updates as the document and selection change.
+
+CodeMirror 6 owns the canonical document, selection and undo history. The local
+`syntax.ts` lexer supplies highlighting and declaration sites; CodeMirror renders
+source as text. Document loads reset history; import insertion is one isolated
+undoable transaction. Native input and clipboard events use canonical UTF-16
+document offsets. Sources over 32,768 UTF-16 code units use plain highlighting.
+Drafts retain their complete text, and compilation enforces the 16,384-scalar
+input limit with diagnostics.
+
+Import **hashes** display their first three and last three characters with literal
+dots (`abc...xyz`), in muted teal with a dotted underline. Editing an import line
+reveals its full hash; a range selection reveals every affected line, leaving
+unrelated imports folded. Each hash also has an independent keyboard-accessible
+expand/collapse control. Copying, saving and compilation use complete canonical
+source; folding and selection preserve the document and undo history.
+
+The pinned editor sources, fixed-output hashes, licenses and declaration build
+are in `codemirror/`. Nix builds and bundles the editor locally. Physical mobile
+Safari, real IME and screen-reader behavior require device/manual validation.
## Runtime selection
@@ -136,9 +146,10 @@ TEST_IDE=1 TEST_BACKEND=haskell-wasm \
Repeat with `TEST_BACKEND=zig-wasm` and with `TEST_MODULES=1`,
`TEST_LOCAL_MODULES=1`, or `TEST_ASSET_CACHE=1` in place of `TEST_IDE=1`.
-The IDE, complete demo/module, local-file and cache suites pass on both backends
-with Playwright 1.59.1 / WebKit build 2272. The runner also checks layout at
-320, 390 and 1280 pixels after textarea mirror resize observers settle.
+The runner uses Playwright 1.59.1 / WebKit build 2272 and also checks layout at
+320, 390 and 1280 pixels after editor viewport measurements settle. For the longer
+Zig IDE run, set `TEST_WEBKIT_TIMEOUT_MS=360000` (default: 240000).
+`TEST_DIAGNOSTICS=1` reports read-only page status every 30 seconds.
`SCREENSHOT=/tmp/arboricx.png` saves a screenshot at each width.
Each run uses a fresh, temporary disk-backed browser profile, matching the
@@ -159,7 +170,7 @@ A cancellable, separate Worker uses the selected native backend to inspect the
header and compile the candidate source. Namespace conflicts and compiler
failures appear before insertion. Existing imports offer a jump action; unfinished
source can use Copy import. Insertion prepends a qualified directive while
-preserving all original source, supplies one native textarea undo transaction,
+preserving all original source, supplies one isolated editor undo transaction,
and follows normal idle compilation. The dialog uses native focus containment,
Escape cancellation and focus restoration. Each candidate check has a 60-second
cutoff. A revision guard rejects stale replies; insertion rechecks source and
@@ -1149,8 +1160,8 @@ Use the published manifest pins with the native source import syntax above.
Tooling comes from the repository's locked nixpkgs:
```sh
-./ext/demo-site/build.sh # strict TS → dist/*.js (TypeScript 5.9.3)
-./ext/demo-site/build.sh --check # fresh temporary compile; exact shipped-JS parity
+./ext/demo-site/build.sh # pinned Nix editor bundle + strict TS → dist/*.js
+./ext/demo-site/build.sh --check # exact generated-JS and license parity
nix shell --inputs-from . nixpkgs#nodejs -c python3 ext/demo-site/test/run-bounded.py \
--seconds 60 -- node --max-old-space-size=512 --test --test-concurrency=1 ext/demo-site/test/*.test.mjs
# Independent native CLI oracle for browser module semantics:
@@ -1388,7 +1399,7 @@ TEST_IDE=1 ARBORICX_SITE_ROOT="$SITE" nix shell --inputs-from . nixpkgs#nodejs n
```
Use `TEST_DEFINITION_NAMES=1` for declaration-name inspection, editing/focus,
-Unicode offsets, invalidation, IME, and wrapped/scrolled hit rectangles. Chromium
+Unicode offsets, invalidation, IME lifecycle, and wrapped inline hit areas. Chromium
also sends trusted mouse/touch and Tab/Enter/Space/Escape events, verifies native
rename/undo and cross-name drag selection, touch-hold selection and panning
cancellation at 390/1440 pixels. `TEST_SCREENSHOT_PREFIX` saves closed/open card
@@ -1396,6 +1407,12 @@ screenshots at those widths. Firefox runs the shared compiled-definition and
DOM/geometry checks; it does not run the CDP input checks. Physical mobile Safari
keyboard/selection-handle behavior is not covered by these automated checks.
+Use `TEST_IMPORT_FOLDS=1` for hash recognition, independent toggles, per-line/range
+expansion, canonical source/revision invariance, and dynamic import undo/redo.
+Chromium additionally checks trusted mouse/touch caret placement, partial/full
+system clipboard contents, native pasted-import undo/redo, single-character hash
+deletion, plain Enter, and read-only editing at 390/1440 pixels.
+
The focused inline IO suite can be run with `TEST_INLINE_IO=1` in that harness.
It includes source-free IO, private entries, envelope-only recognition of a
program with a divergent action, explicit Run, CPU-bound cancellation, closing
@@ -1415,19 +1432,18 @@ snapshots every 30 seconds; it is off by default, including idle-soak checks.
### Inline definition inspection and library discovery
Underlined top-level declaration names toggle an anchored compiled-definition card.
-There is no inspection gutter or reserved horizontal column. Names are interactive
+Names are interactive
only for the current successfully compiled scope (public roots for published
packages). References and local binders stay ordinary editable text. Tab then
Enter/Space also opens the card. **Edit name** closes it and selects the identifier
-in the native textarea for renaming; read-only source disables that action.
+in the canonical editor for renaming; read-only source disables that action.
A touch/pen hold selects the identifier in the native editor without inspecting
it (also available through **Edit name**); selection drags and native context
-menus do not trigger inspection. IME composition hides the hit areas. Wrapped identifiers have separate hit rectangles
-per fragment, avoiding adjacent expression text. Opening
+menus do not trigger inspection. IME composition disables name activation. Names are inline editor decorations,
+so wrapped fragments use their native text hit areas. Opening
starts with **Auto**, checking the supported IO envelope, then preferring readable text, a natural number, a decoded list
of text/naturals, a Boolean, bytes, then tricu tree source. The status names the
-chosen interpretation (for example **Auto → Text**); this is a display heuristic,
-not type inference. An empty tree defaults to natural zero. Readable text allows
+chosen interpretation (for example **Auto → Text**). An empty tree defaults to natural zero. Readable text allows
Unicode letters/marks/numbers/punctuation/symbols/spaces, TAB/LF/CR, and joining
characters, but excludes other controls, private-use and unassigned scalars.
Manual Text still accepts any valid Unicode scalar string. A manual selection
diff --git a/ext/demo-site/build.sh b/ext/demo-site/build.sh
@@ -1,12 +1,13 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/../.."
-# Resolve tooling through the repository's locked nixpkgs, not npm or a global tsc.
+# Compiler, editor sources and bundler all come from the locked Nix build.
+temporary=$(mktemp -d)
+trap 'rm -rf "$temporary"' EXIT
+nix build .#arboricxSiteJavaScript --out-link "$temporary/javascript"
if [[ "${1:-}" == --check ]]; then
- temporary=$(mktemp -d)
- trap 'rm -rf "$temporary"' EXIT
- nix shell --inputs-from . nixpkgs#typescript -c tsc -p ext/demo-site/tsconfig.json --outDir "$temporary"
- diff -ru ext/demo-site/dist "$temporary"
+ diff -ru ext/demo-site/dist "$temporary/javascript/"
else
- nix shell --inputs-from . nixpkgs#typescript -c tsc -p ext/demo-site/tsconfig.json
+ cp -rL "$temporary/javascript/." ext/demo-site/dist/
+ chmod -R u+w ext/demo-site/dist
fi
diff --git a/ext/demo-site/codemirror/default.nix b/ext/demo-site/codemirror/default.nix
@@ -0,0 +1,28 @@
+{ pkgs }:
+let
+ lock = builtins.fromJSON (builtins.readFile ./sources.json);
+ sources = builtins.listToAttrs (map (row: {
+ name = row.slug;
+ value = pkgs.fetchzip { url = "https://api.github.com/repos/${row.repo}/tarball/${row.rev}"; hash = row.hash; extension = "tar.gz"; };
+ }) lock);
+ aliases = pkgs.lib.concatMapStringsSep " " (row: "--alias:${row.name}=${sources.${row.slug}}/${row.entry}") lock;
+ dependencies = pkgs.lib.concatMapStringsSep "\n" (row: ''
+ cp -r ${sources.${row.slug}} "deps/${row.slug}"
+ '') lock;
+ licenses = pkgs.lib.concatMapStringsSep "\n" (row: ''
+ cp ${sources.${row.slug}}/LICENSE "$out/licenses/${row.slug}.txt"
+ '') lock;
+in pkgs.runCommand "arboricx-codemirror" { nativeBuildInputs = [pkgs.esbuild pkgs.typescript pkgs.python3]; } ''
+ mkdir -p "$out/licenses"
+ cp ${./entry.ts} entry.ts
+ mkdir -p deps
+ ${dependencies}
+ cp ${./sources.json} sources.json
+ python3 ${./typecheck.py}
+ tsc -p tsconfig.upstream.json
+ esbuild entry.ts --bundle --format=esm --target=es2022 --tsconfig-raw='{"compilerOptions":{"useDefineForClassFields":false}}' --minify --legal-comments=linked ${aliases} --outfile="$out/codemirror.js" --metafile="$out/bundle-meta.json"
+ cp ${./sources.json} "$out/sources.json"
+ ${licenses}
+ cp -r types "$out/types"
+ cp -r deps "$out/deps"
+''
diff --git a/ext/demo-site/codemirror/entry.ts b/ext/demo-site/codemirror/entry.ts
@@ -0,0 +1,3 @@
+export {EditorState, StateField, StateEffect, Transaction, EditorSelection, Compartment} from '@codemirror/state';
+export {EditorView, Decoration, WidgetType, keymap, drawSelection} from '@codemirror/view';
+export {history, historyKeymap, standardKeymap, isolateHistory, undo, redo, insertNewline} from '@codemirror/commands';
diff --git a/ext/demo-site/codemirror/sources.json b/ext/demo-site/codemirror/sources.json
@@ -0,0 +1,123 @@
+[
+ {
+ "name": "@codemirror/state",
+ "repo": "codemirror/state",
+ "rev": "821d9b772a1d2d9c989b6ae472513380bf10136b",
+ "tag": "6.6.0",
+ "version": "6.6.0",
+ "entry": "src/index.ts",
+ "hash": "sha256-4Qv8CcNDpf3iFIpoAvQF4lGMBjPZ2UeP37hZHYDiPPM=",
+ "slug": "codemirror-state",
+ "license": "MIT"
+ },
+ {
+ "name": "@codemirror/view",
+ "repo": "codemirror/view",
+ "rev": "a0a5ed946cfdfde61dcf33b131d551136378ccf9",
+ "tag": "6.41.0",
+ "version": "6.41.0",
+ "entry": "src/index.ts",
+ "hash": "sha256-VRVHvoDDgObm/WodDMYFpux+s+emALDAJnm37VVhjV0=",
+ "slug": "codemirror-view",
+ "license": "MIT"
+ },
+ {
+ "name": "@codemirror/commands",
+ "repo": "codemirror/commands",
+ "rev": "6f83cb93abc81cb13993ce4805aafce45bfe2853",
+ "tag": "6.10.3",
+ "version": "6.10.3",
+ "entry": "src/commands.ts",
+ "hash": "sha256-jov9JLmRlaFfoe8fv6J/t2Iyv32fSiweryJLLOIBjWU=",
+ "slug": "codemirror-commands",
+ "license": "MIT"
+ },
+ {
+ "name": "@codemirror/language",
+ "repo": "codemirror/language",
+ "rev": "f5af31eed71fa22e8c110d74e61098c0fb1c1acb",
+ "tag": "6.12.3",
+ "version": "6.12.3",
+ "entry": "src/index.ts",
+ "hash": "sha256-8l781Wyg8oydTDohmy45dReGIpVNSJ9TwgA2wwy6N2w=",
+ "slug": "codemirror-language",
+ "license": "MIT"
+ },
+ {
+ "name": "@lezer/common",
+ "repo": "lezer-parser/common",
+ "rev": "de5f96276a2954c249de1475e8b03f79c20d9ce4",
+ "tag": "1.5.2",
+ "version": "1.5.2",
+ "entry": "src/index.ts",
+ "hash": "sha256-Sfbg8NRzqu66FfKGDn7V6+8vw55dvATZBkBUqAnGDRo=",
+ "slug": "lezer-parser-common",
+ "license": "MIT"
+ },
+ {
+ "name": "@lezer/highlight",
+ "repo": "lezer-parser/highlight",
+ "rev": "37e3eef517edd8e8dc8790419d04b61a7ac28420",
+ "tag": "1.2.3",
+ "version": "1.2.3",
+ "entry": "src/highlight.ts",
+ "hash": "sha256-lNqVZ4xKMHvUy7En4zOEUPnQnSLsZeIDz9vngJOQhf4=",
+ "slug": "lezer-parser-highlight",
+ "license": "MIT"
+ },
+ {
+ "name": "@lezer/lr",
+ "repo": "lezer-parser/lr",
+ "rev": "f81d6a25c3482aa7fc12434e9adea9d75c56ad08",
+ "tag": "1.4.8",
+ "version": "1.4.8",
+ "entry": "src/index.ts",
+ "hash": "sha256-fdBQfez64NEj3ZHz+eVSG0U5fD7OHlXJuf9udrPdDfA=",
+ "slug": "lezer-parser-lr",
+ "license": "MIT"
+ },
+ {
+ "name": "@marijn/find-cluster-break",
+ "repo": "marijnh/find-cluster-break",
+ "rev": "b0b1f10aa0c131cf53f2dc347a09544b4ae87324",
+ "tag": "1.0.2",
+ "version": "1.0.2",
+ "entry": "src/index.js",
+ "hash": "sha256-y8B89SiEXGxJtAjI95quAzYheHMQEXBp3Eh7IHog6Ls=",
+ "slug": "marijnh-find-cluster-break",
+ "license": "MIT"
+ },
+ {
+ "name": "crelt",
+ "repo": "marijnh/crelt",
+ "rev": "25eabb104d50e160cd4e4acd9eed2eacb32b332b",
+ "tag": "1.0.6",
+ "version": "1.0.6",
+ "entry": "index.js",
+ "hash": "sha256-77qlhPNk0gtkjH7ZwcZ/NrzaFPJBGGgtoU12BcQhXPU=",
+ "slug": "marijnh-crelt",
+ "license": "MIT"
+ },
+ {
+ "name": "style-mod",
+ "repo": "marijnh/style-mod",
+ "rev": "f8a0376473b604184916ef2ae4f28edfaf653849",
+ "tag": "4.1.3",
+ "version": "4.1.3",
+ "entry": "src/style-mod.js",
+ "hash": "sha256-g73AMEoYTyn2UlBedtuuFIYbRvu+RnTBiZEBPUxDK2I=",
+ "slug": "marijnh-style-mod",
+ "license": "MIT"
+ },
+ {
+ "name": "w3c-keyname",
+ "repo": "marijnh/w3c-keyname",
+ "rev": "5ea93b04bb62230c7de4165e3a9b5c840f05cd44",
+ "tag": "2.2.8",
+ "version": "2.2.8",
+ "entry": "index.js",
+ "hash": "sha256-KQ7xL6ff0BBIPEkZVTT7uMQKYlWHLZnnm+AyvoBMThM=",
+ "slug": "marijnh-w3c-keyname",
+ "license": "MIT"
+ }
+]
diff --git a/ext/demo-site/codemirror/typecheck.py b/ext/demo-site/codemirror/typecheck.py
@@ -0,0 +1,9 @@
+import pathlib,json
+p=pathlib.Path.cwd(); rows=json.loads((p/'sources.json').read_text());paths={}
+for row in rows:
+ entry=p/'deps'/row['slug']/row['entry'];paths[row['name']]=[str(entry.with_suffix('.d.ts') if entry.suffix=='.js' else entry)]
+(p/'deps'/'node-env.d.ts').write_text('declare const process: { env: { LOG?: string } };\n')
+# Declaration generation only; variance and class-field settings accommodate the
+# upstream source builds. Our application is checked separately with strict flags.
+config={'compilerOptions':{'target':'ES2022','module':'ESNext','moduleResolution':'Bundler','strict':True,'strictFunctionTypes':False,'strictNullChecks':True,'useDefineForClassFields':False,'skipLibCheck':True,'declaration':True,'emitDeclarationOnly':True,'rootDir':str(p/'deps'),'outDir':str(p/'types'),'lib':['ES2022','DOM','DOM.Iterable'],'paths':paths},'include':[str(p/'deps'/'codemirror-*'/'src'/'*.ts'),str(p/'deps'/'lezer-parser-*'/'src'/'*.ts'),str(p/'deps'/'node-env.d.ts')]}
+(p/'tsconfig.upstream.json').write_text(json.dumps(config))
diff --git a/ext/demo-site/dist/app.js b/ext/demo-site/dist/app.js
@@ -1,8 +1,9 @@
+import { SourceEditor } from './source-editor.js';
import { definitionInspector } from './definition-inspector.js';
import { exampleGroups, exampleGroup, libraryLabel } from './program-catalogue.js';
import { importPicker } from './import-picker.js';
import { localModulesUI } from './local-modules-ui.js';
-import { syntaxEditor, tokenize, paintSyntax } from './syntax.js';
+import { tokenize, paintSyntax } from './syntax.js';
import { backend, backends, runtimeStats } from './runtime-backends.js';
import { setupInspector } from './inspector.js';
import { ActiveClock } from './clock.js';
@@ -17,7 +18,7 @@ function el(id) {
throw new Error(`Missing element ${id}`);
return element;
}
-const sourceEditor = el('source-editor'), refreshSourceSyntax = syntaxEditor(sourceEditor);
+const sourceEditor = new SourceEditor(el('source-editor'));
const compileButton = el('compile'), restoreButton = el('restore-source');
const downloadButton = el('download-bundle'), exportModuleButton = el('export-compiled-module');
const backendPicker = el('runtime-backend'), programPicker = el('program-picker');
@@ -71,7 +72,7 @@ const definitions = definitionInspector(sourceEditor, (id, name, output) => {
worker.postMessage({ type: 'inspect', id, name, output });
}, {
run(name, output, step) {
- if (busy || !worker || draft && (!compiled || sourceEditor.value !== compiledSource || editRevision !== compiledRevision))
+ if (busy || !worker || draft && (!compiled || sourceEditor.getSource() !== compiledSource || editRevision !== compiledRevision))
return;
currentName = name;
operation = 'running';
@@ -94,11 +95,11 @@ const definitions = definitionInspector(sourceEditor, (id, name, output) => {
},
});
const imports = importPicker({ source: sourceEditor, backend: () => backendPicker.value,
- available: () => !busy, editable: () => !busy && !sourceEditor.hidden && !sourceEditor.readOnly,
+ available: () => !busy, editable: () => !busy && !sourceEditor.dom.hidden && !sourceEditor.isReadOnly,
tryLibrary: (library, definition) => { preferredExport = definition; loadBundle(library); },
local: () => localModules.entries(), inputs: () => localModules.inputs() });
function diagnostic(message = '') { el('operation-diagnostic').textContent = message; el('operation-diagnostic').hidden = !message; }
-function ready() { return !!worker && (draft ? compiled && sourceEditor.value === compiledSource && editRevision === compiledRevision : loaded); }
+function ready() { return !!worker && (draft ? compiled && sourceEditor.getSource() === compiledSource && editRevision === compiledRevision : loaded); }
function controls(working) {
busy = working;
localModules.disable(busy);
@@ -114,29 +115,28 @@ function controls(working) {
restoreButton.disabled = busy || originalSource === undefined;
exportModuleButton.disabled = busy || !draft || !ready();
downloadButton.disabled = busy || draft || downloadHash() === undefined;
- sourceEditor.disabled = busy && operation !== 'compiling';
- sourceEditor.readOnly = originalSource === undefined && !draft;
- const editable = !sourceEditor.hidden && (draft || originalSource !== undefined);
+ sourceEditor.setAvailability(busy && operation !== 'compiling', originalSource === undefined && !draft);
+ const editable = !sourceEditor.dom.hidden && (draft || originalSource !== undefined);
el('playground-intro').hidden = selected?.id !== 'names-values' || !editable;
el('source-title').textContent = editable ? 'Source' : sourceAvailable ? 'Read-only source' : loaded ? 'Compiled package' : 'Package information';
el('source-availability').hidden = editable || !loaded;
el('source-availability').textContent = 'Browse stored definitions below, or import this module into your own source. Inspection does not execute IO.';
- el('package-definitions').hidden = !loaded || !sourceEditor.hidden;
+ el('package-definitions').hidden = !loaded || !sourceEditor.dom.hidden;
el('reload-package').hidden = draft || !selection || !!worker;
el('stored-download').disabled = busy || draft || !loaded || !worker;
el('stored-definition').disabled = el('stored-format').disabled = busy || draft || !loaded;
el('authorship').textContent = draft ? 'Local draft · your authored code (not published)' : loaded ? 'Published package · verified executable' : 'Published selection · not yet verified';
const modified = draft && !ready();
el('authorship').classList.toggle('modified', modified);
- sourceEditor.classList.toggle('modified', modified);
+ sourceEditor.dom.classList.toggle('modified', modified);
for (const button of document.querySelectorAll('[data-compiler-example]'))
button.disabled = busy;
stopButton.disabled = !busy && !draft;
stopButton.hidden = !busy;
shareButton.disabled = busy || draft || !loaded;
el('reset').disabled = busy;
- refreshSourceSyntax();
- definitions.update(!sourceEditor.hidden && ready() || sourceEditor.hidden && loaded && !!worker, busy, draft ? undefined : publishedNames);
+ sourceEditor.refresh();
+ definitions.update(!sourceEditor.dom.hidden && ready() || sourceEditor.dom.hidden && loaded && !!worker, busy, draft ? undefined : publishedNames);
for (const button of el('package-definition-list').querySelectorAll('button'))
button.disabled = busy || !loaded;
}
@@ -344,16 +344,16 @@ function newWorker(preserveSource = false) {
el('package-info').textContent = `SHA-256 verified · ${data.nodes.toLocaleString()} stored DAG nodes · ${publishedNames.length} export(s) · ${data.hash}`;
if (!preserveSource || originalSource === undefined) {
originalSource = selected?.environment !== undefined && data.source !== null ? data.source : undefined;
- sourceEditor.value = originalSource ?? '';
+ sourceEditor.replaceSource(originalSource ?? '');
}
- sourceEditor.hidden = originalSource === undefined;
- el('source-notes').hidden = !sourceEditor.hidden;
+ sourceEditor.dom.hidden = originalSource === undefined;
+ el('source-notes').hidden = !sourceEditor.dom.hidden;
sourceAvailable = data.source !== null;
el('source-label').textContent = sourceAvailable ? 'Curated tricu / stable' : 'Package metadata';
el('source').textContent = data.source ?? `Verified package metadata\n${JSON.stringify(data.metadata, null, 2)}`;
if (data.source !== null)
paintSyntax(el('source'), tokenize(data.source));
- el('package-definition-search').value = sourceEditor.hidden && requested && publishedNames.includes(requested) ? requested : '';
+ el('package-definition-search').value = sourceEditor.dom.hidden && requested && publishedNames.includes(requested) ? requested : '';
renderPublishedNames();
idle();
el('status').textContent = 'Ready';
@@ -384,7 +384,7 @@ function select(entry, release) {
publishedNames = [];
selection = { hash: entry.hash, localId: entry.id };
hashInput.value = entry.hash;
- sourceEditor.hidden = true;
+ sourceEditor.dom.hidden = true;
el('source-notes').hidden = false;
const pinned = release ?? releases.find(r => r.hash === entry.hash && r.demo === entry.id);
chooseProgram(`demo:${entry.id}`, pinned?.version);
@@ -402,7 +402,7 @@ function invalidateProgram() {
selection = undefined;
selected = undefined;
publishedNames = [];
- sourceEditor.hidden = true;
+ sourceEditor.dom.hidden = true;
el('source-notes').hidden = false;
el('source').textContent = 'Load the selected program to inspect its source or package notes.';
el('package-info').textContent = 'No bundle loaded.';
@@ -608,10 +608,10 @@ downloadButton.onclick = () => {
finish(event.message || 'Worker error', true); };
current.postMessage({ type: 'load', hash });
};
-sourceEditor.addEventListener('compositionstart', () => { composing = true; cancelIdleCompile(); });
-sourceEditor.addEventListener('compositionend', () => { composing = false; if (draft)
+sourceEditor.dom.addEventListener('compositionstart', () => { composing = true; cancelIdleCompile(); });
+sourceEditor.dom.addEventListener('compositionend', () => { composing = false; if (draft)
queueCompile(); });
-sourceEditor.oninput = () => {
+sourceEditor.onChange(() => {
if (busy && operation !== 'compiling')
return;
editRevision++;
@@ -625,7 +625,7 @@ sourceEditor.oninput = () => {
}
if (!worker || !compiled || busy)
dispose();
- draft = compiled || scratch || sourceEditor.value !== originalSource;
+ draft = compiled || scratch || sourceEditor.getSource() !== originalSource;
controls(false);
if (!draft && selection)
newWorker(true);
@@ -633,14 +633,14 @@ sourceEditor.oninput = () => {
el('status').textContent = 'Changes pending';
queueCompile();
}
-};
+});
restoreButton.onclick = () => { if (originalSource === undefined || busy)
- return; dispose(); sourceEditor.value = originalSource; sourceEditor.dispatchEvent(new Event('input')); };
+ return; dispose(); sourceEditor.replaceSource(originalSource, true); };
compileButton.onclick = () => compileDraft();
function compileDraft() {
if (!draft || busy)
return;
- const snapshot = { revision: editRevision, source: sourceEditor.value };
+ const snapshot = { revision: editRevision, source: sourceEditor.getSource() };
dispose();
operation = 'compiling';
diagnostic();
@@ -723,9 +723,9 @@ for (const button of document.querySelectorAll('[data-compiler-example]'))
selection = undefined;
selected = undefined;
editRevision++;
- sourceEditor.hidden = false;
+ sourceEditor.dom.hidden = false;
el('source-notes').hidden = true;
- sourceEditor.value = source;
+ sourceEditor.replaceSource(source);
controls(false);
el('package-info').textContent = 'Scratch program · no published bundle selected.';
showRelease();
diff --git a/ext/demo-site/dist/codemirror.LICENSE.txt b/ext/demo-site/dist/codemirror.LICENSE.txt
@@ -0,0 +1,247 @@
+
+--- codemirror-commands.txt ---
+MIT License
+
+Copyright (C) 2018-2021 by Marijn Haverbeke <marijn@haverbeke.berlin> and others
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+--- codemirror-language.txt ---
+MIT License
+
+Copyright (C) 2018-2021 by Marijn Haverbeke <marijn@haverbeke.berlin> and others
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+--- codemirror-state.txt ---
+MIT License
+
+Copyright (C) 2018-2021 by Marijn Haverbeke <marijn@haverbeke.berlin> and others
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+--- codemirror-view.txt ---
+MIT License
+
+Copyright (C) 2018-2021 by Marijn Haverbeke <marijn@haverbeke.berlin> and others
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+--- lezer-parser-common.txt ---
+MIT License
+
+Copyright (C) 2018 by Marijn Haverbeke <marijn@haverbeke.berlin> and others
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+--- lezer-parser-highlight.txt ---
+MIT License
+
+Copyright (C) 2018 by Marijn Haverbeke <marijn@haverbeke.berlin> and others
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+--- lezer-parser-lr.txt ---
+MIT License
+
+Copyright (C) 2018 by Marijn Haverbeke <marijn@haverbeke.berlin> and others
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+--- marijnh-crelt.txt ---
+Copyright (C) 2020 by Marijn Haverbeke <marijn@haverbeke.berlin>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+--- marijnh-find-cluster-break.txt ---
+MIT License
+
+Copyright (C) 2024 by Marijn Haverbeke <marijn@haverbeke.berlin>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+--- marijnh-style-mod.txt ---
+Copyright (C) 2018 by Marijn Haverbeke <marijn@haverbeke.berlin> and others
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+--- marijnh-w3c-keyname.txt ---
+Copyright (C) 2016 by Marijn Haverbeke <marijn@haverbeke.berlin> and others
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/ext/demo-site/dist/codemirror.js b/ext/demo-site/dist/codemirror.js
@@ -0,0 +1,10 @@
+var A=class r{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,n){[e,t]=Ot(this,e,t);let i=[];return this.decompose(0,e,i,2),n.length&&n.decompose(0,n.length,i,3),this.decompose(t,this.length,i,1),Rt.from(i,this.length-(t-e)+n.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=Ot(this,e,t);let n=[];return this.decompose(e,t,n,0),Rt.from(n,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),n=this.length-this.scanIdentical(e,-1),i=new st(this),o=new st(e);for(let s=t,l=t;;){if(i.next(s),o.next(s),s=0,i.lineBreak!=o.lineBreak||i.done!=o.done||i.value!=o.value)return!1;if(l+=i.value.length,i.done||l>=n)return!0}}iter(e=1){return new st(this,e)}iterRange(e,t=this.length){return new Pn(this,e,t)}iterLines(e,t){let n;if(e==null)n=this.iter();else{t==null&&(t=this.lines+1);let i=this.line(e).from;n=this.iterRange(i,Math.max(i,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Vn(n)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?r.empty:e.length<=32?new oe(e):Rt.from(oe.split(e,[]))}},oe=class r extends A{constructor(t,n=Da(t)){super();this.text=t;this.length=n}get lines(){return this.text.length}get children(){return null}lineInner(t,n,i,o){for(let s=0;;s++){let l=this.text[s],a=o+l.length;if((n?i:a)>=t)return new Hn(o,a,i,l);o=a+1,i++}}decompose(t,n,i,o){let s=t<=0&&n>=this.length?this:new r(Zo(this.text,t,n),Math.min(n,this.length)-Math.max(0,t));if(o&1){let l=i.pop(),a=Nn(s.text,l.text.slice(),0,s.length);if(a.length<=32)i.push(new r(a,l.length+s.length));else{let u=a.length>>1;i.push(new r(a.slice(0,u)),new r(a.slice(u)))}}else i.push(s)}replace(t,n,i){if(!(i instanceof r))return super.replace(t,n,i);[t,n]=Ot(this,t,n);let o=Nn(this.text,Nn(i.text,Zo(this.text,0,t)),n),s=this.length+i.length-(n-t);return o.length<=32?new r(o,s):Rt.from(r.split(o,[]),s)}sliceString(t,n=this.length,i=`
+`){[t,n]=Ot(this,t,n);let o="";for(let s=0,l=0;s<=n&&l<this.text.length;l++){let a=this.text[l],u=s+a.length;s>t&&l&&(o+=i),t<u&&n>s&&(o+=a.slice(Math.max(0,t-s),n-s)),s=u+1}return o}flatten(t){for(let n of this.text)t.push(n)}scanIdentical(){return 0}static split(t,n){let i=[],o=-1;for(let s of t)i.push(s),o+=s.length+1,i.length==32&&(n.push(new r(i,o)),i=[],o=-1);return o>-1&&n.push(new r(i,o)),n}},Rt=class r extends A{constructor(t,n){super();this.children=t;this.length=n;this.lines=0;for(let i of t)this.lines+=i.lines}lineInner(t,n,i,o){for(let s=0;;s++){let l=this.children[s],a=o+l.length,u=i+l.lines-1;if((n?u:a)>=t)return l.lineInner(t,n,i,o);o=a+1,i=u+1}}decompose(t,n,i,o){for(let s=0,l=0;l<=n&&s<this.children.length;s++){let a=this.children[s],u=l+a.length;if(t<=u&&n>=l){let h=o&((l<=t?1:0)|(u>=n?2:0));l>=t&&u<=n&&!h?i.push(a):a.decompose(t-l,n-l,i,h)}l=u+1}}replace(t,n,i){if([t,n]=Ot(this,t,n),i.lines<this.lines)for(let o=0,s=0;o<this.children.length;o++){let l=this.children[o],a=s+l.length;if(t>=s&&n<=a){let u=l.replace(t-s,n-s,i),h=this.lines-l.lines+u.lines;if(u.lines<h>>4&&u.lines>h>>6){let c=this.children.slice();return c[o]=u,new r(c,this.length-(n-t)+i.length)}return super.replace(s,a,u)}s=a+1}return super.replace(t,n,i)}sliceString(t,n=this.length,i=`
+`){[t,n]=Ot(this,t,n);let o="";for(let s=0,l=0;s<this.children.length&&l<=n;s++){let a=this.children[s],u=l+a.length;l>t&&s&&(o+=i),t<u&&n>l&&(o+=a.sliceString(t-l,n-l,i)),l=u+1}return o}flatten(t){for(let n of this.children)n.flatten(t)}scanIdentical(t,n){if(!(t instanceof r))return 0;let i=0,[o,s,l,a]=n>0?[0,0,this.children.length,t.children.length]:[this.children.length-1,t.children.length-1,-1,-1];for(;;o+=n,s+=n){if(o==l||s==a)return i;let u=this.children[o],h=t.children[s];if(u!=h)return i+u.scanIdentical(h,n);i+=u.length+1}}static from(t,n=t.reduce((i,o)=>i+o.length+1,-1)){let i=0;for(let d of t)i+=d.lines;if(i<32){let d=[];for(let p of t)p.flatten(d);return new oe(d,n)}let o=Math.max(32,i>>5),s=o<<1,l=o>>1,a=[],u=0,h=-1,c=[];function f(d){let p;if(d.lines>s&&d instanceof r)for(let g of d.children)f(g);else d.lines>l&&(u>l||!u)?(m(),a.push(d)):d instanceof oe&&u&&(p=c[c.length-1])instanceof oe&&d.lines+p.lines<=32?(u+=d.lines,h+=d.length+1,c[c.length-1]=new oe(p.text.concat(d.text),p.length+1+d.length)):(u+d.lines>o&&m(),u+=d.lines,h+=d.length+1,c.push(d))}function m(){u!=0&&(a.push(c.length==1?c[0]:r.from(c,h)),h=-1,u=c.length=0)}for(let d of t)f(d);return m(),a.length==1?a[0]:new r(a,n)}};A.empty=new oe([""],0);function Da(r){let e=-1;for(let t of r)e+=t.length+1;return e}function Nn(r,e,t=0,n=1e9){for(let i=0,o=0,s=!0;o<r.length&&i<=n;o++){let l=r[o],a=i+l.length;a>=t&&(a>n&&(l=l.slice(0,n-i)),i<t&&(l=l.slice(t-i)),s?(e[e.length-1]+=l,s=!1):e.push(l)),i=a+1}return e}function Zo(r,e,t){return Nn(r,[""],e,t)}var st=class{constructor(e,t=1){this.dir=t;this.done=!1;this.lineBreak=!1;this.value="";this.nodes=[e],this.offsets=[t>0?1:(e instanceof oe?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let n=this.nodes.length-1,i=this.nodes[n],o=this.offsets[n],s=o>>1,l=i instanceof oe?i.text.length:i.children.length;if(s==(t>0?l:0)){if(n==0)return this.done=!0,this.value="",this;t>0&&this.offsets[n-1]++,this.nodes.pop(),this.offsets.pop()}else if((o&1)==(t>0?0:1)){if(this.offsets[n]+=t,e==0)return this.lineBreak=!0,this.value=`
+`,this;e--}else if(i instanceof oe){let a=i.text[s+(t<0?-1:0)];if(this.offsets[n]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=i.children[s+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[n]+=t):(t<0&&this.offsets[n]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof oe?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}},Pn=class{constructor(e,t,n){this.value="";this.done=!1;this.cursor=new st(e,t>n?-1:1),this.pos=t>n?e.length:0,this.from=Math.min(t,n),this.to=Math.max(t,n)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let n=t<0?this.pos-this.from:this.to-this.pos;e>n&&(e=n),n-=e;let{value:i}=this.cursor.next(e);return this.pos+=(i.length+e)*t,this.value=i.length<=n?i:t<0?i.slice(i.length-n):i.slice(0,n),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}},Vn=class{constructor(e){this.inner=e;this.afterBreak=!0;this.value="";this.done=!1}next(e=0){let{done:t,lineBreak:n,value:i}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):n?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=i,this.afterBreak=!1),this}get lineBreak(){return!1}};typeof Symbol<"u"&&(A.prototype[Symbol.iterator]=function(){return this.iter()},st.prototype[Symbol.iterator]=Pn.prototype[Symbol.iterator]=Vn.prototype[Symbol.iterator]=function(){return this});var Hn=class{constructor(e,t,n,i){this.from=e;this.to=t;this.number=n;this.text=i}get length(){return this.to-this.from}};function Ot(r,e,t){return e=Math.max(0,Math.min(r.length,e)),[e,Math.max(e,Math.min(r.length,t))]}var ui=[],ns=[];(()=>{let r="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e<r.length;e++)(e%2?ns:ui).push(t=t+r[e])})();function Ba(r){if(r<768)return!1;for(let e=0,t=ui.length;;){let n=e+t>>1;if(r<ui[n])t=n;else if(r>=ns[n])e=n+1;else return!0;if(e==t)return!1}}function _o(r){return r>=127462&&r<=127487}var es=8205;function rs(r,e,t=!0,n=!0){return(t?is:Ra)(r,e,n)}function is(r,e,t){if(e==r.length)return e;e&&os(r.charCodeAt(e))&&ss(r.charCodeAt(e-1))&&e--;let n=ai(r,e);for(e+=ts(n);e<r.length;){let i=ai(r,e);if(n==es||i==es||t&&Ba(i))e+=ts(i),n=i;else if(_o(i)){let o=0,s=e-2;for(;s>=0&&_o(ai(r,s));)o++,s-=2;if(o%2==0)break;e+=2}else break}return e}function Ra(r,e,t){for(;e>0;){let n=is(r,e-2,t);if(n<e)return n;e--}return 0}function ai(r,e){let t=r.charCodeAt(e);if(!ss(t)||e+1==r.length)return t;let n=r.charCodeAt(e+1);return os(n)?(t-55296<<10)+(n-56320)+65536:t}function os(r){return r>=56320&&r<57344}function ss(r){return r>=55296&&r<56320}function ts(r){return r<65536?1:2}function z(r,e,t=!0,n=!0){return rs(r,e,t,n)}function Oa(r){return r>=56320&&r<57344}function La(r){return r>=55296&&r<56320}function hi(r,e){let t=r.charCodeAt(e);if(!La(t)||e+1==r.length)return t;let n=r.charCodeAt(e+1);return Oa(n)?(t-55296<<10)+(n-56320)+65536:t}function ci(r){return r<65536?1:2}var Fn=/\r\n?|\n/;var Ie=class r{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;t<this.sections.length;t+=2)e+=this.sections[t];return e}get newLength(){let e=0;for(let t=0;t<this.sections.length;t+=2){let n=this.sections[t+1];e+=n<0?this.sections[t]:n}return e}get empty(){return this.sections.length==0||this.sections.length==2&&this.sections[1]<0}iterGaps(e){for(let t=0,n=0,i=0;t<this.sections.length;){let o=this.sections[t++],s=this.sections[t++];s<0?(e(n,i,o),i+=o):i+=s,n+=o}}iterChangedRanges(e,t=!1){fi(this,e,t)}get invertedDesc(){let e=[];for(let t=0;t<this.sections.length;){let n=this.sections[t++],i=this.sections[t++];i<0?e.push(n,i):e.push(i,n)}return new r(e)}composeDesc(e){return this.empty?e:e.empty?this:ls(this,e)}mapDesc(e,t=!1){return e.empty?this:di(this,e,t)}mapPos(e,t=-1,n=0){let i=0,o=0;for(let s=0;s<this.sections.length;){let l=this.sections[s++],a=this.sections[s++],u=i+l;if(a<0){if(u>e)return o+(e-i);o+=l}else{if(n!=0&&u>=e&&(n==1&&i<e&&u>e||n==2&&i<e||n==3&&u>e))return null;if(u>e||u==e&&t<0&&!l)return e==i||t<0?o:o+a;o+=a}i=u}if(e>i)throw new RangeError(`Position ${e} is out of range for changeset of length ${i}`);return o}touchesRange(e,t=e){for(let n=0,i=0;n<this.sections.length&&i<=t;){let o=this.sections[n++],s=this.sections[n++],l=i+o;if(s>=0&&i<=t&&l>=e)return i<e&&l>t?"cover":!0;i=l}return!1}toString(){let e="";for(let t=0;t<this.sections.length;){let n=this.sections[t++],i=this.sections[t++];e+=(e?" ":"")+n+(i>=0?":"+i:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new r(e)}static create(e){return new r(e)}},G=class r extends Ie{constructor(t,n){super(t);this.inserted=n}apply(t){if(this.length!=t.length)throw new RangeError("Applying change set to a document with the wrong length");return fi(this,(n,i,o,s,l)=>t=t.replace(o,o+(i-n),l),!1),t}mapDesc(t,n=!1){return di(this,t,n,!0)}invert(t){let n=this.sections.slice(),i=[];for(let o=0,s=0;o<n.length;o+=2){let l=n[o],a=n[o+1];if(a>=0){n[o]=a,n[o+1]=l;let u=o>>1;for(;i.length<u;)i.push(A.empty);i.push(l?t.slice(s,s+l):A.empty)}s+=l}return new r(n,i)}compose(t){return this.empty?t:t.empty?this:ls(this,t,!0)}map(t,n=!1){return t.empty?this:di(this,t,n,!0)}iterChanges(t,n=!1){fi(this,t,n)}get desc(){return Ie.create(this.sections)}filter(t){let n=[],i=[],o=[],s=new lt(this);e:for(let l=0,a=0;;){let u=l==t.length?1e9:t[l++];for(;a<u||a==u&&s.len==0;){if(s.done)break e;let c=Math.min(s.len,u-a);Y(o,c,-1);let f=s.ins==-1?-1:s.off==0?s.ins:0;Y(n,c,f),f>0&&je(i,n,s.text),s.forward(c),a+=c}let h=t[l++];for(;a<h;){if(s.done)break e;let c=Math.min(s.len,h-a);Y(n,c,-1),Y(o,c,s.ins==-1?-1:s.off==0?s.ins:0),s.forward(c),a+=c}}return{changes:new r(n,i),filtered:Ie.create(o)}}toJSON(){let t=[];for(let n=0;n<this.sections.length;n+=2){let i=this.sections[n],o=this.sections[n+1];o<0?t.push(i):o==0?t.push([i]):t.push([i].concat(this.inserted[n>>1].toJSON()))}return t}static of(t,n,i){let o=[],s=[],l=0,a=null;function u(c=!1){if(!c&&!o.length)return;l<n&&Y(o,n-l,-1);let f=new r(o,s);a=a?a.compose(f.map(a)):f,o=[],s=[],l=0}function h(c){if(Array.isArray(c))for(let f of c)h(f);else if(c instanceof r){if(c.length!=n)throw new RangeError(`Mismatched change set length (got ${c.length}, expected ${n})`);u(),a=a?a.compose(c.map(a)):c}else{let{from:f,to:m=f,insert:d}=c;if(f>m||f<0||m>n)throw new RangeError(`Invalid change range ${f} to ${m} (in doc of length ${n})`);let p=d?typeof d=="string"?A.of(d.split(i||Fn)):d:A.empty,g=p.length;if(f==m&&g==0)return;f<l&&u(),f>l&&Y(o,f-l,-1),Y(o,m-f,g),je(s,o,p),l=m}}return h(t),u(!a),a}static empty(t){return new r(t?[t,-1]:[],[])}static fromJSON(t){if(!Array.isArray(t))throw new RangeError("Invalid JSON representation of ChangeSet");let n=[],i=[];for(let o=0;o<t.length;o++){let s=t[o];if(typeof s=="number")n.push(s,-1);else{if(!Array.isArray(s)||typeof s[0]!="number"||s.some((l,a)=>a&&typeof l!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)n.push(s[0],0);else{for(;i.length<o;)i.push(A.empty);i[o]=A.of(s.slice(1)),n.push(s[0],i[o].length)}}}return new r(n,i)}static createSet(t,n){return new r(t,n)}};function Y(r,e,t,n=!1){if(e==0&&t<=0)return;let i=r.length-2;i>=0&&t<=0&&t==r[i+1]?r[i]+=e:i>=0&&e==0&&r[i]==0?r[i+1]+=t:n?(r[i]+=e,r[i+1]+=t):r.push(e,t)}function je(r,e,t){if(t.length==0)return;let n=e.length-2>>1;if(n<r.length)r[r.length-1]=r[r.length-1].append(t);else{for(;r.length<n;)r.push(A.empty);r.push(t)}}function fi(r,e,t){let n=r.inserted;for(let i=0,o=0,s=0;s<r.sections.length;){let l=r.sections[s++],a=r.sections[s++];if(a<0)i+=l,o+=l;else{let u=i,h=o,c=A.empty;for(;u+=l,h+=a,a&&n&&(c=c.append(n[s-2>>1])),!(t||s==r.sections.length||r.sections[s+1]<0);)l=r.sections[s++],a=r.sections[s++];e(i,u,o,h,c),i=u,o=h}}}function di(r,e,t,n=!1){let i=[],o=n?[]:null,s=new lt(r),l=new lt(e);for(let a=-1;;){if(s.done&&l.len||l.done&&s.len)throw new Error("Mismatched change set lengths");if(s.ins==-1&&l.ins==-1){let u=Math.min(s.len,l.len);Y(i,u,-1),s.forward(u),l.forward(u)}else if(l.ins>=0&&(s.ins<0||a==s.i||s.off==0&&(l.len<s.len||l.len==s.len&&!t))){let u=l.len;for(Y(i,l.ins,-1);u;){let h=Math.min(s.len,u);s.ins>=0&&a<s.i&&s.len<=h&&(Y(i,0,s.ins),o&&je(o,i,s.text),a=s.i),s.forward(h),u-=h}l.next()}else if(s.ins>=0){let u=0,h=s.len;for(;h;)if(l.ins==-1){let c=Math.min(h,l.len);u+=c,h-=c,l.forward(c)}else if(l.ins==0&&l.len<h)h-=l.len,l.next();else break;Y(i,u,a<s.i?s.ins:0),o&&a<s.i&&je(o,i,s.text),a=s.i,s.forward(s.len-h)}else{if(s.done&&l.done)return o?G.createSet(i,o):Ie.create(i);throw new Error("Mismatched change set lengths")}}}function ls(r,e,t=!1){let n=[],i=t?[]:null,o=new lt(r),s=new lt(e);for(let l=!1;;){if(o.done&&s.done)return i?G.createSet(n,i):Ie.create(n);if(o.ins==0)Y(n,o.len,0,l),o.next();else if(s.len==0&&!s.done)Y(n,0,s.ins,l),i&&je(i,n,s.text),s.next();else{if(o.done||s.done)throw new Error("Mismatched change set lengths");{let a=Math.min(o.len2,s.len),u=n.length;if(o.ins==-1){let h=s.ins==-1?-1:s.off?0:s.ins;Y(n,a,h,l),i&&h&&je(i,n,s.text)}else s.ins==-1?(Y(n,o.off?0:o.len,a,l),i&&je(i,n,o.textBit(a))):(Y(n,o.off?0:o.len,s.off?0:s.ins,l),i&&!s.off&&je(i,n,s.text));l=(o.ins>a||s.ins>=0&&s.len>a)&&(l||n.length>u),o.forward2(a),s.forward(a)}}}}var lt=class{constructor(e){this.set=e;this.i=0;this.next()}next(){let{sections:e}=this.set;this.i<e.length?(this.len=e[this.i++],this.ins=e[this.i++]):(this.len=0,this.ins=-2),this.off=0}get done(){return this.ins==-2}get len2(){return this.ins<0?this.len:this.ins}get text(){let{inserted:e}=this.set,t=this.i-2>>1;return t>=e.length?A.empty:e[t]}textBit(e){let{inserted:t}=this.set,n=this.i-2>>1;return n>=t.length&&!e?A.empty:t[n].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}};var at=class r{constructor(e,t,n){this.from=e;this.to=t;this.flags=n}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}get goalColumn(){let e=this.flags>>6;return e==16777215?void 0:e}map(e,t=-1){let n,i;return this.empty?n=i=e.mapPos(this.from,t):(n=e.mapPos(this.from,1),i=e.mapPos(this.to,-1)),n==this.from&&i==this.to?this:new r(n,i,this.flags)}extend(e,t=e,n=0){if(e<=this.anchor&&t>=this.anchor)return y.range(e,t,void 0,void 0,n);let i=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return y.range(this.anchor,i,void 0,void 0,n)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return y.range(e.anchor,e.head)}static create(e,t,n){return new r(e,t,n)}},y=class r{constructor(e,t){this.ranges=e;this.mainIndex=t}map(e,t=-1){return e.empty?this:r.create(this.ranges.map(n=>n.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let n=0;n<this.ranges.length;n++)if(!this.ranges[n].eq(e.ranges[n],t))return!1;return!0}get main(){return this.ranges[this.mainIndex]}asSingle(){return this.ranges.length==1?this:new r([this.main],0)}addRange(e,t=!0){return r.create([e].concat(this.ranges),t?0:this.mainIndex+1)}replaceRange(e,t=this.mainIndex){let n=this.ranges.slice();return n[t]=e,r.create(n,this.mainIndex)}toJSON(){return{ranges:this.ranges.map(e=>e.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new r(e.ranges.map(t=>at.fromJSON(t)),e.main)}static single(e,t=e){return new r([r.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let n=0,i=0;i<e.length;i++){let o=e[i];if(o.empty?o.from<=n:o.from<n)return r.normalized(e.slice(),t);n=o.to}return new r(e,t)}static cursor(e,t=0,n,i){return at.create(e,e,(t==0?0:t<0?8:16)|(n==null?7:Math.min(6,n))|(i??16777215)<<6)}static range(e,t,n,i,o){let s=(n??16777215)<<6|(i==null?7:Math.min(6,i));return!o&&e!=t&&(o=t<e?1:-1),t<e?at.create(t,e,48|s):at.create(e,t,(o?o<0?8:16:0)|s)}static normalized(e,t=0){let n=e[t];e.sort((i,o)=>i.from-o.from),t=e.indexOf(n);for(let i=1;i<e.length;i++){let o=e[i],s=e[i-1];if(o.empty?o.from<=s.to:o.from<s.to){let l=s.from,a=Math.max(o.to,s.to);i<=t&&t--,e.splice(--i,2,o.anchor>o.head?r.range(a,l):r.range(l,a))}}return new r(e,t)}};function Wn(r,e){for(let t of r.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}var pi=0,T=class r{constructor(e,t,n,i,o){this.combine=e;this.compareInput=t;this.compare=n;this.isStatic=i;this.id=pi++;this.default=e([]),this.extensions=typeof o=="function"?o(this):o}get reader(){return this}static define(e={}){return new r(e.combine||(t=>t),e.compareInput||((t,n)=>t===n),e.compare||(e.combine?(t,n)=>t===n:gi),!!e.static,e.enables)}of(e){return new Lt([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Lt(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Lt(e,this,2,t)}from(e,t){return t||(t=n=>n),this.compute([e],n=>t(n.field(e)))}};function gi(r,e){return r==e||r.length==e.length&&r.every((t,n)=>t===e[n])}var Lt=class{constructor(e,t,n,i){this.dependencies=e;this.facet=t;this.type=n;this.value=i;this.id=pi++}dynamicSlot(e){let t=this.value,n=this.facet.compareInput,i=this.id,o=e[i]>>1,s=this.type==2,l=!1,a=!1,u=[];for(let h of this.dependencies)h=="doc"?l=!0:h=="selection"?a=!0:((e[h.id]??1)&1)==0&&u.push(e[h.id]);return{create(h){return h.values[o]=t(h),1},update(h,c){if(l&&c.docChanged||a&&(c.docChanged||c.selection)||mi(h,u)){let f=t(h);if(s?!as(f,h.values[o],n):!n(f,h.values[o]))return h.values[o]=f,1}return 0},reconfigure:(h,c)=>{let f,m=c.config.address[i];if(m!=null){let d=nn(c,m);if(this.dependencies.every(p=>p instanceof T?c.facet(p)===h.facet(p):p instanceof se?c.field(p,!1)==h.field(p,!1):!0)||(s?as(f=t(h),d,n):n(f=t(h),d)))return h.values[o]=d,0}else f=t(h);return h.values[o]=f,1}}}};function as(r,e,t){if(r.length!=e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function mi(r,e){let t=!1;for(let n of e)It(r,n)&1&&(t=!0);return t}function Ia(r,e,t){let n=t.map(a=>r[a.id]),i=t.map(a=>a.type),o=n.filter(a=>!(a&1)),s=r[e.id]>>1;function l(a){let u=[];for(let h=0;h<n.length;h++){let c=nn(a,n[h]);if(i[h]==2)for(let f of c)u.push(f);else u.push(c)}return e.combine(u)}return{create(a){for(let u of n)It(a,u);return a.values[s]=l(a),1},update(a,u){if(!mi(a,o))return 0;let h=l(a);return e.compare(h,a.values[s])?0:(a.values[s]=h,1)},reconfigure(a,u){let h=mi(a,n),c=u.config.facets[e.id],f=u.facet(e);if(c&&!h&&gi(t,c))return a.values[s]=f,0;let m=l(a);return e.compare(m,f)?(a.values[s]=f,0):(a.values[s]=m,1)}}}var zn=T.define({static:!0}),se=class r{constructor(e,t,n,i,o){this.id=e;this.createF=t;this.updateF=n;this.compareF=i;this.spec=o;this.provides=void 0}static define(e){let t=new r(pi++,e.create,e.update,e.compare||((n,i)=>n===i),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){return(e.facet(zn).find(n=>n.field==this)?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:n=>(n.values[t]=this.create(n),1),update:(n,i)=>{let o=n.values[t],s=this.updateF(o,i);return this.compareF(o,s)?0:(n.values[t]=s,1)},reconfigure:(n,i)=>{let o=n.facet(zn),s=i.facet(zn),l;return(l=o.find(a=>a.field==this))&&l!=s.find(a=>a.field==this)?(n.values[t]=l.create(n),1):i.config.address[this.id]!=null?(n.values[t]=i.field(this),0):(n.values[t]=this.create(n),1)}}}init(e){return[this,zn.of({field:this,create:e})]}get extension(){return this}},ut={lowest:4,low:3,default:2,high:1,highest:0};function _t(r){return e=>new Kn(e,r)}var ct={highest:_t(ut.highest),high:_t(ut.high),default:_t(ut.default),low:_t(ut.low),lowest:_t(ut.lowest)},Kn=class{constructor(e,t){this.inner=e;this.prec=t}},ht=class r{of(e){return new en(this,e)}reconfigure(e){return r.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}},en=class{constructor(e,t){this.compartment=e;this.inner=t}},tn=class r{constructor(e,t,n,i,o,s){this.base=e;this.compartments=t;this.dynamicSlots=n;this.address=i;this.staticValues=o;this.facets=s;this.statusTemplate=[];for(;this.statusTemplate.length<n.length;)this.statusTemplate.push(0)}staticFacet(e){let t=this.address[e.id];return t==null?e.default:this.staticValues[t>>1]}static resolve(e,t,n){let i=[],o=Object.create(null),s=new Map;for(let f of Na(e,t,s))f instanceof se?i.push(f):(o[f.facet.id]||(o[f.facet.id]=[])).push(f);let l=Object.create(null),a=[],u=[];for(let f of i)l[f.id]=u.length<<1,u.push(m=>f.slot(m));let h=n?.config.facets;for(let f in o){let m=o[f],d=m[0].facet,p=h&&h[f]||[];if(m.every(g=>g.type==0))if(l[d.id]=a.length<<1|1,gi(p,m))a.push(n.facet(d));else{let g=d.combine(m.map(b=>b.value));a.push(n&&d.compare(g,n.facet(d))?n.facet(d):g)}else{for(let g of m)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=u.length<<1,u.push(b=>g.dynamicSlot(b)));l[d.id]=u.length<<1,u.push(g=>Ia(g,d,m))}}let c=u.map(f=>f(l));return new r(e,s,c,l,a,o)}};function Na(r,e,t){let n=[[],[],[],[],[]],i=new Map;function o(s,l){let a=i.get(s);if(a!=null){if(a<=l)return;let u=n[a].indexOf(s);u>-1&&n[a].splice(u,1),s instanceof en&&t.delete(s.compartment)}if(i.set(s,l),Array.isArray(s))for(let u of s)o(u,l);else if(s instanceof en){if(t.has(s.compartment))throw new RangeError("Duplicate use of compartment in extensions");let u=e.get(s.compartment)||s.inner;t.set(s.compartment,u),o(u,l)}else if(s instanceof Kn)o(s.inner,s.prec);else if(s instanceof se)n[l].push(s),s.provides&&o(s.provides,l);else if(s instanceof Lt)n[l].push(s),s.facet.extensions&&o(s.facet.extensions,ut.default);else{let u=s.extension;if(!u)throw new Error(`Unrecognized extension value in extension set (${s}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);o(u,l)}}return o(r,ut.default),n.reduce((s,l)=>s.concat(l))}function It(r,e){if(e&1)return 2;let t=e>>1,n=r.status[t];if(n==4)throw new Error("Cyclic dependency between fields and/or facets");if(n&2)return n;r.status[t]=4;let i=r.computeSlot(r,r.config.dynamicSlots[t]);return r.status[t]=2|i}function nn(r,e){return e&1?r.config.staticValues[e>>1]:r.values[e>>1]}var bi=T.define(),Un=T.define({combine:r=>r.some(e=>e),static:!0}),qn=T.define({combine:r=>r.length?r[0]:void 0,static:!0}),Gn=T.define(),jn=T.define(),Jn=T.define(),yi=T.define({combine:r=>r.length?r[0]:!1});var le=class{constructor(e,t){this.type=e;this.value=t}static define(){return new $n}},$n=class{of(e){return new le(this,e)}},Yn=class{constructor(e){this.map=e}of(e){return new W(this,e)}},W=class r{constructor(e,t){this.type=e;this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new r(this.type,t)}is(e){return this.type==e}static define(e={}){return new Yn(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let n=[];for(let i of e){let o=i.map(t);o&&n.push(o)}return n}static{this.reconfigure=r.define()}static{this.appendConfig=r.define()}},X=class r{constructor(e,t,n,i,o,s){this.startState=e;this.changes=t;this.selection=n;this.effects=i;this.annotations=o;this.scrollIntoView=s;this._doc=null;this._state=null;n&&Wn(n,t.newLength),o.some(l=>l.type==r.time)||(this.annotations=o.concat(r.time.of(Date.now())))}static create(e,t,n,i,o,s){return new r(e,t,n,i,o,s)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(r.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}static{this.time=le.define()}static{this.userEvent=le.define()}static{this.addToHistory=le.define()}static{this.remote=le.define()}};function Pa(r,e){let t=[];for(let n=0,i=0;;){let o,s;if(n<r.length&&(i==e.length||e[i]>=r[n]))o=r[n++],s=r[n++];else if(i<e.length)o=e[i++],s=e[i++];else return t;!t.length||t[t.length-1]<o?t.push(o,s):t[t.length-1]<s&&(t[t.length-1]=s)}}function us(r,e,t){let n,i,o;return t?(n=e.changes,i=G.empty(e.changes.length),o=r.changes.compose(e.changes)):(n=e.changes.map(r.changes),i=r.changes.mapDesc(e.changes,!0),o=r.changes.compose(n)),{changes:o,selection:e.selection?e.selection.map(i):r.selection?.map(n),effects:W.mapEffects(r.effects,n).concat(W.mapEffects(e.effects,i)),annotations:r.annotations.length?r.annotations.concat(e.annotations):e.annotations,scrollIntoView:r.scrollIntoView||e.scrollIntoView}}function xi(r,e,t){let n=e.selection,i=ft(e.annotations);return e.userEvent&&(i=i.concat(X.userEvent.of(e.userEvent))),{changes:e.changes instanceof G?e.changes:G.of(e.changes||[],t,r.facet(qn)),selection:n&&(n instanceof y?n:y.single(n.anchor,n.head)),effects:ft(e.effects),annotations:i,scrollIntoView:!!e.scrollIntoView}}function Si(r,e,t){let n=xi(r,e.length?e[0]:{},r.doc.length);e.length&&e[0].filter===!1&&(t=!1);for(let o=1;o<e.length;o++){e[o].filter===!1&&(t=!1);let s=!!e[o].sequential;n=us(n,xi(r,e[o],s?n.changes.newLength:r.doc.length),s)}let i=X.create(r,n.changes,n.selection,n.effects,n.annotations,n.scrollIntoView);return Ha(t?Va(i):i)}function Va(r){let e=r.startState,t=!0;for(let i of e.facet(Gn)){let o=i(r);if(o===!1){t=!1;break}Array.isArray(o)&&(t=t===!0?o:Pa(t,o))}if(t!==!0){let i,o;if(t===!1)o=r.changes.invertedDesc,i=G.empty(e.doc.length);else{let s=r.changes.filter(t);i=s.changes,o=s.filtered.mapDesc(s.changes).invertedDesc}r=X.create(e,i,r.selection&&r.selection.map(o),W.mapEffects(r.effects,o),r.annotations,r.scrollIntoView)}let n=e.facet(jn);for(let i=n.length-1;i>=0;i--){let o=n[i](r);o instanceof X?r=o:Array.isArray(o)&&o.length==1&&o[0]instanceof X?r=o[0]:r=Si(e,ft(o),!1)}return r}function Ha(r){let e=r.startState,t=e.facet(Jn),n=r;for(let i=t.length-1;i>=0;i--){let o=t[i](r);o&&Object.keys(o).length&&(n=us(n,xi(e,o,r.changes.newLength),!0))}return n==r?r:X.create(e,r.changes,r.selection,n.effects,n.annotations,n.scrollIntoView)}var Fa=[];function ft(r){return r==null?Fa:Array.isArray(r)?r:[r]}var Wa=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,Ti;try{Ti=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function za(r){if(Ti)return Ti.test(r);for(let e=0;e<r.length;e++){let t=r[e];if(/\w/.test(t)||t>"\x80"&&(t.toUpperCase()!=t.toLowerCase()||Wa.test(t)))return!0}return!1}function hs(r){return e=>{if(!/\S/.test(e))return 1;if(za(e))return 0;for(let t=0;t<r.length;t++)if(e.indexOf(r[t])>-1)return 0;return 2}}var j=class r{constructor(e,t,n,i,o,s){this.config=e;this.doc=t;this.selection=n;this.values=i;this.status=e.statusTemplate.slice(),this.computeSlot=o,s&&(s._state=this);for(let l=0;l<this.config.dynamicSlots.length;l++)It(this,l<<1);this.computeSlot=null}field(e,t=!0){let n=this.config.address[e.id];if(n==null){if(t)throw new RangeError("Field is not present in this state");return}return It(this,n),nn(this,n)}update(...e){return Si(this,e,!0)}applyTransaction(e){let t=this.config,{base:n,compartments:i}=t;for(let l of e.effects)l.is(ht.reconfigure)?(t&&(i=new Map,t.compartments.forEach((a,u)=>i.set(u,a)),t=null),i.set(l.value.compartment,l.value.extension)):l.is(W.reconfigure)?(t=null,n=l.value):l.is(W.appendConfig)&&(t=null,n=ft(n).concat(l.value));let o;t?o=e.startState.values.slice():(t=tn.resolve(n,i,this),o=new r(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,u)=>u.reconfigure(a,this),null).values);let s=e.startState.facet(Un)?e.newSelection:e.newSelection.asSingle();new r(t,e.newDoc,s,o,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:y.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,n=e(t.ranges[0]),i=this.changes(n.changes),o=[n.range],s=ft(n.effects);for(let l=1;l<t.ranges.length;l++){let a=e(t.ranges[l]),u=this.changes(a.changes),h=u.map(i);for(let f=0;f<l;f++)o[f]=o[f].map(h);let c=i.mapDesc(u,!0);o.push(a.range.map(c)),i=i.compose(h),s=W.mapEffects(s,h).concat(W.mapEffects(ft(a.effects),c))}return{changes:i,selection:y.create(o,t.mainIndex),effects:s}}changes(e=[]){return e instanceof G?e:G.of(e,this.doc.length,this.facet(r.lineSeparator))}toText(e){return A.of(e.split(this.facet(r.lineSeparator)||Fn))}sliceDoc(e=0,t=this.doc.length){return this.doc.sliceString(e,t,this.lineBreak)}facet(e){let t=this.config.address[e.id];return t==null?e.default:(It(this,t),nn(this,t))}toJSON(e){let t={doc:this.sliceDoc(),selection:this.selection.toJSON()};if(e)for(let n in e){let i=e[n];i instanceof se&&this.config.address[i.id]!=null&&(t[n]=i.spec.toJSON(this.field(e[n]),this))}return t}static fromJSON(e,t={},n){if(!e||typeof e.doc!="string")throw new RangeError("Invalid JSON representation for EditorState");let i=[];if(n){for(let o in n)if(Object.prototype.hasOwnProperty.call(e,o)){let s=n[o],l=e[o];i.push(s.init(a=>s.spec.fromJSON(l,a)))}}return r.create({doc:e.doc,selection:y.fromJSON(e.selection),extensions:t.extensions?i.concat([t.extensions]):i})}static create(e={}){let t=tn.resolve(e.extensions||[],new Map),n=e.doc instanceof A?e.doc:A.of((e.doc||"").split(t.staticFacet(r.lineSeparator)||Fn)),i=e.selection?e.selection instanceof y?e.selection:y.single(e.selection.anchor,e.selection.head):y.single(0);return Wn(i,n.length),t.staticFacet(Un)||(i=i.asSingle()),new r(t,n,i,t.dynamicSlots.map(()=>null),(o,s)=>s.create(o),null)}static{this.allowMultipleSelections=Un}static{this.tabSize=T.define({combine:e=>e.length?e[0]:4})}get tabSize(){return this.facet(r.tabSize)}static{this.lineSeparator=qn}get lineBreak(){return this.facet(r.lineSeparator)||`
+`}static{this.readOnly=yi}get readOnly(){return this.facet(yi)}static{this.phrases=T.define({compare(e,t){let n=Object.keys(e),i=Object.keys(t);return n.length==i.length&&n.every(o=>e[o]==t[o])}})}phrase(e,...t){for(let n of this.facet(r.phrases))if(Object.prototype.hasOwnProperty.call(n,e)){e=n[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(n,i)=>{if(i=="$")return"$";let o=+(i||1);return!o||o>t.length?n:t[o-1]})),e}static{this.languageData=bi}languageDataAt(e,t,n=-1){let i=[];for(let o of this.facet(bi))for(let s of o(this,t,n))Object.prototype.hasOwnProperty.call(s,e)&&i.push(s[e]);return i}charCategorizer(e){let t=this.languageDataAt("wordChars",e);return hs(t.length?t[0]:"")}wordAt(e){let{text:t,from:n,length:i}=this.doc.lineAt(e),o=this.charCategorizer(e),s=e-n,l=e-n;for(;s>0;){let a=z(t,s,!1);if(o(t.slice(a,s))!=0)break;s=a}for(;l<i;){let a=z(t,l);if(o(t.slice(l,a))!=0)break;l=a}return s==l?null:y.range(s+n,l+n)}static{this.changeFilter=Gn}static{this.transactionFilter=jn}static{this.transactionExtender=Jn}};ht.reconfigure=W.define();function dt(r,e,t={}){let n={};for(let i of r)for(let o of Object.keys(i)){let s=i[o],l=n[o];if(l===void 0)n[o]=s;else if(!(l===s||s===void 0))if(Object.hasOwnProperty.call(t,o))n[o]=t[o](l,s);else throw new Error("Config merge conflict for field "+o)}for(let i in e)n[i]===void 0&&(n[i]=e[i]);return n}var Ne=class{eq(e){return this==e}range(e,t=e){return Nt.create(e,t,this)}};Ne.prototype.startSide=Ne.prototype.endSide=0;Ne.prototype.point=!1;Ne.prototype.mapMode=1;function Mi(r,e){return r==e||r.constructor==e.constructor&&r.eq(e)}var Nt=class r{constructor(e,t,n){this.from=e;this.to=t;this.value=n}static create(e,t,n){return new r(e,t,n)}};function Ci(r,e){return r.from-e.from||r.value.startSide-e.value.startSide}var ki=class r{constructor(e,t,n,i){this.from=e;this.to=t;this.value=n;this.maxPoint=i}get length(){return this.to[this.to.length-1]}findIndex(e,t,n,i=0){let o=n?this.to:this.from;for(let s=i,l=o.length;;){if(s==l)return s;let a=s+l>>1,u=o[a]-e||(n?this.value[a].endSide:this.value[a].startSide)-t;if(a==s)return u>=0?s:l;u>=0?l=a:s=a+1}}between(e,t,n,i){for(let o=this.findIndex(t,-1e9,!0),s=this.findIndex(n,1e9,!1,o);o<s;o++)if(i(this.from[o]+e,this.to[o]+e,this.value[o])===!1)return!1}map(e,t){let n=[],i=[],o=[],s=-1,l=-1;for(let a=0;a<this.value.length;a++){let u=this.value[a],h=this.from[a]+e,c=this.to[a]+e,f,m;if(h==c){let d=t.mapPos(h,u.startSide,u.mapMode);if(d==null||(f=m=d,u.startSide!=u.endSide&&(m=t.mapPos(h,u.endSide),m<f)))continue}else if(f=t.mapPos(h,u.startSide),m=t.mapPos(c,u.endSide),f>m||f==m&&u.startSide>0&&u.endSide<=0)continue;(m-f||u.endSide-u.startSide)<0||(s<0&&(s=f),u.point&&(l=Math.max(l,m-f)),n.push(u),i.push(f-s),o.push(m-s))}return{mapped:n.length?new r(i,o,n,l):null,pos:s}}},N=class r{constructor(e,t,n,i){this.chunkPos=e;this.chunk=t;this.nextLayer=n;this.maxPoint=i}static create(e,t,n,i){return new r(e,t,n,i)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:n=!1,filterFrom:i=0,filterTo:o=this.length}=e,s=e.filter;if(t.length==0&&!s)return this;if(n&&(t=t.slice().sort(Ci)),this.isEmpty)return t.length?r.of(t):this;let l=new Zn(this,null,-1).goto(0),a=0,u=[],h=new rn;for(;l.value||a<t.length;)if(a<t.length&&(l.from-t[a].from||l.startSide-t[a].value.startSide)>=0){let c=t[a++];h.addInner(c.from,c.to,c.value)||u.push(c)}else l.rangeIndex==1&&l.chunkIndex<this.chunk.length&&(a==t.length||this.chunkEnd(l.chunkIndex)<t[a].from)&&(!s||i>this.chunkEnd(l.chunkIndex)||o<this.chunkPos[l.chunkIndex])&&h.addChunk(this.chunkPos[l.chunkIndex],this.chunk[l.chunkIndex])?l.nextChunk():((!s||i>l.to||o<l.from||s(l.from,l.to,l.value))&&(h.addInner(l.from,l.to,l.value)||u.push(Nt.create(l.from,l.to,l.value))),l.next());return h.finishInner(this.nextLayer.isEmpty&&!u.length?r.empty:this.nextLayer.update({add:u,filter:s,filterFrom:i,filterTo:o}))}map(e){if(e.empty||this.isEmpty)return this;let t=[],n=[],i=-1;for(let s=0;s<this.chunk.length;s++){let l=this.chunkPos[s],a=this.chunk[s],u=e.touchesRange(l,l+a.length);if(u===!1)i=Math.max(i,a.maxPoint),t.push(a),n.push(e.mapPos(l));else if(u===!0){let{mapped:h,pos:c}=a.map(l,e);h&&(i=Math.max(i,h.maxPoint),t.push(h),n.push(c))}}let o=this.nextLayer.map(e);return t.length==0?o:new r(n,t,o||r.empty,i)}between(e,t,n){if(!this.isEmpty){for(let i=0;i<this.chunk.length;i++){let o=this.chunkPos[i],s=this.chunk[i];if(t>=o&&e<=o+s.length&&s.between(o,e-o,t-o,n)===!1)return}this.nextLayer.between(e,t,n)}}iter(e=0){return on.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return on.from(e).goto(t)}static compare(e,t,n,i,o=-1){let s=e.filter(c=>c.maxPoint>0||!c.isEmpty&&c.maxPoint>=o),l=t.filter(c=>c.maxPoint>0||!c.isEmpty&&c.maxPoint>=o),a=fs(s,l,n),u=new mt(s,a,o),h=new mt(l,a,o);n.iterGaps((c,f,m)=>ds(u,c,h,f,m,i)),n.empty&&n.length==0&&ds(u,0,h,0,0,i)}static eq(e,t,n=0,i){i==null&&(i=999999999);let o=e.filter(h=>!h.isEmpty&&t.indexOf(h)<0),s=t.filter(h=>!h.isEmpty&&e.indexOf(h)<0);if(o.length!=s.length)return!1;if(!o.length)return!0;let l=fs(o,s),a=new mt(o,l,0).goto(n),u=new mt(s,l,0).goto(n);for(;;){if(a.to!=u.to||!vi(a.active,u.active)||a.point&&(!u.point||!Mi(a.point,u.point)))return!1;if(a.to>i)return!0;a.next(),u.next()}}static spans(e,t,n,i,o=-1){let s=new mt(e,null,o).goto(t),l=t,a=s.openStart;for(;;){let u=Math.min(s.to,n);if(s.point){let h=s.activeForPoint(s.to),c=s.pointFrom<t?h.length+1:s.point.startSide<0?h.length:Math.min(h.length,a);i.point(l,u,s.point,h,c,s.pointRank),a=Math.min(s.openEnd(u),h.length)}else u>l&&(i.span(l,u,s.active,a),a=s.openEnd(u));if(s.to>n)return a+(s.point&&s.to>n?1:0);l=s.to,s.next()}}static of(e,t=!1){let n=new rn;for(let i of e instanceof Nt?[e]:t?Ka(e):e)n.add(i.from,i.to,i.value);return n.finish()}static join(e){if(!e.length)return r.empty;let t=e[e.length-1];for(let n=e.length-2;n>=0;n--)for(let i=e[n];i!=r.empty;i=i.nextLayer)t=new r(i.chunkPos,i.chunk,t,Math.max(i.maxPoint,t.maxPoint));return t}static{this.empty=new r([],[],null,-1)}};function Ka(r){if(r.length>1)for(let e=r[0],t=1;t<r.length;t++){let n=r[t];if(Ci(e,n)>0)return r.slice().sort(Ci);e=n}return r}N.empty.nextLayer=N.empty;var rn=class r{constructor(){this.chunks=[];this.chunkPos=[];this.chunkStart=-1;this.last=null;this.lastFrom=-1e9;this.lastTo=-1e9;this.from=[];this.to=[];this.value=[];this.maxPoint=-1;this.setMaxPoint=-1;this.nextLayer=null}finishChunk(e){this.chunks.push(new ki(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,e&&(this.from=[],this.to=[],this.value=[])}add(e,t,n){this.addInner(e,t,n)||(this.nextLayer||(this.nextLayer=new r)).add(e,t,n)}addInner(e,t,n){let i=e-this.lastTo||n.startSide-this.last.endSide;if(i<=0&&(e-this.lastFrom||n.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return i<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=e),this.from.push(e-this.chunkStart),this.to.push(t-this.chunkStart),this.last=n,this.lastFrom=e,this.lastTo=t,this.value.push(n),n.point&&(this.maxPoint=Math.max(this.maxPoint,t-e)),!0)}addChunk(e,t){if((e-this.lastTo||t.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,t.maxPoint),this.chunks.push(t),this.chunkPos.push(e);let n=t.value.length-1;return this.last=t.value[n],this.lastFrom=t.from[n]+e,this.lastTo=t.to[n]+e,!0}finish(){return this.finishInner(N.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let t=N.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,t}};function fs(r,e,t){let n=new Map;for(let o of r)for(let s=0;s<o.chunk.length;s++)o.chunk[s].maxPoint<=0&&n.set(o.chunk[s],o.chunkPos[s]);let i=new Set;for(let o of e)for(let s=0;s<o.chunk.length;s++){let l=n.get(o.chunk[s]);l!=null&&(t?t.mapPos(l):l)==o.chunkPos[s]&&!t?.touchesRange(l,l+o.chunk[s].length)&&i.add(o.chunk[s])}return i}var Zn=class{constructor(e,t,n,i=0){this.layer=e;this.skip=t;this.minPoint=n;this.rank=i}get startSide(){return this.value?this.value.startSide:0}get endSide(){return this.value?this.value.endSide:0}goto(e,t=-1e9){return this.chunkIndex=this.rangeIndex=0,this.gotoInner(e,t,!1),this}gotoInner(e,t,n){for(;this.chunkIndex<this.layer.chunk.length;){let i=this.layer.chunk[this.chunkIndex];if(!(this.skip&&this.skip.has(i)||this.layer.chunkEnd(this.chunkIndex)<e||i.maxPoint<this.minPoint))break;this.chunkIndex++,n=!1}if(this.chunkIndex<this.layer.chunk.length){let i=this.layer.chunk[this.chunkIndex].findIndex(e-this.layer.chunkPos[this.chunkIndex],t,!0);(!n||this.rangeIndex<i)&&this.setRangeIndex(i)}this.next()}forward(e,t){(this.to-e||this.endSide-t)<0&&this.gotoInner(e,t,!0)}next(){for(;;)if(this.chunkIndex==this.layer.chunk.length){this.from=this.to=1e9,this.value=null;break}else{let e=this.layer.chunkPos[this.chunkIndex],t=this.layer.chunk[this.chunkIndex],n=e+t.from[this.rangeIndex];if(this.from=n,this.to=e+t.to[this.rangeIndex],this.value=t.value[this.rangeIndex],this.setRangeIndex(this.rangeIndex+1),this.minPoint<0||this.value.point&&this.to-this.from>=this.minPoint)break}}setRangeIndex(e){if(e==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex<this.layer.chunk.length&&this.skip.has(this.layer.chunk[this.chunkIndex]);)this.chunkIndex++;this.rangeIndex=0}else this.rangeIndex=e}nextChunk(){this.chunkIndex++,this.rangeIndex=0,this.next()}compare(e){return this.from-e.from||this.startSide-e.startSide||this.rank-e.rank||this.to-e.to||this.endSide-e.endSide}},on=class r{constructor(e){this.heap=e}static from(e,t=null,n=-1){let i=[];for(let o=0;o<e.length;o++)for(let s=e[o];!s.isEmpty;s=s.nextLayer)s.maxPoint>=n&&i.push(new Zn(s,t,n,o));return i.length==1?i[0]:new r(i)}get startSide(){return this.value?this.value.startSide:0}goto(e,t=-1e9){for(let n of this.heap)n.goto(e,t);for(let n=this.heap.length>>1;n>=0;n--)wi(this.heap,n);return this.next(),this}forward(e,t){for(let n of this.heap)n.forward(e,t);for(let n=this.heap.length>>1;n>=0;n--)wi(this.heap,n);(this.to-e||this.value.endSide-t)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let e=this.heap[0];this.from=e.from,this.to=e.to,this.value=e.value,this.rank=e.rank,e.value&&e.next(),wi(this.heap,0)}}};function wi(r,e){for(let t=r[e];;){let n=(e<<1)+1;if(n>=r.length)break;let i=r[n];if(n+1<r.length&&i.compare(r[n+1])>=0&&(i=r[n+1],n++),t.compare(i)<0)break;r[n]=t,r[e]=i,e=n}}var mt=class{constructor(e,t,n){this.minPoint=n;this.active=[];this.activeTo=[];this.activeRank=[];this.minActive=-1;this.point=null;this.pointFrom=0;this.pointRank=0;this.to=-1e9;this.endSide=0;this.openStart=-1;this.cursor=on.from(e,t,n)}goto(e,t=-1e9){return this.cursor.goto(e,t),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=e,this.endSide=t,this.openStart=-1,this.next(),this}forward(e,t){for(;this.minActive>-1&&(this.activeTo[this.minActive]-e||this.active[this.minActive].endSide-t)<0;)this.removeActive(this.minActive);this.cursor.forward(e,t)}removeActive(e){Xn(this.active,e),Xn(this.activeTo,e),Xn(this.activeRank,e),this.minActive=ms(this.active,this.activeTo)}addActive(e){let t=0,{value:n,to:i,rank:o}=this.cursor;for(;t<this.activeRank.length&&(o-this.activeRank[t]||i-this.activeTo[t])>0;)t++;Qn(this.active,t,n),Qn(this.activeTo,t,i),Qn(this.activeRank,t,o),e&&Qn(e,t,this.cursor.from),this.minActive=ms(this.active,this.activeTo)}next(){let e=this.to,t=this.point;this.point=null;let n=this.openStart<0?[]:null;for(;;){let i=this.minActive;if(i>-1&&(this.activeTo[i]-this.cursor.from||this.active[i].endSide-this.cursor.startSide)<0){if(this.activeTo[i]>e){this.to=this.activeTo[i],this.endSide=this.active[i].endSide;break}this.removeActive(i),n&&Xn(n,i)}else if(this.cursor.value)if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let o=this.cursor.value;if(!o.point)this.addActive(n),this.cursor.next();else if(t&&this.cursor.to==this.to&&this.cursor.from<this.cursor.to)this.cursor.next();else{this.point=o,this.pointFrom=this.cursor.from,this.pointRank=this.cursor.rank,this.to=this.cursor.to,this.endSide=o.endSide,this.cursor.next(),this.forward(this.to,this.endSide);break}}else{this.to=this.endSide=1e9;break}}if(n){this.openStart=0;for(let i=n.length-1;i>=0&&n[i]<e;i--)this.openStart++}}activeForPoint(e){if(!this.active.length)return this.active;let t=[];for(let n=this.active.length-1;n>=0&&!(this.activeRank[n]<this.pointRank);n--)(this.activeTo[n]>e||this.activeTo[n]==e&&this.active[n].endSide>=this.point.endSide)&&t.push(this.active[n]);return t.reverse()}openEnd(e){let t=0;for(let n=this.activeTo.length-1;n>=0&&this.activeTo[n]>e;n--)t++;return t}};function ds(r,e,t,n,i,o){r.goto(e),t.goto(n);let s=n+i,l=n,a=n-e,u=!!o.boundChange;for(let h=!1;;){let c=r.to+a-t.to,f=c||r.endSide-t.endSide,m=f<0?r.to+a:t.to,d=Math.min(m,s);if(r.point||t.point?(r.point&&t.point&&Mi(r.point,t.point)&&vi(r.activeForPoint(r.to),t.activeForPoint(t.to))||o.comparePoint(l,d,r.point,t.point),h=!1):(h&&o.boundChange(l),d>l&&!vi(r.active,t.active)&&o.compareRange(l,d,r.active,t.active),u&&d<s&&(c||r.openEnd(m)!=t.openEnd(m))&&(h=!0)),m>s)break;l=m,f<=0&&r.next(),f>=0&&t.next()}}function vi(r,e){if(r.length!=e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!=e[t]&&!Mi(r[t],e[t]))return!1;return!0}function Xn(r,e){for(let t=e,n=r.length-1;t<n;t++)r[t]=r[t+1];r.pop()}function Qn(r,e,t){for(let n=r.length-1;n>=e;n--)r[n+1]=r[n];r[e]=t}function ms(r,e){let t=-1,n=1e9;for(let i=0;i<e.length;i++)(e[i]-n||r[i].endSide-r[t].endSide)<0&&(t=i,n=e[i]);return t}function pt(r,e,t=r.length){let n=0;for(let i=0;i<t&&i<r.length;)r.charCodeAt(i)==9?(n+=e-n%e,i++):(n++,i=z(r,i));return n}function Ei(r,e,t,n){for(let i=0,o=0;;){if(o>=e)return i;if(i==r.length)break;o+=r.charCodeAt(i)==9?t-o%t:1,i=z(r,i)}return n===!0?-1:r.length}var ps=typeof Symbol>"u"?"__\u037C":Symbol.for("\u037C"),Ai=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),gs=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{},Pe=class{constructor(e,t){this.rules=[];let{finish:n}=t||{};function i(s){return/^@/.test(s)?[s]:s.split(/,\s*/)}function o(s,l,a,u){let h=[],c=/^@(\w+)\b/.exec(s[0]),f=c&&c[1]=="keyframes";if(c&&l==null)return a.push(s[0]+";");for(let m in l){let d=l[m];if(/&/.test(m))o(m.split(/,\s*/).map(p=>s.map(g=>p.replace(/&/,g))).reduce((p,g)=>p.concat(g)),d,a);else if(d&&typeof d=="object"){if(!c)throw new RangeError("The value of a property ("+m+") should be a primitive value.");o(i(m),d,h,f)}else d!=null&&h.push(m.replace(/_.*/,"").replace(/[A-Z]/g,p=>"-"+p.toLowerCase())+": "+d+";")}(h.length||f)&&a.push((n&&!c&&!u?s.map(n):s).join(", ")+" {"+h.join(" ")+"}")}for(let s in e)o(i(s),e[s],this.rules)}getRules(){return this.rules.join(`
+`)}static newName(){let e=gs[ps]||1;return gs[ps]=e+1,"\u037C"+e.toString(36)}static mount(e,t,n){let i=e[Ai],o=n&&n.nonce;i?o&&i.setNonce(o):i=new Di(e,o),i.mount(Array.isArray(t)?t:[t],e)}},bs=new Map,Di=class{constructor(e,t){let n=e.ownerDocument||e,i=n.defaultView;if(!e.head&&e.adoptedStyleSheets&&i.CSSStyleSheet){let o=bs.get(n);if(o)return e[Ai]=o;this.sheet=new i.CSSStyleSheet,bs.set(n,this)}else this.styleTag=n.createElement("style"),t&&this.styleTag.setAttribute("nonce",t);this.modules=[],e[Ai]=this}mount(e,t){let n=this.sheet,i=0,o=0;for(let s=0;s<e.length;s++){let l=e[s],a=this.modules.indexOf(l);if(a<o&&a>-1&&(this.modules.splice(a,1),o--,a=-1),a==-1){if(this.modules.splice(o++,0,l),n)for(let u=0;u<l.rules.length;u++)n.insertRule(l.rules[u],i++)}else{for(;o<a;)i+=this.modules[o++].rules.length;i+=l.rules.length,o++}}if(n)t.adoptedStyleSheets.indexOf(this.sheet)<0&&(t.adoptedStyleSheets=[this.sheet,...t.adoptedStyleSheets]);else{let s="";for(let a=0;a<this.modules.length;a++)s+=this.modules[a].getRules()+`
+`;this.styleTag.textContent=s;let l=t.head||t;this.styleTag.parentNode!=l&&l.insertBefore(this.styleTag,l.firstChild)}}setNonce(e){this.styleTag&&this.styleTag.getAttribute("nonce")!=e&&this.styleTag.setAttribute("nonce",e)}};var Z=typeof navigator<"u"?navigator:{userAgent:"",vendor:"",platform:""},Ri=typeof document<"u"?document:{documentElement:{style:{}}},Oi=/Edge\/(\d+)/.exec(Z.userAgent),Ts=/MSIE \d/.test(Z.userAgent),Li=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(Z.userAgent),_n=!!(Ts||Li||Oi),ys=!_n&&/gecko\/(\d+)/i.test(Z.userAgent),Bi=!_n&&/Chrome\/(\d+)/.exec(Z.userAgent),xs="webkitFontSmoothing"in Ri.documentElement.style,Ii=!_n&&/Apple Computer/.test(Z.vendor),Ss=Ii&&(/Mobile\/\w+/.test(Z.userAgent)||Z.maxTouchPoints>2),S={mac:Ss||/Mac/.test(Z.platform),windows:/Win/.test(Z.platform),linux:/Linux|X11/.test(Z.platform),ie:_n,ie_version:Ts?Ri.documentMode||6:Li?+Li[1]:Oi?+Oi[1]:0,gecko:ys,gecko_version:ys?+(/Firefox\/(\d+)/.exec(Z.userAgent)||[0,0])[1]:0,chrome:!!Bi,chrome_version:Bi?+Bi[1]:0,ios:Ss,android:/Android\b/.test(Z.userAgent),webkit:xs,webkit_version:xs?+(/\bAppleWebKit\/(\d+)/.exec(Z.userAgent)||[0,0])[1]:0,safari:Ii,safari_version:Ii?+(/\bVersion\/(\d+(\.\d+)?)/.exec(Z.userAgent)||[0,0])[1]:0,tabSize:Ri.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};function Pt(r,e){for(let t in r)t=="class"&&e.class?e.class+=" "+r.class:t=="style"&&e.style?e.style+=";"+r.style:e[t]=r[t];return e}var sn=Object.create(null);function er(r,e,t){if(r==e)return!0;r||(r=sn),e||(e=sn);let n=Object.keys(r),i=Object.keys(e);if(n.length-(t&&n.indexOf(t)>-1?1:0)!=i.length-(t&&i.indexOf(t)>-1?1:0))return!1;for(let o of n)if(o!=t&&(i.indexOf(o)==-1||r[o]!==e[o]))return!1;return!0}function ws(r,e){for(let t=r.attributes.length-1;t>=0;t--){let n=r.attributes[t].name;e[n]==null&&r.removeAttribute(n)}for(let t in e){let n=e[t];t=="style"?r.style.cssText=n:r.getAttribute(t)!=n&&r.setAttribute(t,n)}}function Ni(r,e,t){let n=!1;if(e)for(let i in e)t&&i in t||(n=!0,i=="style"?r.style.cssText="":r.removeAttribute(i));if(t)for(let i in t)e&&e[i]==t[i]||(n=!0,i=="style"?r.style.cssText=t[i]:r.setAttribute(i,t[i]));return n}function Cs(r){let e=Object.create(null);for(let t=0;t<r.attributes.length;t++){let n=r.attributes[t];e[n.name]=n.value}return e}var ke=class{eq(e){return!1}updateDOM(e,t,n){return!1}compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}get estimatedHeight(){return-1}get lineBreaks(){return 0}ignoreEvent(e){return!0}coordsAt(e,t,n){return null}get isHidden(){return!1}get editable(){return!1}destroy(e){}};var V=class extends Ne{constructor(t,n,i,o){super();this.startSide=t;this.endSide=n;this.widget=i;this.spec=o}get heightRelevant(){return!1}static mark(t){return new Vt(t)}static widget(t){let n=Math.max(-1e4,Math.min(1e4,t.side||0)),i=!!t.block;return n+=i&&!t.inlineOrder?n>0?3e8:-4e8:n>0?1e8:-1e8,new We(t,n,n,i,t.widget||null,!1)}static replace(t){let n=!!t.block,i,o;if(t.isBlockGap)i=-5e8,o=4e8;else{let{start:s,end:l}=ks(t,n);i=(s?n?-3e8:-1:5e8)-1,o=(l?n?2e8:1:-6e8)+1}return new We(t,i,o,n,t.widget||null,!0)}static line(t){return new ln(t)}static set(t,n=!1){return N.of(t,n)}static{this.none=N.empty}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}},Vt=class r extends V{constructor(e){let{start:t,end:n}=ks(e);super(t?-1:5e8,n?1:-6e8,null,e),this.tagName=e.tagName||"span",this.attrs=e.class&&e.attributes?Pt(e.attributes,{class:e.class}):e.class?{class:e.class}:e.attributes||sn}eq(e){return this==e||e instanceof r&&this.tagName==e.tagName&&er(this.attrs,e.attrs)}range(e,t=e){if(e>=t)throw new RangeError("Mark decorations may not be empty");return super.range(e,t)}};Vt.prototype.point=!1;var ln=class r extends V{constructor(e){super(-2e8,-2e8,null,e)}eq(e){return e instanceof r&&this.spec.class==e.spec.class&&er(this.spec.attributes,e.spec.attributes)}range(e,t=e){if(t!=e)throw new RangeError("Line decoration ranges must be zero-length");return super.range(e,t)}};ln.prototype.mapMode=2;ln.prototype.point=!0;var We=class r extends V{constructor(t,n,i,o,s,l){super(n,i,s,t);this.block=o;this.isReplace=l;this.mapMode=o?n<=0?2:3:1}get type(){return this.startSide!=this.endSide?3:this.startSide<=0?1:2}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(t){return t instanceof r&&qa(this.widget,t.widget)&&this.block==t.block&&this.startSide==t.startSide&&this.endSide==t.endSide}range(t,n=t){if(this.isReplace&&(t>n||t==n&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&n!=t)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(t,n)}};We.prototype.point=!0;function ks(r,e=!1){let{inclusiveStart:t,inclusiveEnd:n}=r;return t==null&&(t=r.inclusive),n==null&&(n=r.inclusive),{start:t??e,end:n??e}}function qa(r,e){return r==e||!!(r&&e&&r.compare(e))}function Je(r,e,t,n=0){let i=t.length-1;i>=0&&t[i]+n>=r?t[i]=Math.max(t[i],e):t.push(r,e)}var an=class r extends Ne{constructor(t,n){super();this.tagName=t;this.attributes=n}eq(t){return t==this||t instanceof r&&this.tagName==t.tagName&&er(this.attributes,t.attributes)}static create(t){return new r(t.tagName,t.attributes||sn)}static set(t,n=!1){return N.of(t,n)}};an.prototype.startSide=an.prototype.endSide=-1;function $e(r){let e;return r.nodeType==11?e=r.getSelection?r:r.ownerDocument:e=r,e.getSelection()}function nr(r,e){return e?r==e||r.contains(e.nodeType!=1?e.parentNode:e):!1}function Ye(r,e){if(!e.anchorNode)return!1;try{return nr(r,e.anchorNode)}catch{return!1}}function Ht(r){return r.nodeType==3?Xe(r,0,r.nodeValue.length).getClientRects():r.nodeType==1?r.getClientRects():[]}function bt(r,e,t,n){return t?vs(r,e,t,n,-1)||vs(r,e,t,n,1):!1}function Ve(r){for(var e=0;;e++)if(r=r.previousSibling,!r)return e}function un(r){return r.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(r.nodeName)}function vs(r,e,t,n,i){for(;;){if(r==t&&e==n)return!0;if(e==(i<0?0:ae(r))){if(r.nodeName=="DIV")return!1;let o=r.parentNode;if(!o||o.nodeType!=1)return!1;e=Ve(r)+(i<0?0:1),r=o}else if(r.nodeType==1){if(r=r.childNodes[e+(i<0?-1:0)],r.nodeType==1&&r.contentEditable=="false")return!1;e=i<0?ae(r):0}else return!1}}function ae(r){return r.nodeType==3?r.nodeValue.length:r.childNodes.length}function Ft(r,e){let t=e?r.left:r.right;return{left:t,right:t,top:r.top,bottom:r.bottom}}function Ga(r){let e=r.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:r.innerWidth,top:0,bottom:r.innerHeight}}function Pi(r,e){let t=e.width/r.offsetWidth,n=e.height/r.offsetHeight;return(t>.995&&t<1.005||!isFinite(t)||Math.abs(e.width-r.offsetWidth)<1)&&(t=1),(n>.995&&n<1.005||!isFinite(n)||Math.abs(e.height-r.offsetHeight)<1)&&(n=1),{scaleX:t,scaleY:n}}function Es(r,e,t,n,i,o,s,l){let a=r.ownerDocument,u=a.defaultView||window;for(let h=r,c=!1;h&&!c;)if(h.nodeType==1){let f,m=h==a.body,d=1,p=1;if(m)f=Ga(u);else{if(/^(fixed|sticky)$/.test(getComputedStyle(h).position)&&(c=!0),h.scrollHeight<=h.clientHeight&&h.scrollWidth<=h.clientWidth){h=h.assignedSlot||h.parentNode;continue}let C=h.getBoundingClientRect();({scaleX:d,scaleY:p}=Pi(h,C)),f={left:C.left,right:C.left+h.clientWidth*d,top:C.top,bottom:C.top+h.clientHeight*p}}let g=0,b=0;if(i=="nearest")e.top<f.top+s?(b=e.top-(f.top+s),t>0&&e.bottom>f.bottom+b&&(b=e.bottom-f.bottom+s)):e.bottom>f.bottom-s&&(b=e.bottom-f.bottom+s,t<0&&e.top-b<f.top&&(b=e.top-(f.top+s)));else{let C=e.bottom-e.top,v=f.bottom-f.top;b=(i=="center"&&C<=v?e.top+C/2-v/2:i=="start"||i=="center"&&t<0?e.top-s:e.bottom-v+s)-f.top}if(n=="nearest"?e.left<f.left+o?(g=e.left-(f.left+o),t>0&&e.right>f.right+g&&(g=e.right-f.right+o)):e.right>f.right-o&&(g=e.right-f.right+o,t<0&&e.left<f.left+g&&(g=e.left-(f.left+o))):g=(n=="center"?e.left+(e.right-e.left)/2-(f.right-f.left)/2:n=="start"==l?e.left-o:e.right-(f.right-f.left)+o)-f.left,g||b)if(m)u.scrollBy(g,b);else{let C=0,v=0;if(b){let M=h.scrollTop;h.scrollTop+=b/p,v=(h.scrollTop-M)*p}if(g){let M=h.scrollLeft;h.scrollLeft+=g/d,C=(h.scrollLeft-M)*d}e={left:e.left-C,top:e.top-v,right:e.right-C,bottom:e.bottom-v},C&&Math.abs(C-g)<1&&(n="nearest"),v&&Math.abs(v-b)<1&&(i="nearest")}if(m)break;(e.top<f.top||e.bottom>f.bottom||e.left<f.left||e.right>f.right)&&(e={left:Math.max(e.left,f.left),right:Math.min(e.right,f.right),top:Math.max(e.top,f.top),bottom:Math.min(e.bottom,f.bottom)}),h=h.assignedSlot||h.parentNode}else if(h.nodeType==11)h=h.host;else break}function rr(r,e=!0){let t=r.ownerDocument,n=null,i=null;for(let o=r.parentNode;o&&!(o==t.body||(!e||n)&&i);)if(o.nodeType==1)!i&&o.scrollHeight>o.clientHeight&&(i=o),e&&!n&&o.scrollWidth>o.clientWidth&&(n=o),o=o.assignedSlot||o.parentNode;else if(o.nodeType==11)o=o.host;else break;return{x:n,y:i}}var tr=class{constructor(){this.anchorNode=null;this.anchorOffset=0;this.focusNode=null;this.focusOffset=0}eq(e){return this.anchorNode==e.anchorNode&&this.anchorOffset==e.anchorOffset&&this.focusNode==e.focusNode&&this.focusOffset==e.focusOffset}setRange(e){let{anchorNode:t,focusNode:n}=e;this.set(t,Math.min(e.anchorOffset,t?ae(t):0),n,Math.min(e.focusOffset,n?ae(n):0))}set(e,t,n,i){this.anchorNode=e,this.anchorOffset=t,this.focusNode=n,this.focusOffset=i}},gt=null;S.safari&&S.safari_version>=26&&(gt=!1);function ir(r){if(r.setActive)return r.setActive();if(gt)return r.focus(gt);let e=[];for(let t=r;t&&(e.push(t,t.scrollTop,t.scrollLeft),t!=t.ownerDocument);t=t.parentNode);if(r.focus(gt==null?{get preventScroll(){return gt={preventScroll:!0},!0}}:void 0),!gt){gt=!1;for(let t=0;t<e.length;){let n=e[t++],i=e[t++],o=e[t++];n.scrollTop!=i&&(n.scrollTop=i),n.scrollLeft!=o&&(n.scrollLeft=o)}}}var Ms;function Xe(r,e,t=e){let n=Ms||(Ms=document.createRange());return n.setEnd(r,t),n.setStart(r,e),n}function He(r,e,t,n){let i={key:e,code:e,keyCode:t,which:t,cancelable:!0};n&&({altKey:i.altKey,ctrlKey:i.ctrlKey,shiftKey:i.shiftKey,metaKey:i.metaKey}=n);let o=new KeyboardEvent("keydown",i);o.synthetic=!0,r.dispatchEvent(o);let s=new KeyboardEvent("keyup",i);return s.synthetic=!0,r.dispatchEvent(s),o.defaultPrevented||s.defaultPrevented}function As(r){for(;r;){if(r&&(r.nodeType==9||r.nodeType==11&&r.host))return r;r=r.assignedSlot||r.parentNode}return null}function Ds(r,e){let t=e.focusNode,n=e.focusOffset;if(!t||e.anchorNode!=t||e.anchorOffset!=n)return!1;for(n=Math.min(n,ae(t));;)if(n){if(t.nodeType!=1)return!1;let i=t.childNodes[n-1];i.contentEditable=="false"?n--:(t=i,n=ae(t))}else{if(t==r)return!0;n=Ve(t),t=t.parentNode}}function or(r){return r instanceof Window?r.pageYOffset>Math.max(0,r.document.documentElement.scrollHeight-r.innerHeight-4):r.scrollTop>Math.max(1,r.scrollHeight-r.clientHeight-4)}function Vi(r,e){for(let t=r,n=e;;){if(t.nodeType==3&&n>0)return{node:t,offset:n};if(t.nodeType==1&&n>0){if(t.contentEditable=="false")return null;t=t.childNodes[n-1],n=ae(t)}else if(t.parentNode&&!un(t))n=Ve(t),t=t.parentNode;else return null}}function Hi(r,e){for(let t=r,n=e;;){if(t.nodeType==3&&n<t.nodeValue.length)return{node:t,offset:n};if(t.nodeType==1&&n<t.childNodes.length){if(t.contentEditable=="false")return null;t=t.childNodes[n],n=0}else if(t.parentNode&&!un(t))n=Ve(t)+1,t=t.parentNode;else return null}}var ue=class r{constructor(e,t,n=!0){this.node=e;this.offset=t;this.precise=n}static before(e,t){return new r(e.parentNode,Ve(e),t)}static after(e,t){return new r(e.parentNode,Ve(e)+1,t)}};var yt=0,Ki=1;function Bs(r){let e=[];for(let t=0;t<r.length;t++)e.push(1<<+r[t]);return e}var ja=Bs("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008"),Ja=Bs("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333"),Fi=Object.create(null),Fe=[];for(let r of["()","[]","{}"]){let e=r.charCodeAt(0),t=r.charCodeAt(1);Fi[e]=t,Fi[t]=-e}function Rs(r){return r<=247?ja[r]:1424<=r&&r<=1524?2:1536<=r&&r<=1785?Ja[r-1536]:1774<=r&&r<=2220?4:8192<=r&&r<=8204?256:64336<=r&&r<=65023?4:1}var $a=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/,te=class{constructor(e,t,n){this.from=e;this.to=t;this.level=n}get dir(){return this.level%2?Ki:yt}side(e,t){return this.dir==t==e?this.to:this.from}forward(e,t){return e==(this.dir==t)}static find(e,t,n,i){let o=-1;for(let s=0;s<e.length;s++){let l=e[s];if(l.from<=t&&l.to>=t){if(l.level==n)return s;(o<0||(i!=0?i<0?l.from<t:l.to>t:e[o].level>l.level))&&(o=s)}}if(o<0)throw new RangeError("Index out of range");return o}};function Ui(r,e){if(r.length!=e.length)return!1;for(let t=0;t<r.length;t++){let n=r[t],i=e[t];if(n.from!=i.from||n.to!=i.to||n.direction!=i.direction||!Ui(n.inner,i.inner))return!1}return!0}var P=[];function Ya(r,e,t,n,i){for(let o=0;o<=n.length;o++){let s=o?n[o-1].to:e,l=o<n.length?n[o].from:t,a=o?256:i;for(let u=s,h=a,c=a;u<l;u++){let f=Rs(r.charCodeAt(u));f==512?f=h:f==8&&c==4&&(f=16),P[u]=f==4?2:f,f&7&&(c=f),h=f}for(let u=s,h=a,c=a;u<l;u++){let f=P[u];if(f==128)u<l-1&&h==P[u+1]&&h&24?f=P[u]=h:P[u]=256;else if(f==64){let m=u+1;for(;m<l&&P[m]==64;)m++;let d=u&&h==8||m<t&&P[m]==8?c==1?1:8:256;for(let p=u;p<m;p++)P[p]=d;u=m-1}else f==8&&c==1&&(P[u]=1);h=f,f&7&&(c=f)}}}function Xa(r,e,t,n,i){let o=i==1?2:1;for(let s=0,l=0,a=0;s<=n.length;s++){let u=s?n[s-1].to:e,h=s<n.length?n[s].from:t;for(let c=u,f,m,d;c<h;c++)if(m=Fi[f=r.charCodeAt(c)])if(m<0){for(let p=l-3;p>=0;p-=3)if(Fe[p+1]==-m){let g=Fe[p+2],b=g&2?i:g&4?g&1?o:i:0;b&&(P[c]=P[Fe[p]]=b),l=p;break}}else{if(Fe.length==189)break;Fe[l++]=c,Fe[l++]=f,Fe[l++]=a}else if((d=P[c])==2||d==1){let p=d==i;a=p?0:1;for(let g=l-3;g>=0;g-=3){let b=Fe[g+2];if(b&2)break;if(p)Fe[g+2]|=2;else{if(b&4)break;Fe[g+2]|=4}}}}}function Qa(r,e,t,n){for(let i=0,o=n;i<=t.length;i++){let s=i?t[i-1].to:r,l=i<t.length?t[i].from:e;for(let a=s;a<l;){let u=P[a];if(u==256){let h=a+1;for(;;)if(h==l){if(i==t.length)break;h=t[i++].to,l=i<t.length?t[i].from:e}else if(P[h]==256)h++;else break;let c=o==1,f=(h<e?P[h]:n)==1,m=c==f?c?1:2:n;for(let d=h,p=i,g=p?t[p-1].to:r;d>a;)d==g&&(d=t[--p].from,g=p?t[p-1].to:r),P[--d]=m;a=h}else o=u,a++}}}function Wi(r,e,t,n,i,o,s){let l=n%2?2:1;if(n%2==i%2)for(let a=e,u=0;a<t;){let h=!0,c=!1;if(u==o.length||a<o[u].from){let p=P[a];p!=l&&(h=!1,c=p==16)}let f=!h&&l==1?[]:null,m=h?n:n+1,d=a;e:for(;;)if(u<o.length&&d==o[u].from){if(c)break e;let p=o[u];if(!h)for(let g=p.to,b=u+1;;){if(g==t)break e;if(b<o.length&&o[b].from==g)g=o[b++].to;else{if(P[g]==l)break e;break}}if(u++,f)f.push(p);else{p.from>a&&s.push(new te(a,p.from,m));let g=p.direction==yt!=!(m%2);zi(r,g?n+1:n,i,p.inner,p.from,p.to,s),a=p.to}d=p.to}else{if(d==t||(h?P[d]!=l:P[d]==l))break;d++}f?Wi(r,a,d,n+1,i,f,s):a<d&&s.push(new te(a,d,m)),a=d}else for(let a=t,u=o.length;a>e;){let h=!0,c=!1;if(!u||a>o[u-1].to){let p=P[a-1];p!=l&&(h=!1,c=p==16)}let f=!h&&l==1?[]:null,m=h?n:n+1,d=a;e:for(;;)if(u&&d==o[u-1].to){if(c)break e;let p=o[--u];if(!h)for(let g=p.from,b=u;;){if(g==e)break e;if(b&&o[b-1].to==g)g=o[--b].from;else{if(P[g-1]==l)break e;break}}if(f)f.push(p);else{p.to<a&&s.push(new te(p.to,a,m));let g=p.direction==yt!=!(m%2);zi(r,g?n+1:n,i,p.inner,p.from,p.to,s),a=p.from}d=p.from}else{if(d==e||(h?P[d-1]!=l:P[d-1]==l))break;d--}f?Wi(r,d,a,n+1,i,f,s):d<a&&s.push(new te(d,a,m)),a=d}}function zi(r,e,t,n,i,o,s){let l=e%2?2:1;Ya(r,i,o,n,l),Xa(r,i,o,n,l),Qa(i,o,n,l),Wi(r,i,o,e,t,n,s)}function Os(r,e,t){if(!r)return[new te(0,0,e==Ki?1:0)];if(e==yt&&!t.length&&!$a.test(r))return qi(r.length);if(t.length)for(;r.length>P.length;)P[P.length]=256;let n=[],i=e==yt?0:1;return zi(r,i,i,t,0,r.length,n),n}function qi(r){return[new te(0,r,0)]}var Gi="";function Ls(r,e,t,n,i){let o=n.head-r.from,s=te.find(e,o,n.bidiLevel??-1,n.assoc),l=e[s],a=l.side(i,t);if(o==a){let c=s+=i?1:-1;if(c<0||c>=e.length)return null;l=e[s=c],o=l.side(!i,t),a=l.side(i,t)}let u=z(r.text,o,l.forward(i,t));(u<l.from||u>l.to)&&(u=a),Gi=r.text.slice(Math.min(o,u),Math.max(o,u));let h=s==(i?e.length-1:0)?null:e[s+(i?1:-1)];return h&&u==a&&h.level+(i?0:1)<l.level?y.cursor(h.side(!i,t)+r.from,h.forward(i,t)?1:-1,h.level):y.cursor(u+r.from,l.forward(i,t)?-1:1,l.level)}function Is(r,e,t){for(let n=e;n<t;n++){let i=Rs(r.charCodeAt(n));if(i==1)return yt;if(i==2||i==4)return Ki}return yt}var sr=T.define(),lr=T.define(),ar=T.define(),ji=T.define(),ur=T.define(),hr=T.define(),cr=T.define(),hn=T.define(),cn=T.define(),Ji=T.define({combine:r=>r.some(e=>e)}),fr=T.define({combine:r=>r.some(e=>e)}),dr=T.define(),Wt=class r{constructor(e,t,n,i,o,s=!1){this.range=e;this.y=t;this.x=n;this.yMargin=i;this.xMargin=o;this.isSnapshot=s}map(e){return e.empty?this:new r(this.range.map(e),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}clip(e){return this.range.to<=e.doc.length?this:new r(y.cursor(e.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}},fn=W.define({map:(r,e)=>r.map(e)}),mr=W.define();function _(r,e,t){let n=r.facet(ji);n.length?n[0](e):window.onerror&&window.onerror(String(e),t,void 0,void 0,e)||(t?console.error(t+":",e):console.error(e))}var ce=T.define({combine:r=>r.length?r[0]:!0}),Za=0,xt=T.define({combine(r){return r.filter((e,t)=>{for(let n=0;n<t;n++)if(r[n].plugin==e.plugin)return!1;return!0})}}),ge=class r{constructor(e,t,n,i,o){this.id=e;this.create=t;this.domEventHandlers=n;this.domEventObservers=i;this.baseExtensions=o(this),this.extension=this.baseExtensions.concat(xt.of({plugin:this,arg:void 0}))}of(e){return this.baseExtensions.concat(xt.of({plugin:this,arg:e}))}static define(e,t){let{eventHandlers:n,eventObservers:i,provide:o,decorations:s}=t||{};return new r(Za++,e,n,i,l=>{let a=[];return s&&a.push(St.of(u=>{let h=u.plugin(l);return h?s(h):V.none})),o&&a.push(o(l)),a})}static fromClass(e,t){return r.define((n,i)=>new e(n,i),t)}},zt=class{constructor(e){this.spec=e;this.mustUpdate=null;this.value=null}get plugin(){return this.spec&&this.spec.plugin}update(e){if(this.value){if(this.mustUpdate){let t=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(t)}catch(n){if(_(t.state,n,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.plugin.create(e,this.spec.arg)}catch(t){_(e.state,t,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(e){if(this.value?.destroy)try{this.value.destroy()}catch(t){_(e.state,t,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}},$i=T.define(),dn=T.define(),St=T.define(),pr=T.define(),Ut=T.define(),ze=T.define(),Yi=T.define();function Xi(r,e){let t=r.state.facet(Yi);if(!t.length)return t;let n=t.map(o=>o instanceof Function?o(r):o),i=[];return N.spans(n,e.from,e.to,{point(){},span(o,s,l,a){let u=o-e.from,h=s-e.from,c=i;for(let f=l.length-1;f>=0;f--,a--){let m=l[f].spec.bidiIsolate,d;if(m==null&&(m=Is(e.text,u,h)),a>0&&c.length&&(d=c[c.length-1]).to==u&&d.direction==m)d.to=h,c=d.inner;else{let p={from:u,to:h,direction:m,inner:[]};c.push(p),c=p.inner}}}}),i}var Qi=T.define();function gr(r){let e=0,t=0,n=0,i=0;for(let o of r.state.facet(Qi)){let s=o(r);s&&(s.left!=null&&(e=Math.max(e,s.left)),s.right!=null&&(t=Math.max(t,s.right)),s.top!=null&&(n=Math.max(n,s.top)),s.bottom!=null&&(i=Math.max(i,s.bottom)))}return{left:e,right:t,top:n,bottom:i}}var qt=T.define();var he=class r{constructor(e,t,n,i){this.fromA=e;this.toA=t;this.fromB=n;this.toB=i}join(e){return new r(Math.min(this.fromA,e.fromA),Math.max(this.toA,e.toA),Math.min(this.fromB,e.fromB),Math.max(this.toB,e.toB))}addToSet(e){let t=e.length,n=this;for(;t>0;t--){let i=e[t-1];if(!(i.fromA>n.toA)){if(i.toA<n.fromA)break;n=n.join(i),e.splice(t-1,1)}}return e.splice(t,0,n),e}static extendWithRanges(e,t){if(t.length==0)return e;let n=[];for(let i=0,o=0,s=0;;){let l=i<e.length?e[i].fromB:1e9,a=o<t.length?t[o]:1e9,u=Math.min(l,a);if(u==1e9)break;let h=u+s,c=u,f=h;for(;;)if(o<t.length&&t[o]<=c){let m=t[o+1];o+=2,c=Math.max(c,m);for(let d=i;d<e.length&&e[d].fromB<=c;d++)s=e[d].toA-e[d].toB;f=Math.max(f,m+s)}else if(i<e.length&&e[i].fromB<=c){let m=e[i++];c=Math.max(c,m.toB),f=Math.max(f,m.toA),s=m.toA-m.toB}else break;n.push(new r(h,f,u,c))}return n}},Kt=class r{constructor(e,t,n){this.view=e;this.state=t;this.transactions=n;this.flags=0;this.startState=e.state,this.changes=G.empty(this.startState.doc.length);for(let o of n)this.changes=this.changes.compose(o.changes);let i=[];this.changes.iterChangedRanges((o,s,l,a)=>i.push(new he(o,s,l,a))),this.changedRanges=i}static create(e,t,n){return new r(e,t,n)}get viewportChanged(){return(this.flags&4)>0}get viewportMoved(){return(this.flags&8)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&18)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(e=>e.selection)}get empty(){return this.flags==0&&this.transactions.length==0}};var _a=[],O=class{constructor(e,t,n=0){this.dom=e;this.length=t;this.flags=n;this.parent=null;e.cmTile=this}get breakAfter(){return this.flags&1}get children(){return _a}isWidget(){return!1}get isHidden(){return!1}isComposite(){return!1}isLine(){return!1}isText(){return!1}isBlock(){return!1}get domAttrs(){return null}sync(e){if(this.flags|=2,this.flags&4){this.flags&=-5;let t=this.domAttrs;t&&ws(this.dom,t)}}toString(){return this.constructor.name+(this.children.length?`(${this.children})`:"")+(this.breakAfter?"#":"")}destroy(){this.parent=null}setDOM(e){this.dom=e,e.cmTile=this}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(e,t=this.posAtStart){let n=t;for(let i of this.children){if(i==e)return n;n+=i.length+i.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(e){return this.posBefore(e)+e.length}covers(e){return!0}coordsIn(e,t){return null}domPosFor(e,t){let n=Ve(this.dom),i=this.length?e>0:t>0;return new ue(this.parent.dom,n+(i?1:0),e==0||e==this.length)}markDirty(e){this.flags&=-3,e&&(this.flags|=4),this.parent&&this.parent.flags&2&&this.parent.markDirty(!1)}get overrideDOMText(){return null}get root(){for(let e=this;e;e=e.parent)if(e instanceof Qe)return e;return null}static get(e){return e.cmTile}},Gt=class extends O{constructor(t){super(t,0);this._children=[]}isComposite(){return!0}get children(){return this._children}get lastChild(){return this.children.length?this.children[this.children.length-1]:null}append(t){this.children.push(t),t.parent=this}sync(t){if(this.flags&2)return;super.sync(t);let n=this.dom,i=null,o,s=t?.node==n?t:null,l=0;for(let a of this.children){if(a.sync(t),l+=a.length+a.breakAfter,o=i?i.nextSibling:n.firstChild,s&&o!=a.dom&&(s.written=!0),a.dom.parentNode==n)for(;o&&o!=a.dom;)o=Ns(o);else n.insertBefore(a.dom,o);i=a.dom}for(o=i?i.nextSibling:n.firstChild,s&&o&&(s.written=!0);o;)o=Ns(o);this.length=l}};function Ns(r){let e=r.nextSibling;return r.parentNode.removeChild(r),e}var Qe=class extends Gt{constructor(t,n){super(n);this.view=t}owns(t){for(;t;t=t.parent)if(t==this)return!0;return!1}isBlock(){return!0}nearest(t){for(;;){if(!t)return null;let n=O.get(t);if(n&&this.owns(n))return n;t=t.parentNode}}blockTiles(t){for(let n=[],i=this,o=0,s=0;;)if(o==i.children.length){if(!n.length)return;i=i.parent,i.breakAfter&&s++,o=n.pop()}else{let l=i.children[o++];if(l instanceof ve)n.push(o),i=l,o=0;else{let a=s+l.length,u=t(l,s);if(u!==void 0)return u;s=a+l.breakAfter}}}resolveBlock(t,n){let i,o=-1,s,l=-1;if(this.blockTiles((a,u)=>{let h=u+a.length;if(t>=u&&t<=h){if(a.isWidget()&&n>=-1&&n<=1){if(a.flags&32)return!0;a.flags&16&&(i=void 0)}(u<t||t==h&&(n<-1?a.length:a.covers(1)))&&(!i||!a.isWidget()&&i.isWidget())&&(i=a,o=t-u),(h>t||t==u&&(n>1?a.length:a.covers(-1)))&&(!s||!a.isWidget()&&s.isWidget())&&(s=a,l=t-u)}}),!i&&!s)throw new Error("No tile at position "+t);return i&&n<0||!s?{tile:i,offset:o}:{tile:s,offset:l}}},ve=class r extends Gt{constructor(t,n){super(t);this.wrapper=n}isBlock(){return!0}covers(t){return this.children.length?t<0?this.children[0].covers(-1):this.lastChild.covers(1):!1}get domAttrs(){return this.wrapper.attributes}static of(t,n){let i=new r(n||document.createElement(t.tagName),t);return n||(i.flags|=4),i}},Tt=class r extends Gt{constructor(t,n){super(t);this.attrs=n}isLine(){return!0}static start(t,n,i){let o=new r(n||document.createElement("div"),t);return(!n||!i)&&(o.flags|=4),o}get domAttrs(){return this.attrs}resolveInline(t,n,i){let o=null,s=-1,l=null,a=-1;function u(c,f){for(let m=0,d=0;m<c.children.length&&d<=f;m++){let p=c.children[m],g=d+p.length;g>=f&&(p.isComposite()?u(p,f-d):(!l||l.isHidden&&(n>0||i&&tu(l,p)))&&(g>f||p.flags&32)?(l=p,a=f-d):(d<f||p.flags&16&&!p.isHidden)&&(o=p,s=f-d)),d=g}}u(this,t);let h=(n<0?o:l)||o||l;return h?{tile:h,offset:h==o?s:a}:null}coordsIn(t,n){let i=this.resolveInline(t,n,!0);return i?i.tile.coordsIn(Math.max(0,i.offset),n):eu(this)}domIn(t,n){let i=this.resolveInline(t,n);if(i){let{tile:o,offset:s}=i;if(this.dom.contains(o.dom))return o.isText()?new ue(o.dom,Math.min(o.dom.nodeValue.length,s)):o.domPosFor(s,o.flags&16?1:o.flags&32?-1:n);let l=i.tile.parent,a=!1,u;for(let h of l.children){if(a)return new ue(h.dom,0);if(h==i.tile){if(u)return new ue(u.dom,ae(u.dom));a=!0}}}return new ue(this.dom,0)}};function eu(r){let e=r.dom.lastChild;if(!e)return r.dom.getBoundingClientRect();let t=Ht(e);return t[t.length-1]||null}function tu(r,e){let t=r.coordsIn(0,1),n=e.coordsIn(0,1);return t&&n&&n.top<t.bottom}var ee=class r extends Gt{constructor(t,n){super(t);this.mark=n}get domAttrs(){return this.mark.attrs}static of(t,n){let i=new r(n||document.createElement(t.tagName),t);return n||(i.flags|=4),i}},Ze=class r extends O{constructor(t,n){super(t,n.length);this.text=n}sync(t){this.flags&2||(super.sync(t),this.dom.nodeValue!=this.text&&(t&&t.node==this.dom&&(t.written=!0),this.dom.nodeValue=this.text))}isText(){return!0}toString(){return JSON.stringify(this.text)}coordsIn(t,n){let i=this.dom.nodeValue.length;t>i&&(t=i);let o=t,s=t,l=0;t==0&&n<0||t==i&&n>=0?S.chrome||S.gecko||(t?(o--,l=1):s<i&&(s++,l=-1)):n<0?o--:s<i&&s++;let a=Xe(this.dom,o,s).getClientRects();if(!a.length)return null;let u=a[(l?l<0:n>=0)?0:a.length-1];return S.safari&&!l&&u.width==0&&(u=Array.prototype.find.call(a,h=>h.width)||u),l?Ft(u,l<0):u||null}static of(t,n){let i=new r(n||document.createTextNode(t),t);return n||(i.flags|=2),i}},_e=class r extends O{constructor(t,n,i,o){super(t,n,o);this.widget=i}isWidget(){return!0}get isHidden(){return this.widget.isHidden}covers(t){return this.flags&48?!1:(this.flags&(t<0?64:128))>0}coordsIn(t,n){return this.coordsInWidget(t,n,!1)}coordsInWidget(t,n,i){let o=this.widget.coordsAt(this.dom,t,n);if(o)return o;if(i)return Ft(this.dom.getBoundingClientRect(),this.length?t==0:n<=0);{let s=this.dom.getClientRects(),l=null;if(!s.length)return null;let a=this.flags&16?!0:this.flags&32?!1:t>0;for(let u=a?s.length-1:0;l=s[u],!(t>0?u==0:u==s.length-1||l.top<l.bottom);u+=a?-1:1);return Ft(l,!a)}}get overrideDOMText(){if(!this.length)return A.empty;let{root:t}=this;if(!t)return A.empty;let n=this.posAtStart;return t.view.state.doc.slice(n,n+this.length)}destroy(){super.destroy(),this.widget.destroy(this.dom)}static of(t,n,i,o,s){return s||(s=t.toDOM(n),t.editable||(s.contentEditable="false")),new r(s,i,t,o)}},wt=class extends O{constructor(e){let t=document.createElement("img");t.className="cm-widgetBuffer",t.setAttribute("aria-hidden","true"),super(t,0,e)}get isHidden(){return!0}get overrideDOMText(){return A.empty}coordsIn(e){return this.dom.getBoundingClientRect()}},br=class{constructor(e){this.index=0;this.beforeBreak=!1;this.parents=[];this.tile=e}advance(e,t,n){let{tile:i,index:o,beforeBreak:s,parents:l}=this;for(;e||t>0;)if(i.isComposite())if(s){if(!e)break;n&&n.break(),e--,s=!1}else if(o==i.children.length){if(!e&&!l.length)break;n&&n.leave(i),s=!!i.breakAfter,{tile:i,index:o}=l.pop(),o++}else{let a=i.children[o],u=a.breakAfter;(t>0?a.length<=e:a.length<e)&&(!n||n.skip(a,0,a.length)!==!1||!a.isComposite)?(s=!!u,o++,e-=a.length):(l.push({tile:i,index:o}),i=a,o=0,n&&a.isComposite()&&n.enter(a))}else if(o==i.length)s=!!i.breakAfter,{tile:i,index:o}=l.pop(),o++;else if(e){let a=Math.min(e,i.length-o);n&&n.skip(i,o,o+a),e-=a,o+=a}else break;return this.tile=i,this.index=o,this.beforeBreak=s,this}get root(){return this.parents.length?this.parents[0].tile:this.tile}};var Ct=!1;var eo=class{constructor(e,t,n,i){this.from=e;this.to=t;this.wrapper=n;this.rank=i}},to=class{constructor(e,t,n){this.cache=e;this.root=t;this.blockWrappers=n;this.curLine=null;this.lastBlock=null;this.afterWidget=null;this.pos=0;this.wrappers=[];this.wrapperPos=0}addText(e,t,n,i){this.flushBuffer();let o=this.ensureMarks(t,n),s=o.lastChild;if(s&&s.isText()&&!(s.flags&8)&&s.length+e.length<512){this.cache.reused.set(s,2);let l=o.children[o.children.length-1]=new Ze(s.dom,s.text+e);l.parent=o}else o.append(i||Ze.of(e,this.cache.find(Ze)?.dom));this.pos+=e.length,this.afterWidget=null}addComposition(e,t){let n=this.curLine;n.dom!=t.line.dom&&(n.setDOM(this.cache.reused.has(t.line)?Zi(t.line.dom):t.line.dom),this.cache.reused.set(t.line,2));let i=n;for(let l=t.marks.length-1;l>=0;l--){let a=t.marks[l],u=i.lastChild;if(u instanceof ee&&u.mark.eq(a.mark))u.dom!=a.dom&&u.setDOM(Zi(a.dom)),i=u;else{if(this.cache.reused.get(a)){let c=O.get(a.dom);c&&c.setDOM(Zi(a.dom))}let h=ee.of(a.mark,a.dom);i.append(h),i=h}this.cache.reused.set(a,2)}let o=O.get(e.text);o&&this.cache.reused.set(o,2);let s=new Ze(e.text,e.text.nodeValue);s.flags|=8,i.append(s)}addInlineWidget(e,t,n){let i=this.afterWidget&&e.flags&48&&(this.afterWidget.flags&48)==(e.flags&48);i||this.flushBuffer();let o=this.ensureMarks(t,n);!i&&!(e.flags&16)&&o.append(this.getBuffer(1)),o.append(e),this.pos+=e.length,this.afterWidget=e}addMark(e,t,n){this.flushBuffer(),this.ensureMarks(t,n).append(e),this.pos+=e.length,this.afterWidget=null}addBlockWidget(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}continueWidget(e){let t=this.afterWidget||this.lastBlock;t.length+=e,this.pos+=e}addLineStart(e,t){e||(e=Vs);let n=Tt.start(e,t||this.cache.find(Tt)?.dom,!!t);this.getBlockPos().append(this.lastBlock=this.curLine=n)}addLine(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}addBreak(){this.lastBlock.flags|=1,this.endLine(),this.pos++}addLineStartIfNotCovered(e){this.blockPosCovered()||this.addLineStart(e)}ensureLine(e){this.curLine||this.addLineStart(e)}ensureMarks(e,t){let n=this.curLine;for(let i=e.length-1;i>=0;i--){let o=e[i],s;if(t>0&&(s=n.lastChild)&&s instanceof ee&&s.mark.eq(o))n=s,t--;else{let l=ee.of(o,this.cache.find(ee,a=>a.mark.eq(o))?.dom);n.append(l),n=l,t=0}}return n}endLine(){if(this.curLine){this.flushBuffer();let e=this.curLine.lastChild;(!e||!Ps(this.curLine,!1)||e.dom.nodeName!="BR"&&e.isWidget()&&!(S.ios&&Ps(this.curLine,!0)))&&this.curLine.append(this.cache.findWidget(_i,0,32)||new _e(_i.toDOM(),0,_i,32)),this.curLine=this.afterWidget=null}}updateBlockWrappers(){this.wrapperPos>this.pos+1e4&&(this.blockWrappers.goto(this.pos),this.wrappers.length=0);for(let e=this.wrappers.length-1;e>=0;e--)this.wrappers[e].to<this.pos&&this.wrappers.splice(e,1);for(let e=this.blockWrappers;e.value&&e.from<=this.pos;e.next())if(e.to>=this.pos){let t=new eo(e.from,e.to,e.value,e.rank),n=this.wrappers.length;for(;n>0&&(this.wrappers[n-1].rank-t.rank||this.wrappers[n-1].to-t.to)<0;)n--;this.wrappers.splice(n,0,t)}this.wrapperPos=this.pos}getBlockPos(){this.updateBlockWrappers();let e=this.root;for(let t of this.wrappers){let n=e.lastChild;if(t.from<this.pos&&n instanceof ve&&n.wrapper.eq(t.wrapper))e=n;else{let i=ve.of(t.wrapper,this.cache.find(ve,o=>o.wrapper.eq(t.wrapper))?.dom);e.append(i),e=i}}return e}blockPosCovered(){let e=this.lastBlock;return e!=null&&!e.breakAfter&&(!e.isWidget()||(e.flags&160)>0)}getBuffer(e){let t=2|(e<0?16:32),n=this.cache.find(wt,void 0,1);return n&&(n.flags=t),n||new wt(t)}flushBuffer(){this.afterWidget&&!(this.afterWidget.flags&32)&&(this.afterWidget.parent.append(this.getBuffer(-1)),this.afterWidget=null)}},no=class{constructor(e){this.skipCount=0;this.text="";this.textOff=0;this.cursor=e.iter()}skip(e){this.textOff+e<=this.text.length?this.textOff+=e:(this.skipCount+=e-(this.text.length-this.textOff),this.text="",this.textOff=0)}next(e){if(this.textOff==this.text.length){let{value:i,lineBreak:o,done:s}=this.cursor.next(this.skipCount);if(this.skipCount=0,s)throw new Error("Ran out of text content when drawing inline views");this.text=i;let l=this.textOff=Math.min(e,i.length);return o?null:i.slice(0,l)}let t=Math.min(this.text.length,this.textOff+e),n=this.text.slice(this.textOff,t);return this.textOff=t,n}},yr=[_e,Tt,Ze,ee,wt,ve,Qe];for(let r=0;r<yr.length;r++)yr[r].bucket=r;var ro=class{constructor(e){this.view=e;this.buckets=yr.map(()=>[]);this.index=yr.map(()=>0);this.reused=new Map}add(e){let t=e.constructor.bucket,n=this.buckets[t];n.length<6?n.push(e):n[this.index[t]=(this.index[t]+1)%6]=e}find(e,t,n=2){let i=e.bucket,o=this.buckets[i],s=this.index[i];for(let l=o.length-1;l>=0;l--){let a=(l+s)%o.length,u=o[a];if((!t||t(u))&&!this.reused.has(u))return o.splice(a,1),a<s&&this.index[i]--,this.reused.set(u,n),u}return null}findWidget(e,t,n){let i=this.buckets[0];if(i.length)for(let o=0,s=0;;o++){if(o==i.length){if(s)return null;s=1,o=0}let l=i[o];if(!this.reused.has(l)&&(s==0?l.widget.compare(e):l.widget.constructor==e.constructor&&e.updateDOM(l.dom,this.view,l.widget)))return i.splice(o,1),o<this.index[0]&&this.index[0]--,l.widget==e&&l.length==t&&(l.flags&497)==n?(this.reused.set(l,1),l):(this.reused.set(l,2),new _e(l.dom,t,e,l.flags&-498|n))}}reuse(e){return this.reused.set(e,1),e}maybeReuse(e,t=2){if(!this.reused.has(e))return this.reused.set(e,t),e.dom}clear(){for(let e=0;e<this.buckets.length;e++)this.buckets[e].length=this.index[e]=0}},xr=class{constructor(e,t,n,i,o){this.view=e;this.decorations=i;this.disallowBlockEffectsFor=o;this.openWidget=!1;this.openMarks=0;this.cache=new ro(e),this.text=new no(e.state.doc),this.builder=new to(this.cache,new Qe(e,e.contentDOM),N.iter(n)),this.cache.reused.set(t,2),this.old=new br(t),this.reuseWalker={skip:(s,l,a)=>{if(this.cache.add(s),s.isComposite())return!1},enter:s=>this.cache.add(s),leave:()=>{},break:()=>{}}}run(e,t){Ct&&console.log("Build with changes",JSON.stringify(e)),Ct&&t&&console.log("Composition=",JSON.stringify(t.range),t.text.nodeValue),Ct&&console.log("<<< "+this.old.tile);let n=t&&this.getCompositionContext(t.text);for(let i=0,o=0,s=0;;){let l=s<e.length?e[s++]:null,a=l?l.fromA:this.old.root.length;if(a>i){Ct&&console.log("Preserve",i,"to",a);let u=a-i;this.preserve(u,!s,!l),i=a,o+=u}if(!l)break;t&&l.fromA<=t.range.fromA&&l.toA>=t.range.toA?(Ct&&console.log("Emit composition",o,"to",l.toB,"over",i,"to",l.toA),this.forward(l.fromA,t.range.fromA,t.range.fromA<t.range.toA?1:-1),this.emit(o,t.range.fromB),this.cache.clear(),this.builder.addComposition(t,n),this.text.skip(t.range.toB-t.range.fromB),this.forward(t.range.fromA,l.toA),this.emit(t.range.toB,l.toB)):(Ct&&console.log("Emit",o,"to",l.toB,"over",i,"to",l.toA),this.forward(l.fromA,l.toA),this.emit(o,l.toB)),o=l.toB,i=l.toA}return Ct&&console.log(">>> "+this.builder.root),this.builder.curLine&&this.builder.endLine(),this.builder.root}preserve(e,t,n){let i=ou(this.old),o=this.openMarks;this.old.advance(e,n?1:-1,{skip:(s,l,a)=>{if(s.isWidget())if(this.openWidget)this.builder.continueWidget(a-l);else{let u=a>0||l<s.length?_e.of(s.widget,this.view,a-l,s.flags&496,this.cache.maybeReuse(s)):this.cache.reuse(s);u.flags&256?(u.flags&=-2,this.builder.addBlockWidget(u)):(this.builder.ensureLine(null),this.builder.addInlineWidget(u,i,o),o=i.length)}else if(s.isText())this.builder.ensureLine(null),!l&&a==s.length&&!this.cache.reused.has(s)?this.builder.addText(s.text,i,o,this.cache.reuse(s)):(this.cache.add(s),this.builder.addText(s.text.slice(l,a),i,o)),o=i.length;else if(s.isLine())s.flags&=-2,this.cache.reused.set(s,1),this.builder.addLine(s);else if(s instanceof wt)this.cache.add(s);else if(s instanceof ee)this.builder.ensureLine(null),this.builder.addMark(s,i,o),this.cache.reused.set(s,1),o=i.length;else return!1;this.openWidget=!1},enter:s=>{s.isLine()?this.builder.addLineStart(s.attrs,this.cache.maybeReuse(s)):(this.cache.add(s),s instanceof ee&&i.unshift(s.mark)),this.openWidget=!1},leave:s=>{s.isLine()?i.length&&(i.length=o=0):s instanceof ee&&(i.shift(),o=Math.min(o,i.length))},break:()=>{this.builder.addBreak(),this.openWidget=!1}}),this.text.skip(e)}emit(e,t){let n=null,i=this.builder,o=0,s=N.spans(this.decorations,e,t,{point:(l,a,u,h,c,f)=>{if(u instanceof We){if(this.disallowBlockEffectsFor[f]){if(u.block)throw new RangeError("Block decorations may not be specified via plugins");if(a>this.view.state.doc.lineAt(l).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}if(o=h.length,c>h.length)i.continueWidget(a-l);else{let m=u.widget||(u.block?Sr.block:Sr.inline),d=ru(u),p=this.cache.findWidget(m,a-l,d)||_e.of(m,this.view,a-l,d);u.block?(u.startSide>0&&i.addLineStartIfNotCovered(n),i.addBlockWidget(p)):(i.ensureLine(n),i.addInlineWidget(p,h,c))}n=null}else n=iu(n,u);a>l&&this.text.skip(a-l)},span:(l,a,u,h)=>{for(let c=l;c<a;){let f=this.text.next(Math.min(512,a-c));f==null?(i.addLineStartIfNotCovered(n),i.addBreak(),c++):(i.ensureLine(n),i.addText(f,u,c==l?h:u.length),c+=f.length),n=null}}});i.addLineStartIfNotCovered(n),this.openWidget=s>o,this.openMarks=s}forward(e,t,n=1){t-e<=10?this.old.advance(t-e,n,this.reuseWalker):(this.old.advance(5,-1,this.reuseWalker),this.old.advance(t-e-10,-1),this.old.advance(5,n,this.reuseWalker))}getCompositionContext(e){let t=[],n=null;for(let i=e.parentNode;;i=i.parentNode){let o=O.get(i);if(i==this.view.contentDOM)break;o instanceof ee?t.push(o):o?.isLine()?n=o:o instanceof ve||(i.nodeName=="DIV"&&!n&&i!=this.view.contentDOM?n=new Tt(i,Vs):n||t.push(ee.of(new Vt({tagName:i.nodeName.toLowerCase(),attributes:Cs(i)}),i)))}return{line:n,marks:t}}};function Ps(r,e){let t=n=>{for(let i of n.children)if((e?i.isText():i.length)||t(i))return!0;return!1};return t(r)}function ru(r){let e=r.isReplace?(r.startSide<0?64:0)|(r.endSide>0?128:0):r.startSide>0?32:16;return r.block&&(e|=256),e}var Vs={class:"cm-line"};function iu(r,e){let t=e.spec.attributes,n=e.spec.class;return!t&&!n||(r||(r={class:"cm-line"}),t&&Pt(t,r),n&&(r.class+=" "+n)),r}function ou(r){let e=[];for(let t=r.parents.length;t>1;t--){let n=t==r.parents.length?r.tile:r.parents[t].tile;n instanceof ee&&e.push(n.mark)}return e}function Zi(r){let e=O.get(r);return e&&e.setDOM(r.cloneNode()),r}var Sr=class r extends ke{constructor(t){super();this.tag=t}eq(t){return t.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(t){return t.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}static{this.inline=new r("span")}static{this.block=new r("div")}},_i=new class extends ke{toDOM(){return document.createElement("br")}get isHidden(){return!0}get editable(){return!0}};var pn=class{constructor(e){this.view=e;this.decorations=[];this.blockWrappers=[];this.dynamicDecorationMap=[!1];this.domChanged=null;this.hasComposition=null;this.editContextFormatting=V.none;this.lastCompositionAfterCursor=!1;this.minWidth=0;this.minWidthFrom=0;this.minWidthTo=0;this.impreciseAnchor=null;this.impreciseHead=null;this.forceSelection=!1;this.lastUpdate=Date.now();this.updateDeco(),this.tile=new Qe(e,e.contentDOM),this.updateInner([new he(0,0,0,e.state.doc.length)],null)}update(e){let t=e.changedRanges;this.minWidth>0&&t.length&&(t.every(({fromA:u,toA:h})=>h<this.minWidthFrom||u>this.minWidthTo)?(this.minWidthFrom=e.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=e.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0),this.updateEditContextFormatting(e);let n=-1;this.view.inputState.composing>=0&&!this.view.observer.editContext&&(this.domChanged?.newSel?n=this.domChanged.newSel.head:!fu(e.changes,this.hasComposition)&&!e.selectionSet&&(n=e.state.selection.main.head));let i=n>-1?lu(this.view,e.changes,n):null;if(this.domChanged=null,this.hasComposition){let{from:u,to:h}=this.hasComposition;t=new he(u,h,e.changes.mapPos(u,-1),e.changes.mapPos(h,1)).addToSet(t.slice())}this.hasComposition=i?{from:i.range.fromB,to:i.range.toB}:null,(S.ie||S.chrome)&&!i&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let o=this.decorations,s=this.blockWrappers;this.updateDeco();let l=uu(o,this.decorations,e.changes);l.length&&(t=he.extendWithRanges(t,l));let a=hu(s,this.blockWrappers,e.changes);return a.length&&(t=he.extendWithRanges(t,a)),i&&!t.some(u=>u.fromA<=i.range.fromA&&u.toA>=i.range.toA)&&(t=i.range.addToSet(t.slice())),this.tile.flags&2&&t.length==0?!1:(this.updateInner(t,i),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,t){this.view.viewState.mustMeasureContent=!0;let{observer:n}=this.view;n.ignore(()=>{if(t||e.length){let s=this.tile,l=new xr(this.view,s,this.blockWrappers,this.decorations,this.dynamicDecorationMap);t&&O.get(t.text)&&l.cache.reused.set(O.get(t.text),2),this.tile=l.run(e,t),io(s,l.cache.reused)}this.tile.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.tile.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let o=S.chrome||S.ios?{node:n.selectionRange.focusNode,written:!1}:void 0;this.tile.sync(o),o&&(o.written||n.selectionRange.focusNode!=o.node||!this.tile.dom.contains(o.node))&&(this.forceSelection=!0),this.tile.dom.style.height=""});let i=[];if(this.view.viewport.from||this.view.viewport.to<this.view.state.doc.length)for(let o of this.tile.children)o.isWidget()&&o.widget instanceof mn&&i.push(o.dom);n.updateGaps(i)}updateEditContextFormatting(e){this.editContextFormatting=this.editContextFormatting.map(e.changes);for(let t of e.transactions)for(let n of t.effects)n.is(mr)&&(this.editContextFormatting=n.value)}updateSelection(e=!1,t=!1){(e||!this.view.observer.selectionRange.focusNode)&&this.view.observer.readSelectionRange();let{dom:n}=this.tile,i=this.view.root.activeElement,o=i==n,s=!o&&!(this.view.state.facet(ce)||n.tabIndex>-1)&&Ye(n,this.view.observer.selectionRange)&&!(i&&n.contains(i));if(!(o||t||s))return;let l=this.forceSelection;this.forceSelection=!1;let a=this.view.state.selection.main,u,h;if(a.empty?h=u=this.inlineDOMNearPos(a.anchor,a.assoc||1):(h=this.inlineDOMNearPos(a.head,a.head==a.from?1:-1),u=this.inlineDOMNearPos(a.anchor,a.anchor==a.from?1:-1)),S.gecko&&a.empty&&!this.hasComposition&&su(u)){let f=document.createTextNode("");this.view.observer.ignore(()=>u.node.insertBefore(f,u.node.childNodes[u.offset]||null)),u=h=new ue(f,0),l=!0}let c=this.view.observer.selectionRange;(l||!c.focusNode||(!bt(u.node,u.offset,c.anchorNode,c.anchorOffset)||!bt(h.node,h.offset,c.focusNode,c.focusOffset))&&!this.suppressWidgetCursorChange(c,a))&&(this.view.observer.ignore(()=>{S.android&&S.chrome&&n.contains(c.focusNode)&&cu(c.focusNode,n)&&(n.blur(),n.focus({preventScroll:!0}));let f=$e(this.view.root);if(f)if(a.empty){if(S.gecko){let m=au(u.node,u.offset);if(m&&m!=3){let d=(m==1?Vi:Hi)(u.node,u.offset);d&&(u=new ue(d.node,d.offset))}}f.collapse(u.node,u.offset),a.bidiLevel!=null&&f.caretBidiLevel!==void 0&&(f.caretBidiLevel=a.bidiLevel)}else if(f.extend){f.collapse(u.node,u.offset);try{f.extend(h.node,h.offset)}catch{}}else{let m=document.createRange();a.anchor>a.head&&([u,h]=[h,u]),m.setEnd(h.node,h.offset),m.setStart(u.node,u.offset),f.removeAllRanges(),f.addRange(m)}s&&this.view.root.activeElement==n&&(n.blur(),i&&i.focus())}),this.view.observer.setSelectionRange(u,h)),this.impreciseAnchor=u.precise?null:new ue(c.anchorNode,c.anchorOffset),this.impreciseHead=h.precise?null:new ue(c.focusNode,c.focusOffset)}suppressWidgetCursorChange(e,t){return this.hasComposition&&t.empty&&bt(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset)&&this.posFromDOM(e.focusNode,e.focusOffset)==t.head}enforceCursorAssoc(){if(this.hasComposition)return;let{view:e}=this,t=e.state.selection.main,n=$e(e.root),{anchorNode:i,anchorOffset:o}=e.observer.selectionRange;if(!n||!t.empty||!t.assoc||!n.modify)return;let s=this.lineAt(t.head,t.assoc);if(!s)return;let l=s.posAtStart;if(t.head==l||t.head==l+s.length)return;let a=this.coordsAt(t.head,-1),u=this.coordsAt(t.head,1);if(!a||!u||a.bottom>u.top)return;let h=this.domAtPos(t.head+t.assoc,t.assoc);n.collapse(h.node,h.offset),n.modify("move",t.assoc<0?"forward":"backward","lineboundary"),e.observer.readSelectionRange();let c=e.observer.selectionRange;e.docView.posFromDOM(c.anchorNode,c.anchorOffset)!=t.from&&n.collapse(i,o)}posFromDOM(e,t){let n=this.tile.nearest(e);if(!n)return this.tile.dom.compareDocumentPosition(e)&2?0:this.view.state.doc.length;let i=n.posAtStart;if(n.isComposite()){let o;if(e==n.dom)o=n.dom.childNodes[t];else{let s=ae(e)==0?0:t==0?-1:1;for(;;){let l=e.parentNode;if(l==n.dom)break;s==0&&l.firstChild!=l.lastChild&&(e==l.firstChild?s=-1:s=1),e=l}s<0?o=e:o=e.nextSibling}if(o==n.dom.firstChild)return i;for(;o&&!O.get(o);)o=o.nextSibling;if(!o)return i+n.length;for(let s=0,l=i;;s++){let a=n.children[s];if(a.dom==o)return l;l+=a.length+a.breakAfter}}else return n.isText()?e==n.dom?i+t:i+(t?n.length:0):i}domAtPos(e,t){let{tile:n,offset:i}=this.tile.resolveBlock(e,t);return n.isWidget()?n.domPosFor(e,t):n.domIn(i,t)}inlineDOMNearPos(e,t){let n,i=-1,o=!1,s,l=-1,a=!1;return this.tile.blockTiles((u,h)=>{if(u.isWidget()){if(u.flags&32&&h>=e)return!0;u.flags&16&&(o=!0)}else{let c=h+u.length;if(h<=e&&(n=u,i=e-h,o=c<e),c>=e&&!s&&(s=u,l=e-h,a=h>e),h>e&&s)return!0}}),!n&&!s?this.domAtPos(e,t):(o&&s?n=null:a&&n&&(s=null),n&&t<0||!s?n.domIn(i,t):s.domIn(l,t))}coordsAt(e,t){let{tile:n,offset:i}=this.tile.resolveBlock(e,t);return n.isWidget()?n.widget instanceof mn?null:n.coordsInWidget(i,t,!0):n.coordsIn(i,t)}lineAt(e,t){let{tile:n}=this.tile.resolveBlock(e,t);return n.isLine()?n:null}coordsForChar(e){let{tile:t,offset:n}=this.tile.resolveBlock(e,1);if(!t.isLine())return null;function i(o,s){if(o.isComposite())for(let l of o.children){if(l.length>=s){let a=i(l,s);if(a)return a}if(s-=l.length,s<0)break}else if(o.isText()&&s<o.length){let l=z(o.text,s);if(l==s)return null;let a=Xe(o.dom,s,l).getClientRects();for(let u=0;u<a.length;u++){let h=a[u];if(u==a.length-1||h.top<h.bottom&&h.left<h.right)return h}}return null}return i(t,n)}measureVisibleLineHeights(e){let t=[],{from:n,to:i}=e,o=this.view.contentDOM.clientWidth,s=o>Math.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,l=-1,a=this.view.textDirection==0,u=0,h=(c,f,m)=>{for(let d=0;d<c.children.length&&!(f>i);d++){let p=c.children[d],g=f+p.length,b=p.dom.getBoundingClientRect(),{height:C}=b;if(m&&!d&&(u+=b.top-m.top),p instanceof ve)g>n&&h(p,f,b);else if(f>=n&&(u>0&&t.push(-u),t.push(C+u),u=0,s)){let v=p.dom.lastChild,M=v?Ht(v):[];if(M.length){let w=M[M.length-1],x=a?w.right-b.left:b.right-w.left;x>l&&(l=x,this.minWidth=o,this.minWidthFrom=f,this.minWidthTo=g)}}m&&d==c.children.length-1&&(u+=m.bottom-b.bottom),f=g+p.breakAfter}};return h(this.tile,0,null),t}textDirectionAt(e){let{tile:t}=this.tile.resolveBlock(e,1);return getComputedStyle(t.dom).direction=="rtl"?1:0}measureTextSize(){let e=this.tile.blockTiles(s=>{if(s.isLine()&&s.children.length&&s.length<=20){let l=0,a;for(let u of s.children){if(!u.isText()||/[^ -~]/.test(u.text))return;let h=Ht(u.dom);if(h.length!=1)return;l+=h[0].width,a=h[0].height}if(l)return{lineHeight:s.dom.getBoundingClientRect().height,charWidth:l/s.length,textHeight:a}}});if(e)return e;let t=document.createElement("div"),n,i,o;return t.className="cm-line",t.style.width="99999px",t.style.position="absolute",t.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.tile.dom.appendChild(t);let s=Ht(t.firstChild)[0];n=t.getBoundingClientRect().height,i=s&&s.width?s.width/27:7,o=s&&s.height?s.height:n,t.remove()}),{lineHeight:n,charWidth:i,textHeight:o}}computeBlockGapDeco(){let e=[],t=this.view.viewState;for(let n=0,i=0;;i++){let o=i==t.viewports.length?null:t.viewports[i],s=o?o.from-1:this.view.state.doc.length;if(s>n){let l=(t.lineBlockAt(s).bottom-t.lineBlockAt(n).top)/this.view.scaleY;e.push(V.replace({widget:new mn(l),block:!0,inclusive:!0,isBlockGap:!0}).range(n,s))}if(!o)break;n=o.to+1}return V.set(e)}updateDeco(){let e=1,t=this.view.state.facet(St).map(o=>(this.dynamicDecorationMap[e++]=typeof o=="function")?o(this.view):o),n=!1,i=this.view.state.facet(Ut).map((o,s)=>{let l=typeof o=="function";return l&&(n=!0),l?o(this.view):o});for(i.length&&(this.dynamicDecorationMap[e++]=n,t.push(N.join(i))),this.decorations=[this.editContextFormatting,...t,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco];e<this.decorations.length;)this.dynamicDecorationMap[e++]=!1;this.blockWrappers=this.view.state.facet(pr).map(o=>typeof o=="function"?o(this.view):o)}scrollIntoView(e){if(e.isSnapshot){let u=this.view.viewState.lineBlockAt(e.range.head);this.view.scrollDOM.scrollTop=u.top-e.yMargin,this.view.scrollDOM.scrollLeft=e.xMargin;return}for(let u of this.view.state.facet(dr))try{if(u(this.view,e.range,e))return!0}catch(h){_(this.view.state,h,"scroll handler")}let{range:t}=e,n=this.coordsAt(t.head,t.assoc??(t.empty?0:t.head>t.anchor?-1:1)),i;if(!n)return;!t.empty&&(i=this.coordsAt(t.anchor,t.anchor>t.head?-1:1))&&(n={left:Math.min(n.left,i.left),top:Math.min(n.top,i.top),right:Math.max(n.right,i.right),bottom:Math.max(n.bottom,i.bottom)});let o=gr(this.view),s={left:n.left-o.left,top:n.top-o.top,right:n.right+o.right,bottom:n.bottom+o.bottom},{offsetWidth:l,offsetHeight:a}=this.view.scrollDOM;if(Es(this.view.scrollDOM,s,t.head<t.anchor?-1:1,e.x,e.y,Math.max(Math.min(e.xMargin,l),-l),Math.max(Math.min(e.yMargin,a),-a),this.view.textDirection==0),window.visualViewport&&window.innerHeight-window.visualViewport.height>1&&(n.top>window.pageYOffset+window.visualViewport.offsetTop+window.visualViewport.height||n.bottom<window.pageYOffset+window.visualViewport.offsetTop)){let u=this.view.docView.lineAt(t.head,1);u&&u.dom.scrollIntoView({block:"nearest"})}}lineHasWidget(e){let t=n=>n.isWidget()||n.children.some(t);return t(this.tile.resolveBlock(e,1).tile)}destroy(){io(this.tile)}};function io(r,e){let t=e?.get(r);if(t!=1){t==null&&r.destroy();for(let n of r.children)io(n,e)}}function su(r){return r.node.nodeType==1&&r.node.firstChild&&(r.offset==0||r.node.childNodes[r.offset-1].contentEditable=="false")&&(r.offset==r.node.childNodes.length||r.node.childNodes[r.offset].contentEditable=="false")}function lo(r,e){let t=r.observer.selectionRange;if(!t.focusNode)return null;let n=Vi(t.focusNode,t.focusOffset),i=Hi(t.focusNode,t.focusOffset),o=n||i;if(i&&n&&i.node!=n.node){let l=O.get(i.node);if(!l||l.isText()&&l.text!=i.node.nodeValue)o=i;else if(r.docView.lastCompositionAfterCursor){let a=O.get(n.node);!a||a.isText()&&a.text!=n.node.nodeValue||(o=i)}}if(r.docView.lastCompositionAfterCursor=o!=n,!o)return null;let s=e-o.offset;return{from:s,to:s+o.node.nodeValue.length,node:o.node}}function lu(r,e,t){let n=lo(r,t);if(!n)return null;let{node:i,from:o,to:s}=n,l=i.nodeValue;if(/[\n\r]/.test(l)||r.state.doc.sliceString(n.from,n.to)!=l)return null;let a=e.invertedDesc;return{range:new he(a.mapPos(o),a.mapPos(s),o,s),text:i}}function au(r,e){return r.nodeType!=1?0:(e&&r.childNodes[e-1].contentEditable=="false"?1:0)|(e<r.childNodes.length&&r.childNodes[e].contentEditable=="false"?2:0)}var oo=class{constructor(){this.changes=[]}compareRange(e,t){Je(e,t,this.changes)}comparePoint(e,t){Je(e,t,this.changes)}boundChange(e){Je(e,e,this.changes)}};function uu(r,e,t){let n=new oo;return N.compare(r,e,t,n),n.changes}var so=class{constructor(){this.changes=[]}compareRange(e,t){Je(e,t,this.changes)}comparePoint(){}boundChange(e){Je(e,e,this.changes)}};function hu(r,e,t){let n=new so;return N.compare(r,e,t,n),n.changes}function cu(r,e){for(let t=r;t&&t!=e;t=t.assignedSlot||t.parentNode)if(t.nodeType==1&&t.contentEditable=="false")return!0;return!1}function fu(r,e){let t=!1;return e&&r.iterChangedRanges((n,i)=>{n<e.to&&i>e.from&&(t=!0)}),t}var mn=class extends ke{constructor(t){super();this.height=t}toDOM(){let t=document.createElement("div");return t.className="cm-gap",this.updateDOM(t),t}eq(t){return t.height==this.height}updateDOM(t){return t.style.height=this.height+"px",!0}get editable(){return!0}get estimatedHeight(){return this.height}ignoreEvent(){return!1}};function Fs(r,e,t=1){let n=r.charCategorizer(e),i=r.doc.lineAt(e),o=e-i.from;if(i.length==0)return y.cursor(e);o==0?t=1:o==i.length&&(t=-1);let s=o,l=o;t<0?s=z(i.text,o,!1):l=z(i.text,o);let a=n(i.text.slice(s,l));for(;s>0;){let u=z(i.text,s,!1);if(n(i.text.slice(u,s))!=a)break;s=u}for(;l<i.length;){let u=z(i.text,l);if(n(i.text.slice(l,u))!=a)break;l=u}return y.range(s+i.from,l+i.from)}function du(r,e,t,n,i){let o=Math.round((n-e.left)*r.defaultCharacterWidth);if(r.lineWrapping&&t.height>r.defaultLineHeight*1.5){let l=r.viewState.heightOracle.textHeight,a=Math.floor((i-t.top-(r.defaultLineHeight-l)*.5)/l);o+=a*r.viewState.heightOracle.lineLength}let s=r.state.sliceDoc(t.from,t.to);return t.from+Ei(s,o,r.state.tabSize)}function Tr(r,e,t){let n=r.lineBlockAt(e);if(Array.isArray(n.type)){let i;for(let o of n.type){if(o.from>e)break;if(!(o.to<e)){if(o.from<e&&o.to>e)return o;(!i||o.type==0&&(i.type!=o.type||(t<0?o.from<e:o.to>e)))&&(i=o)}}return i||n}return n}function Ws(r,e,t,n){let i=Tr(r,e.head,e.assoc||-1),o=!n||i.type!=0||!(r.lineWrapping||i.widgetLineBreaks)?null:r.coordsAtPos(e.assoc<0&&e.head>i.from?e.head-1:e.head);if(o){let s=r.dom.getBoundingClientRect(),l=r.textDirectionAt(i.from),a=r.posAtCoords({x:t==(l==0)?s.right-1:s.left+1,y:(o.top+o.bottom)/2});if(a!=null)return y.cursor(a,t?-1:1)}return y.cursor(t?i.to:i.from,t?-1:1)}function uo(r,e,t,n){let i=r.state.doc.lineAt(e.head),o=r.bidiSpans(i),s=r.textDirectionAt(i.from);for(let l=e,a=null;;){let u=Ls(i,o,s,l,t),h=Gi;if(!u){if(i.number==(t?r.state.doc.lines:1))return l;h=`
+`,i=r.state.doc.line(i.number+(t?1:-1)),o=r.bidiSpans(i),u=r.visualLineSide(i,!t)}if(a){if(!a(h))return l}else{if(!n)return u;a=n(h)}l=u}}function zs(r,e,t){let n=r.state.charCategorizer(e),i=n(t);return o=>{let s=n(o);return i==1&&(i=s),i==s}}function Ks(r,e,t,n){let i=e.head,o=t?1:-1;if(i==(t?r.state.doc.length:0))return y.cursor(i,e.assoc);let s=e.goalColumn,l,a=r.contentDOM.getBoundingClientRect(),u=r.coordsAtPos(i,e.assoc||((e.empty?t:e.head==e.from)?1:-1)),h=r.documentTop;if(u)s==null&&(s=u.left-a.left),l=o<0?u.top:u.bottom;else{let d=r.viewState.lineBlockAt(i);s==null&&(s=Math.min(a.right-a.left,r.defaultCharacterWidth*(i-d.from))),l=(o<0?d.top:d.bottom)+h}let c=a.left+s,f=r.viewState.heightOracle.textHeight>>1,m=n??f;for(let d=0;;d+=f){let p=l+(m+d)*o,g=kr(r,{x:c,y:p},!1,o);if(t?p>a.bottom:p<a.top)return y.cursor(g.pos,g.assoc);let b=r.coordsAtPos(g.pos,g.assoc),C=b?(b.top+b.bottom)/2:0;if(!b||(t?C>l:C<l))return y.cursor(g.pos,g.assoc,void 0,s)}}function jt(r,e,t){for(;;){let n=0;for(let i of r)i.between(e-1,e+1,(o,s,l)=>{if(e>o&&e<s){let a=n||t||(e-o<s-e?-1:1);e=a<0?o:s,n=a}});if(!n)return e}}function wr(r,e){let t=null;for(let n=0;n<e.ranges.length;n++){let i=e.ranges[n],o=null;if(i.empty){let s=jt(r,i.from,0);s!=i.from&&(o=y.cursor(s,-1))}else{let s=jt(r,i.from,-1),l=jt(r,i.to,1);(s!=i.from||l!=i.to)&&(o=y.range(i.from==i.anchor?s:l,i.from==i.head?s:l))}o&&(t||(t=e.ranges.slice()),t[n]=o)}return t?y.create(t,e.mainIndex):e}function Cr(r,e,t){let n=jt(r.state.facet(ze).map(i=>i(r)),t.from,e.head>t.from?-1:1);return n==t.from?t:y.cursor(n,n<t.from?1:-1)}var be=class{constructor(e,t){this.pos=e;this.assoc=t}};function kr(r,e,t,n){let i=r.contentDOM.getBoundingClientRect(),o=i.top+r.viewState.paddingTop,{x:s,y:l}=e,a=l-o,u;for(;;){if(a<0)return new be(0,1);if(a>r.viewState.docHeight)return new be(r.state.doc.length,-1);if(u=r.elementAtHeight(a),n==null)break;if(u.type==0){if(n<0?u.to<r.viewport.from:u.from>r.viewport.to)break;let f=r.docView.coordsAt(n<0?u.from:u.to,n>0?-1:1);if(f&&(n<0?f.top<=a+o:f.bottom>=a+o))break}let c=r.viewState.heightOracle.textHeight/2;a=n>0?u.bottom+c:u.top-c}if(r.viewport.from>=u.to||r.viewport.to<=u.from){if(t)return null;if(u.type==0){let c=du(r,i,u,s,l);return new be(c,c==u.from?1:-1)}}if(u.type!=0)return a<(u.top+u.bottom)/2?new be(u.from,1):new be(u.to,-1);let h=r.docView.lineAt(u.from,2);return(!h||h.length!=u.length)&&(h=r.docView.lineAt(u.from,-2)),new ao(r,s,l,r.textDirectionAt(u.from)).scanTile(h,u.from)}var ao=class{constructor(e,t,n,i){this.view=e;this.x=t;this.y=n;this.baseDir=i;this.line=null;this.spans=null}bidiSpansAt(e){return(!this.line||this.line.from>e||this.line.to<e)&&(this.line=this.view.state.doc.lineAt(e),this.spans=this.view.bidiSpans(this.line)),this}baseDirAt(e,t){let{line:n,spans:i}=this.bidiSpansAt(e);return i[te.find(i,e-n.from,-1,t)].level==this.baseDir}dirAt(e,t){let{line:n,spans:i}=this.bidiSpansAt(e);return i[te.find(i,e-n.from,-1,t)].dir}bidiIn(e,t){let{spans:n,line:i}=this.bidiSpansAt(e);return n.length>1||n.length&&(n[0].level!=this.baseDir||n[0].to+i.from<t)}scan(e,t){let n=0,i=e.length-1,o=new Set,s=this.bidiIn(e[0],e[i]),l,a,u=-1,h=1e9,c;e:for(;n<i;){let m=i-n,d=n+i>>1;t:if(o.has(d)){let g=n+Math.floor(Math.random()*m);for(let b=0;b<m;b++){if(!o.has(g)){d=g;break t}g++,g==i&&(g=n)}break e}o.add(d);let p=t(d);if(p)for(let g=0;g<p.length;g++){let b=p[g],C=0;if(!(b.width==0&&p.length>1)){if(b.bottom<this.y)(!l||l.bottom<b.bottom)&&(l=b),C=1;else if(b.top>this.y)(!a||a.top>b.top)&&(a=b),C=-1;else{let v=b.left>this.x?this.x-b.left:b.right<this.x?this.x-b.right:0,M=Math.abs(v);M<h&&(u=d,h=M,c=b),v&&(C=v<0==(this.baseDir==0)?-1:1)}C==-1&&(!s||this.baseDirAt(e[d],1))?i=d:C==1&&(!s||this.baseDirAt(e[d+1],-1))&&(n=d+1)}}}if(!c){let m=l&&(!a||this.y-l.bottom<a.top-this.y)?l:a;return this.y=(m.top+m.bottom)/2,this.scan(e,t)}if(h){if(l&&l.bottom>c.top)return this.y=l.bottom-1,this.scan(e,t);if(a&&a.top<c.bottom)return this.y=a.top+1,this.scan(e,t)}let f=(s?this.dirAt(e[u],1):this.baseDir)==0;return{i:u,after:this.x>(c.left+c.right)/2==f}}scanText(e,t){let n=[];for(let o=0;o<e.length;o=z(e.text,o))n.push(t+o);n.push(t+e.length);let i=this.scan(n,o=>{let s=n[o]-t,l=n[o+1]-t;return Xe(e.dom,s,l).getClientRects()});return i.after?new be(n[i.i+1],-1):new be(n[i.i],1)}scanTile(e,t){if(!e.length)return new be(t,1);if(e.children.length==1){let l=e.children[0];if(l.isText())return this.scanText(l,t);if(l.isComposite())return this.scanTile(l,t)}let n=[t];for(let l=0,a=t;l<e.children.length;l++)n.push(a+=e.children[l].length);let i=this.scan(n,l=>{let a=e.children[l];return a.flags&48?null:(a.dom.nodeType==1?a.dom:Xe(a.dom,0,a.length)).getClientRects()}),o=e.children[i.i],s=n[i.i];return o.isText()?this.scanText(o,s):o.isComposite()?this.scanTile(o,s):i.after?new be(n[i.i+1],-1):new be(s,1)}};var kt="\uFFFF",vr=class{constructor(e,t){this.points=e;this.view=t;this.text="";this.lineSeparator=t.state.facet(j.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=kt}readRange(e,t){if(!e)return this;let n=e.parentNode;for(let i=e;;){this.findPointBefore(n,i);let o=this.text.length;this.readNode(i);let s=O.get(i),l=i.nextSibling;if(l==t){s?.breakAfter&&!l&&n!=this.view.contentDOM&&this.lineBreak();break}let a=O.get(l);(s&&a?s.breakAfter:(s?s.breakAfter:un(i))||un(l)&&(i.nodeName!="BR"||s?.isWidget())&&this.text.length>o)&&!pu(l,t)&&this.lineBreak(),i=l}return this.findPointBefore(n,t),this}readTextNode(e){let t=e.nodeValue;for(let n of this.points)n.node==e&&(n.pos=this.text.length+Math.min(n.offset,t.length));for(let n=0,i=this.lineSeparator?null:/\r\n?|\n/g;;){let o=-1,s=1,l;if(this.lineSeparator?(o=t.indexOf(this.lineSeparator,n),s=this.lineSeparator.length):(l=i.exec(t))&&(o=l.index,s=l[0].length),this.append(t.slice(n,o<0?t.length:o)),o<0)break;if(this.lineBreak(),s>1)for(let a of this.points)a.node==e&&a.pos>this.text.length&&(a.pos-=s-1);n=o+s}}readNode(e){let t=O.get(e),n=t&&t.overrideDOMText;if(n!=null){this.findPointInside(e,n.length);for(let i=n.iter();!i.next().done;)i.lineBreak?this.lineBreak():this.append(i.value)}else e.nodeType==3?this.readTextNode(e):e.nodeName=="BR"?e.nextSibling&&this.lineBreak():e.nodeType==1&&this.readRange(e.firstChild,null)}findPointBefore(e,t){for(let n of this.points)n.node==e&&e.childNodes[n.offset]==t&&(n.pos=this.text.length)}findPointInside(e,t){for(let n of this.points)(e.nodeType==3?n.node==e:e.contains(n.node))&&(n.pos=this.text.length+(mu(e,n.node,n.offset)?t:0))}};function mu(r,e,t){for(;;){if(!e||t<ae(e))return!1;if(e==r)return!0;t=Ve(e)+1,e=e.parentNode}}function pu(r,e){let t;for(;!(r==e||!r);r=r.nextSibling){let n=O.get(r);if(!n?.isWidget())return!1;n&&(t||(t=[])).push(n)}if(t){for(let n of t)if(n.overrideDOMText?.length)return!1}return!0}var gn=class{constructor(e,t){this.node=e;this.offset=t;this.pos=-1}};var Mr=class{constructor(e,t,n,i){this.typeOver=i;this.bounds=null;this.text="";this.domChanged=t>-1;let{impreciseHead:o,impreciseAnchor:s}=e.docView,l=e.state.selection;if(e.state.readOnly&&t>-1)this.newSel=null;else if(t>-1&&(this.bounds=Us(e.docView.tile,t,n,0))){let a=o||s?[]:bu(e),u=new vr(a,e);u.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=u.text,this.newSel=yu(a,this.bounds.from)}else{let a=e.observer.selectionRange,u=o&&o.node==a.focusNode&&o.offset==a.focusOffset||!nr(e.contentDOM,a.focusNode)?l.main.head:e.docView.posFromDOM(a.focusNode,a.focusOffset),h=s&&s.node==a.anchorNode&&s.offset==a.anchorOffset||!nr(e.contentDOM,a.anchorNode)?l.main.anchor:e.docView.posFromDOM(a.anchorNode,a.anchorOffset),c=e.viewport;if((S.ios||S.chrome)&&l.main.empty&&u!=h&&(c.from>0||c.to<e.state.doc.length)){let f=Math.min(u,h),m=Math.max(u,h),d=c.from-f,p=c.to-m;(d==0||d==1||f==0)&&(p==0||p==-1||m==e.state.doc.length)&&(u=0,h=e.state.doc.length)}if(e.inputState.composing>-1&&l.ranges.length>1)this.newSel=l.replaceRange(y.range(h,u));else if(e.lineWrapping&&h==u&&!(l.main.empty&&l.main.head==u)&&e.inputState.lastTouchTime>Date.now()-100){let f=e.coordsAtPos(u,-1),m=0;f&&(m=e.inputState.lastTouchY<=f.bottom?-1:1),this.newSel=y.create([y.cursor(u,m)])}else this.newSel=y.single(h,u)}}};function Us(r,e,t,n){if(r.isComposite()){let i=-1,o=-1,s=-1,l=-1;for(let a=0,u=n,h=n;a<r.children.length;a++){let c=r.children[a],f=u+c.length;if(u<e&&f>t)return Us(c,e,t,u);if(f>=e&&i==-1&&(i=a,o=u),u>t&&c.dom.parentNode==r.dom){s=a,l=h;break}h=f,u=f+c.breakAfter}return{from:o,to:l<0?n+r.length:l,startDOM:(i?r.children[i-1].dom.nextSibling:null)||r.dom.firstChild,endDOM:s<r.children.length&&s>=0?r.children[s].dom:null}}else return r.isText()?{from:n,to:n+r.length,startDOM:r.dom,endDOM:r.dom.nextSibling}:null}function Er(r,e){let t,{newSel:n}=e,{state:i}=r,o=i.selection.main,s=r.inputState.lastKeyTime>Date.now()-100?r.inputState.lastKeyCode:-1;if(e.bounds){let{from:l,to:a}=e.bounds,u=o.from,h=null;(s===8||S.android&&e.text.length<a-l)&&(u=o.to,h="end");let c=i.doc.sliceString(l,a,kt),f,m;!o.empty&&o.from>=l&&o.to<=a&&(e.typeOver||c!=e.text)&&c.slice(0,o.from-l)==e.text.slice(0,o.from-l)&&c.slice(o.to-l)==e.text.slice(f=e.text.length-(c.length-(o.to-l)))?t={from:o.from,to:o.to,insert:A.of(e.text.slice(o.from-l,f).split(kt))}:(m=ho(c,e.text,u-l,h))&&(S.chrome&&s==13&&m.toB==m.from+2&&e.text.slice(m.from,m.toB)==kt+kt&&m.toB--,t={from:l+m.from,to:l+m.toA,insert:A.of(e.text.slice(m.from,m.toB).split(kt))})}else n&&(!r.hasFocus&&i.facet(ce)||bn(n,o))&&(n=null);if(!t&&!n)return!1;if((S.mac||S.android)&&t&&t.from==t.to&&t.from==o.head-1&&/^\. ?$/.test(t.insert.toString())&&r.contentDOM.getAttribute("autocorrect")=="off"?(n&&t.insert.length==2&&(n=y.single(n.main.anchor-1,n.main.head-1)),t={from:t.from,to:t.to,insert:A.of([t.insert.toString().replace("."," ")])}):i.doc.lineAt(o.from).to<o.to&&r.docView.lineHasWidget(o.to)&&r.inputState.insertingTextAt>Date.now()-50?t={from:o.from,to:o.to,insert:i.toText(r.inputState.insertingText)}:S.chrome&&t&&t.from==t.to&&t.from==o.head&&t.insert.toString()==`
+ `&&r.lineWrapping&&(n&&(n=y.single(n.main.anchor-1,n.main.head-1)),t={from:o.from,to:o.to,insert:A.of([" "])}),t)return yn(r,t,n,s);if(n&&!bn(n,o)){let l=!1,a="select";return r.inputState.lastSelectionTime>Date.now()-50&&(r.inputState.lastSelectionOrigin=="select"&&(l=!0),a=r.inputState.lastSelectionOrigin,a=="select.pointer"&&(n=wr(i.facet(ze).map(u=>u(r)),n))),r.dispatch({selection:n,scrollIntoView:l,userEvent:a}),!0}else return!1}function yn(r,e,t,n=-1){if(S.ios&&r.inputState.flushIOSKey(e))return!0;let i=r.state.selection.main;if(S.android&&(e.to==i.to&&(e.from==i.from||e.from==i.from-1&&r.state.sliceDoc(e.from,i.from)==" ")&&e.insert.length==1&&e.insert.lines==2&&He(r.contentDOM,"Enter",13)||(e.from==i.from-1&&e.to==i.to&&e.insert.length==0||n==8&&e.insert.length<e.to-e.from&&e.to>i.head)&&He(r.contentDOM,"Backspace",8)||e.from==i.from&&e.to==i.to+1&&e.insert.length==0&&He(r.contentDOM,"Delete",46)))return!0;let o=e.insert.toString();r.inputState.composing>=0&&r.inputState.composing++;let s,l=()=>s||(s=gu(r,e,t));return r.state.facet(hr).some(a=>a(r,e.from,e.to,o,l))||r.dispatch(l()),!0}function gu(r,e,t){let n,i=r.state,o=i.selection.main,s=-1;if(e.from==e.to&&e.from<o.from||e.from>o.to){let a=e.from<o.from?-1:1,u=a<0?o.from:o.to,h=jt(i.facet(ze).map(c=>c(r)),u,a);e.from==h&&(s=h)}if(s>-1)n={changes:e,selection:y.cursor(e.from+e.insert.length,-1)};else if(e.from>=o.from&&e.to<=o.to&&e.to-e.from>=(o.to-o.from)/3&&(!t||t.main.empty&&t.main.from==e.from+e.insert.length)&&r.inputState.composing<0){let a=o.from<e.from?i.sliceDoc(o.from,e.from):"",u=o.to>e.to?i.sliceDoc(e.to,o.to):"";n=i.replaceSelection(r.state.toText(a+e.insert.sliceString(0,void 0,r.state.lineBreak)+u))}else{let a=i.changes(e),u=t&&t.main.to<=a.newLength?t.main:void 0;if(i.selection.ranges.length>1&&(r.inputState.composing>=0||r.inputState.compositionPendingChange)&&e.to<=o.to+10&&e.to>=o.to-10){let h=r.state.sliceDoc(e.from,e.to),c,f=t&&lo(r,t.main.head);if(f){let d=e.insert.length-(e.to-e.from);c={from:f.from,to:f.to-d}}else c=r.state.doc.lineAt(o.head);let m=o.to-e.to;n=i.changeByRange(d=>{if(d.from==o.from&&d.to==o.to)return{changes:a,range:u||d.map(a)};let p=d.to-m,g=p-h.length;if(r.state.sliceDoc(g,p)!=h||p>=c.from&&g<=c.to)return{range:d};let b=i.changes({from:g,to:p,insert:e.insert}),C=d.to-o.to;return{changes:b,range:u?y.range(Math.max(0,u.anchor+C),Math.max(0,u.head+C)):d.map(b)}})}else n={changes:a,selection:u&&i.selection.replaceRange(u)}}let l="input.type";return(r.composing||r.inputState.compositionPendingChange&&r.inputState.compositionEndedAt>Date.now()-50)&&(r.inputState.compositionPendingChange=!1,l+=".compose",r.inputState.compositionFirstChange&&(l+=".start",r.inputState.compositionFirstChange=!1)),i.update(n,{userEvent:l,scrollIntoView:!0})}function ho(r,e,t,n){let i=Math.min(r.length,e.length),o=0;for(;o<i&&r.charCodeAt(o)==e.charCodeAt(o);)o++;if(o==i&&r.length==e.length)return null;let s=r.length,l=e.length;for(;s>0&&l>0&&r.charCodeAt(s-1)==e.charCodeAt(l-1);)s--,l--;if(n=="end"){let a=Math.max(0,o-Math.min(s,l));t-=s+a-o}if(s<o&&r.length<e.length){let a=t<=o&&t>=s?o-t:0;o-=a,l=o+(l-s),s=o}else if(l<o){let a=t<=o&&t>=l?o-t:0;o-=a,s=o+(s-l),l=o}return{from:o,toA:s,toB:l}}function bu(r){let e=[];if(r.root.activeElement!=r.contentDOM)return e;let{anchorNode:t,anchorOffset:n,focusNode:i,focusOffset:o}=r.observer.selectionRange;return t&&(e.push(new gn(t,n)),(i!=t||o!=n)&&e.push(new gn(i,o))),e}function yu(r,e){if(r.length==0)return null;let t=r[0].pos,n=r.length==2?r[1].pos:t;return t>-1&&n>-1?y.single(t+e,n+e):null}function bn(r,e){return e.head==r.main.head&&e.anchor==r.main.anchor}var Br=class{constructor(e){this.view=e;this.lastKeyCode=0;this.lastKeyTime=0;this.lastTouchTime=0;this.lastTouchX=0;this.lastTouchY=0;this.lastFocusTime=0;this.lastScrollTop=0;this.lastScrollLeft=0;this.lastWheelEvent=0;this.pendingIOSKey=void 0;this.tabFocusMode=-1;this.lastSelectionOrigin=null;this.lastSelectionTime=0;this.lastContextMenu=0;this.scrollHandlers=[];this.handlers=Object.create(null);this.composing=-1;this.compositionFirstChange=null;this.compositionEndedAt=0;this.compositionPendingKey=!1;this.compositionPendingChange=!1;this.insertingText="";this.insertingTextAt=0;this.mouseSelection=null;this.draggedContent=null;this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=e.hasFocus,S.safari&&e.contentDOM.addEventListener("input",()=>null),S.gecko&&Ou(e.contentDOM.ownerDocument)}setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}handleEvent(e){!vu(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||(this.view.updateState!=0?Promise.resolve().then(()=>this.runHandlers(e.type,e)):this.runHandlers(e.type,e))}runHandlers(e,t){let n=this.handlers[e];if(n){for(let i of n.observers)i(this.view,t);for(let i of n.handlers){if(t.defaultPrevented)break;if(i(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=xu(e),n=this.handlers,i=this.view.contentDOM;for(let o in t)if(o!="scroll"){let s=!t[o].handlers.length,l=n[o];l&&s!=!l.handlers.length&&(i.removeEventListener(o,this.handleEvent),l=null),l||i.addEventListener(o,this.handleEvent,{passive:s})}for(let o in n)o!="scroll"&&!t[o]&&i.removeEventListener(o,this.handleEvent);this.handlers=t}keydown(e){if(this.lastKeyCode=e.keyCode,this.lastKeyTime=Date.now(),e.keyCode==9&&this.tabFocusMode>-1&&(!this.tabFocusMode||Date.now()<=this.tabFocusMode))return!0;if(this.tabFocusMode>0&&e.keyCode!=27&&mo.indexOf(e.keyCode)<0&&(this.tabFocusMode=-1),S.android&&S.chrome&&!e.synthetic&&(e.keyCode==13||e.keyCode==8))return this.view.observer.delayAndroidKey(e.key,e.keyCode),!0;let t;return S.ios&&!e.synthetic&&!e.altKey&&!e.metaKey&&!e.shiftKey&&((t=Qs.find(n=>n.keyCode==e.keyCode))&&!e.ctrlKey||Su.indexOf(e.key)>-1&&e.ctrlKey)?(this.pendingIOSKey=t||e,setTimeout(()=>this.flushIOSKey(),250),!0):(e.keyCode!=229&&this.view.observer.forceFlush(),!1)}flushIOSKey(e){let t=this.pendingIOSKey;return!t||t.key=="Enter"&&e&&e.from<e.to&&/^\S+$/.test(e.insert.toString())?!1:(this.pendingIOSKey=void 0,He(this.view.contentDOM,t.key,t.keyCode,t instanceof KeyboardEvent?t:void 0))}ignoreDuringComposition(e){return!/^key/.test(e.type)||e.synthetic?!1:this.composing>0?!0:S.safari&&!S.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.view.observer.update(e),this.mouseSelection&&this.mouseSelection.update(e),this.draggedContent&&e.docChanged&&(this.draggedContent=this.draggedContent.map(e.changes)),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}};function qs(r,e){return(t,n)=>{try{return e.call(r,n,t)}catch(i){_(t.state,i)}}}function xu(r){let e=Object.create(null);function t(n){return e[n]||(e[n]={observers:[],handlers:[]})}for(let n of r){let i=n.spec,o=i&&i.plugin.domEventHandlers,s=i&&i.plugin.domEventObservers;if(o)for(let l in o){let a=o[l];a&&t(l).handlers.push(qs(n.value,a))}if(s)for(let l in s){let a=s[l];a&&t(l).observers.push(qs(n.value,a))}}for(let n in Me)t(n).handlers.push(Me[n]);for(let n in ne)t(n).observers.push(ne[n]);return e}var Qs=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],Su="dthko",mo=[16,17,18,20,91,92,224,225],Ar=6;function Dr(r){return Math.max(0,r)*.7+8}function Tu(r,e){return Math.max(Math.abs(r.clientX-e.clientX),Math.abs(r.clientY-e.clientY))}var co=class{constructor(e,t,n,i){this.view=e;this.startEvent=t;this.style=n;this.mustSelect=i;this.scrollSpeed={x:0,y:0};this.scrolling=-1;this.lastEvent=t,this.scrollParents=rr(e.contentDOM),this.atoms=e.state.facet(ze).map(s=>s(e));let o=e.contentDOM.ownerDocument;o.addEventListener("mousemove",this.move=this.move.bind(this)),o.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=t.shiftKey,this.multiple=e.state.facet(j.allowMultipleSelections)&&wu(e,t),this.dragging=ku(e,t)&&el(t)==1?null:!1}start(e){this.dragging===!1&&this.select(e)}move(e){if(e.buttons==0)return this.destroy();if(this.dragging||this.dragging==null&&Tu(this.startEvent,e)<10)return;this.select(this.lastEvent=e);let t=0,n=0,i=0,o=0,s=this.view.win.innerWidth,l=this.view.win.innerHeight;this.scrollParents.x&&({left:i,right:s}=this.scrollParents.x.getBoundingClientRect()),this.scrollParents.y&&({top:o,bottom:l}=this.scrollParents.y.getBoundingClientRect());let a=gr(this.view);e.clientX-a.left<=i+Ar?t=-Dr(i-e.clientX):e.clientX+a.right>=s-Ar&&(t=Dr(e.clientX-s)),e.clientY-a.top<=o+Ar?n=-Dr(o-e.clientY):e.clientY+a.bottom>=l-Ar&&(n=Dr(e.clientY-l)),this.setScrollSpeed(t,n)}up(e){this.dragging==null&&this.select(this.lastEvent),this.dragging||e.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let e=this.view.contentDOM.ownerDocument;e.removeEventListener("mousemove",this.move),e.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=this.view.inputState.draggedContent=null}setScrollSpeed(e,t){this.scrollSpeed={x:e,y:t},e||t?this.scrolling<0&&(this.scrolling=setInterval(()=>this.scroll(),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){let{x:e,y:t}=this.scrollSpeed;e&&this.scrollParents.x&&(this.scrollParents.x.scrollLeft+=e,e=0),t&&this.scrollParents.y&&(this.scrollParents.y.scrollTop+=t,t=0),(e||t)&&this.view.win.scrollBy(e,t),this.dragging===!1&&this.select(this.lastEvent)}select(e){let{view:t}=this,n=wr(this.atoms,this.style.get(e,this.extend,this.multiple));(this.mustSelect||!n.eq(t.state.selection,this.dragging===!1))&&this.view.dispatch({selection:n,userEvent:"select.pointer"}),this.mustSelect=!1}update(e){e.transactions.some(t=>t.isUserEvent("input.type"))?this.destroy():this.style.update(e)&&setTimeout(()=>this.select(this.lastEvent),20)}};function wu(r,e){let t=r.state.facet(sr);return t.length?t[0](e):S.mac?e.metaKey:e.ctrlKey}function Cu(r,e){let t=r.state.facet(lr);return t.length?t[0](e):S.mac?!e.altKey:!e.ctrlKey}function ku(r,e){let{main:t}=r.state.selection;if(t.empty)return!1;let n=$e(r.root);if(!n||n.rangeCount==0)return!0;let i=n.getRangeAt(0).getClientRects();for(let o=0;o<i.length;o++){let s=i[o];if(s.left<=e.clientX&&s.right>=e.clientX&&s.top<=e.clientY&&s.bottom>=e.clientY)return!0}return!1}function vu(r,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target,n;t!=r.contentDOM;t=t.parentNode)if(!t||t.nodeType==11||(n=O.get(t))&&n.isWidget()&&!n.isHidden&&n.widget.ignoreEvent(e))return!1;return!0}var Me=Object.create(null),ne=Object.create(null),Zs=S.ie&&S.ie_version<15||S.ios&&S.webkit_version<604;function Mu(r){let e=r.dom.parentNode;if(!e)return;let t=e.appendChild(document.createElement("textarea"));t.style.cssText="position: fixed; left: -10000px; top: 10px",t.focus(),setTimeout(()=>{r.focus(),t.remove(),_s(r,t.value)},50)}function Rr(r,e,t){for(let n of r.facet(e))t=n(t,r);return t}function _s(r,e){e=Rr(r.state,hn,e);let{state:t}=r,n,i=1,o=t.toText(e),s=o.lines==t.selection.ranges.length;if(fo!=null&&t.selection.ranges.every(a=>a.empty)&&fo==o.toString()){let a=-1;n=t.changeByRange(u=>{let h=t.doc.lineAt(u.from);if(h.from==a)return{range:u};a=h.from;let c=t.toText((s?o.line(i++).text:e)+t.lineBreak);return{changes:{from:h.from,insert:c},range:y.cursor(u.from+c.length)}})}else s?n=t.changeByRange(a=>{let u=o.line(i++);return{changes:{from:a.from,to:a.to,insert:u.text},range:y.cursor(a.from+u.length)}}):n=t.replaceSelection(o);r.dispatch(n,{userEvent:"input.paste",scrollIntoView:!0})}ne.scroll=r=>{r.inputState.lastScrollTop=r.scrollDOM.scrollTop,r.inputState.lastScrollLeft=r.scrollDOM.scrollLeft};ne.wheel=ne.mousewheel=r=>{r.inputState.lastWheelEvent=Date.now()};Me.keydown=(r,e)=>(r.inputState.setSelectionOrigin("select"),e.keyCode==27&&r.inputState.tabFocusMode!=0&&(r.inputState.tabFocusMode=Date.now()+2e3),!1);ne.touchstart=(r,e)=>{let t=r.inputState,n=e.targetTouches[0];t.lastTouchTime=Date.now(),n&&(t.lastTouchX=n.clientX,t.lastTouchY=n.clientY),t.setSelectionOrigin("select.pointer")};ne.touchmove=r=>{r.inputState.setSelectionOrigin("select.pointer")};Me.mousedown=(r,e)=>{if(r.observer.flush(),r.inputState.lastTouchTime>Date.now()-2e3)return!1;let t=null;for(let n of r.state.facet(ar))if(t=n(r,e),t)break;if(!t&&e.button==0&&(t=Au(r,e)),t){let n=!r.hasFocus;r.inputState.startMouseSelection(new co(r,e,t,n)),n&&r.observer.ignore(()=>{ir(r.contentDOM);let o=r.root.activeElement;o&&!o.contains(r.contentDOM)&&o.blur()});let i=r.inputState.mouseSelection;if(i)return i.start(e),i.dragging===!1}else r.inputState.setSelectionOrigin("select.pointer");return!1};function Gs(r,e,t,n){if(n==1)return y.cursor(e,t);if(n==2)return Fs(r.state,e,t);{let i=r.docView.lineAt(e,t),o=r.state.doc.lineAt(i?i.posAtEnd:e),s=i?i.posAtStart:o.from,l=i?i.posAtEnd:o.to;return l<r.state.doc.length&&l==o.to&&l++,y.range(s,l)}}var Eu=S.ie&&S.ie_version<=11,js=null,Js=0,$s=0;function el(r){if(!Eu)return r.detail;let e=js,t=$s;return js=r,$s=Date.now(),Js=!e||t>Date.now()-400&&Math.abs(e.clientX-r.clientX)<2&&Math.abs(e.clientY-r.clientY)<2?(Js+1)%3:1}function Au(r,e){let t=r.posAndSideAtCoords({x:e.clientX,y:e.clientY},!1),n=el(e),i=r.state.selection;return{update(o){o.docChanged&&(t.pos=o.changes.mapPos(t.pos),i=i.map(o.changes))},get(o,s,l){let a=r.posAndSideAtCoords({x:o.clientX,y:o.clientY},!1),u,h=Gs(r,a.pos,a.assoc,n);if(t.pos!=a.pos&&!s){let c=Gs(r,t.pos,t.assoc,n),f=Math.min(c.from,h.from),m=Math.max(c.to,h.to);h=f<h.from?y.range(f,m,h.assoc):y.range(m,f,h.assoc)}return s?i.replaceRange(i.main.extend(h.from,h.to,h.assoc)):l&&n==1&&i.ranges.length>1&&(u=Du(i,a.pos))?u:l?i.addRange(h):y.create([h])}}}function Du(r,e){for(let t=0;t<r.ranges.length;t++){let{from:n,to:i}=r.ranges[t];if(n<=e&&i>=e)return y.create(r.ranges.slice(0,t).concat(r.ranges.slice(t+1)),r.mainIndex==t?0:r.mainIndex-(r.mainIndex>t?1:0))}return null}Me.dragstart=(r,e)=>{let{selection:{main:t}}=r.state;if(e.target.draggable){let i=r.docView.tile.nearest(e.target);if(i&&i.isWidget()){let o=i.posAtStart,s=o+i.length;(o>=t.to||s<=t.from)&&(t=y.range(o,s))}}let{inputState:n}=r;return n.mouseSelection&&(n.mouseSelection.dragging=!0),n.draggedContent=t,e.dataTransfer&&(e.dataTransfer.setData("Text",Rr(r.state,cn,r.state.sliceDoc(t.from,t.to))),e.dataTransfer.effectAllowed="copyMove"),!1};Me.dragend=r=>(r.inputState.draggedContent=null,!1);function Ys(r,e,t,n){if(t=Rr(r.state,hn,t),!t)return;let i=r.posAtCoords({x:e.clientX,y:e.clientY},!1),{draggedContent:o}=r.inputState,s=n&&o&&Cu(r,e)?{from:o.from,to:o.to}:null,l={from:i,insert:t},a=r.state.changes(s?[s,l]:l);r.focus(),r.dispatch({changes:a,selection:{anchor:a.mapPos(i,-1),head:a.mapPos(i,1)},userEvent:s?"move.drop":"input.drop"}),r.inputState.draggedContent=null}Me.drop=(r,e)=>{if(!e.dataTransfer)return!1;if(r.state.readOnly)return!0;let t=e.dataTransfer.files;if(t&&t.length){let n=Array(t.length),i=0,o=()=>{++i==t.length&&Ys(r,e,n.filter(s=>s!=null).join(r.state.lineBreak),!1)};for(let s=0;s<t.length;s++){let l=new FileReader;l.onerror=o,l.onload=()=>{/[\x00-\x08\x0e-\x1f]{2}/.test(l.result)||(n[s]=l.result),o()},l.readAsText(t[s])}return!0}else{let n=e.dataTransfer.getData("Text");if(n)return Ys(r,e,n,!0),!0}return!1};Me.paste=(r,e)=>{if(r.state.readOnly)return!0;r.observer.flush();let t=Zs?null:e.clipboardData;return t?(_s(r,t.getData("text/plain")||t.getData("text/uri-list")),!0):(Mu(r),!1)};function Bu(r,e){let t=r.dom.parentNode;if(!t)return;let n=t.appendChild(document.createElement("textarea"));n.style.cssText="position: fixed; left: -10000px; top: 10px",n.value=e,n.focus(),n.selectionEnd=e.length,n.selectionStart=0,setTimeout(()=>{n.remove(),r.focus()},50)}function Ru(r){let e=[],t=[],n=!1;for(let i of r.selection.ranges)i.empty||(e.push(r.sliceDoc(i.from,i.to)),t.push(i));if(!e.length){let i=-1;for(let{from:o}of r.selection.ranges){let s=r.doc.lineAt(o);s.number>i&&(e.push(s.text),t.push({from:s.from,to:Math.min(r.doc.length,s.to+1)})),i=s.number}n=!0}return{text:Rr(r,cn,e.join(r.lineBreak)),ranges:t,linewise:n}}var fo=null;Me.copy=Me.cut=(r,e)=>{if(!Ye(r.contentDOM,r.observer.selectionRange))return!1;let{text:t,ranges:n,linewise:i}=Ru(r.state);if(!t&&!i)return!1;fo=i?t:null,e.type=="cut"&&!r.state.readOnly&&r.dispatch({changes:n,scrollIntoView:!0,userEvent:"delete.cut"});let o=Zs?null:e.clipboardData;return o?(o.clearData(),o.setData("text/plain",t),!0):(Bu(r,t),!1)};var po=le.define();function go(r,e){let t=[];for(let n of r.facet(cr)){let i=n(r,e);i&&t.push(i)}return t.length?r.update({effects:t,annotations:po.of(!0)}):null}function tl(r){setTimeout(()=>{let e=r.hasFocus;if(e!=r.inputState.notifiedFocused){let t=go(r.state,e);t?r.dispatch(t):r.update([])}},10)}ne.focus=r=>{r.inputState.lastFocusTime=Date.now(),!r.scrollDOM.scrollTop&&(r.inputState.lastScrollTop||r.inputState.lastScrollLeft)&&(r.scrollDOM.scrollTop=r.inputState.lastScrollTop,r.scrollDOM.scrollLeft=r.inputState.lastScrollLeft),tl(r)};ne.blur=r=>{r.observer.clearSelectionRange(),tl(r)};ne.compositionstart=ne.compositionupdate=r=>{r.observer.editContext||(r.inputState.compositionFirstChange==null&&(r.inputState.compositionFirstChange=!0),r.inputState.composing<0&&(r.inputState.composing=0))};ne.compositionend=r=>{r.observer.editContext||(r.inputState.composing=-1,r.inputState.compositionEndedAt=Date.now(),r.inputState.compositionPendingKey=!0,r.inputState.compositionPendingChange=r.observer.pendingRecords().length>0,r.inputState.compositionFirstChange=null,S.chrome&&S.android?r.observer.flushSoon():r.inputState.compositionPendingChange?Promise.resolve().then(()=>r.observer.flush()):setTimeout(()=>{r.inputState.composing<0&&r.docView.hasComposition&&r.update([])},50))};ne.contextmenu=r=>{r.inputState.lastContextMenu=Date.now()};Me.beforeinput=(r,e)=>{if((e.inputType=="insertText"||e.inputType=="insertCompositionText")&&(r.inputState.insertingText=e.data,r.inputState.insertingTextAt=Date.now()),e.inputType=="insertReplacementText"&&r.observer.editContext){let n=e.dataTransfer?.getData("text/plain"),i=e.getTargetRanges();if(n&&i.length){let o=i[0],s=r.posAtDOM(o.startContainer,o.startOffset),l=r.posAtDOM(o.endContainer,o.endOffset);return yn(r,{from:s,to:l,insert:r.state.toText(n)},null),!0}}let t;if(S.chrome&&S.android&&(t=Qs.find(n=>n.inputType==e.inputType))&&(r.observer.delayAndroidKey(t.key,t.keyCode),t.key=="Backspace"||t.key=="Delete")){let n=window.visualViewport?.height||0;setTimeout(()=>{(window.visualViewport?.height||0)>n+10&&r.hasFocus&&(r.contentDOM.blur(),r.focus())},100)}return S.ios&&e.inputType=="deleteContentForward"&&r.observer.flushSoon(),S.safari&&e.inputType=="insertText"&&r.inputState.composing>=0&&setTimeout(()=>ne.compositionend(r,e),20),!1};var Xs=new Set;function Ou(r){Xs.has(r)||(Xs.add(r),r.addEventListener("copy",()=>{}),r.addEventListener("cut",()=>{}))}var nl=["pre-wrap","normal","pre-line","break-spaces"],vt=!1;function So(){vt=!1}var Lr=class{constructor(e){this.lineWrapping=e;this.doc=A.empty;this.heightSamples={};this.lineHeight=14;this.charWidth=7;this.textHeight=14;this.lineLength=30}heightForGap(e,t){let n=this.doc.lineAt(t).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(n+=Math.max(0,Math.ceil((t-e-n*this.lineLength*.5)/this.lineLength))),this.lineHeight*n}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/Math.max(1,this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return nl.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let t=!1;for(let n=0;n<e.length;n++){let i=e[n];i<0?n++:this.heightSamples[Math.floor(i*10)]||(t=!0,this.heightSamples[Math.floor(i*10)]=!0)}return t}refresh(e,t,n,i,o,s){let l=nl.indexOf(e)>-1,a=Math.abs(t-this.lineHeight)>.3||this.lineWrapping!=l||Math.abs(n-this.charWidth)>.1;if(this.lineWrapping=l,this.lineHeight=t,this.charWidth=n,this.textHeight=i,this.lineLength=o,a){this.heightSamples={};for(let u=0;u<s.length;u++){let h=s[u];h<0?u++:this.heightSamples[Math.floor(h*10)]=!0}}return a}},Ir=class{constructor(e,t){this.from=e;this.heights=t;this.index=0}get more(){return this.index<this.heights.length}},xe=class r{constructor(e,t,n,i,o){this.from=e;this.length=t;this.top=n;this.height=i;this._content=o}get type(){return typeof this._content=="number"?0:Array.isArray(this._content)?this._content:this._content.type}get to(){return this.from+this.length}get bottom(){return this.top+this.height}get widget(){return this._content instanceof We?this._content.widget:null}get widgetLineBreaks(){return typeof this._content=="number"?this._content:0}join(e){let t=(Array.isArray(this._content)?this._content:[this]).concat(Array.isArray(e._content)?e._content:[e]);return new r(this.from,this.length+e.length,this.top,this.height+e.height,t)}};var Or=.001,re=class r{constructor(e,t,n=2){this.length=e;this.height=t;this.flags=n}get outdated(){return(this.flags&2)>0}set outdated(e){this.flags=(e?2:0)|this.flags&-3}setHeight(e){this.height!=e&&(Math.abs(this.height-e)>Or&&(vt=!0),this.height=e)}replace(e,t,n){return r.of(n)}decomposeLeft(e,t){t.push(this)}decomposeRight(e,t){t.push(this)}applyChanges(e,t,n,i){let o=this,s=n.doc;for(let l=i.length-1;l>=0;l--){let{fromA:a,toA:u,fromB:h,toB:c}=i[l],f=o.lineAt(a,2,n.setDoc(t),0,0),m=f.to>=u?f:o.lineAt(u,2,n,0,0);for(c+=m.to-u,u=m.to;l>0&&f.from<=i[l-1].toA;)a=i[l-1].fromA,h=i[l-1].fromB,l--,a<f.from&&(f=o.lineAt(a,2,n,0,0));h+=f.from-a,a=f.from;let d=yo.build(n.setDoc(s),e,h,c);o=Nr(o,o.replace(a,u,d))}return o.updateHeight(n,0)}static empty(){return new ye(0,0,0)}static of(e){if(e.length==1)return e[0];let t=0,n=e.length,i=0,o=0;for(;;)if(t==n)if(i>o*2){let l=e[t-1];l.break?e.splice(--t,1,l.left,null,l.right):e.splice(--t,1,l.left,l.right),n+=1+l.break,i-=l.size}else if(o>i*2){let l=e[n];l.break?e.splice(n,1,l.left,null,l.right):e.splice(n,1,l.left,l.right),n+=2+l.break,o-=l.size}else break;else if(i<o){let l=e[t++];l&&(i+=l.size)}else{let l=e[--n];l&&(o+=l.size)}let s=0;return e[t-1]==null?(s=1,t--):e[t]==null&&(s=1,n++),new bo(r.of(e.slice(0,t)),s,r.of(e.slice(n)))}};function Nr(r,e){return r==e?r:(r.constructor!=e.constructor&&(vt=!0),e)}re.prototype.size=1;var Lu=V.replace({}),Pr=class extends re{constructor(t,n,i){super(t,n);this.deco=i;this.spaceAbove=0}mainBlock(t,n){return new xe(n,this.length,t+this.spaceAbove,this.height-this.spaceAbove,this.deco||0)}blockAt(t,n,i,o){return this.spaceAbove&&t<i+this.spaceAbove?new xe(o,0,i,this.spaceAbove,Lu):this.mainBlock(i,o)}lineAt(t,n,i,o,s){let l=this.mainBlock(o,s);return this.spaceAbove?this.blockAt(0,i,o,s).join(l):l}forEachLine(t,n,i,o,s,l){t<=s+this.length&&n>=s&&l(this.lineAt(0,0,i,o,s))}setMeasuredHeight(t){let n=t.heights[t.index++];n<0?(this.spaceAbove=-n,n=t.heights[t.index++]):this.spaceAbove=0,this.setHeight(n)}updateHeight(t,n=0,i=!1,o){return o&&o.from<=n&&o.more&&this.setMeasuredHeight(o),this.outdated=!1,this}toString(){return`block(${this.length})`}},ye=class r extends Pr{constructor(t,n,i){super(t,n,null);this.collapsed=0;this.widgetHeight=0;this.breaks=0;this.spaceAbove=i}mainBlock(t,n){return new xe(n,this.length,t+this.spaceAbove,this.height-this.spaceAbove,this.breaks)}replace(t,n,i){let o=i[0];return i.length==1&&(o instanceof r||o instanceof et&&o.flags&4)&&Math.abs(this.length-o.length)<10?(o instanceof et?o=new r(o.length,this.height,this.spaceAbove):o.height=this.height,this.outdated||(o.outdated=!1),o):re.of(i)}updateHeight(t,n=0,i=!1,o){return o&&o.from<=n&&o.more?this.setMeasuredHeight(o):(i||this.outdated)&&(this.spaceAbove=0,this.setHeight(Math.max(this.widgetHeight,t.heightForLine(this.length-this.collapsed))+this.breaks*t.lineHeight)),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}},et=class r extends re{constructor(e){super(e,0)}heightMetrics(e,t){let n=e.doc.lineAt(t).number,i=e.doc.lineAt(t+this.length).number,o=i-n+1,s,l=0;if(e.lineWrapping){let a=Math.min(this.height,e.lineHeight*o);s=a/o,this.length>o+1&&(l=(this.height-a)/(this.length-o-1))}else s=this.height/o;return{firstLine:n,lastLine:i,perLine:s,perChar:l}}blockAt(e,t,n,i){let{firstLine:o,lastLine:s,perLine:l,perChar:a}=this.heightMetrics(t,i);if(t.lineWrapping){let u=i+(e<t.lineHeight?0:Math.round(Math.max(0,Math.min(1,(e-n)/this.height))*this.length)),h=t.doc.lineAt(u),c=l+h.length*a,f=Math.max(n,e-c/2);return new xe(h.from,h.length,f,c,0)}else{let u=Math.max(0,Math.min(s-o,Math.floor((e-n)/l))),{from:h,length:c}=t.doc.line(o+u);return new xe(h,c,n+l*u,l,0)}}lineAt(e,t,n,i,o){if(t==1)return this.blockAt(e,n,i,o);if(t==2){let{from:m,to:d}=n.doc.lineAt(e);return new xe(m,d-m,0,0,0)}let{firstLine:s,perLine:l,perChar:a}=this.heightMetrics(n,o),u=n.doc.lineAt(e),h=l+u.length*a,c=u.number-s,f=i+l*c+a*(u.from-o-c);return new xe(u.from,u.length,Math.max(i,Math.min(f,i+this.height-h)),h,0)}forEachLine(e,t,n,i,o,s){e=Math.max(e,o),t=Math.min(t,o+this.length);let{firstLine:l,perLine:a,perChar:u}=this.heightMetrics(n,o);for(let h=e,c=i;h<=t;){let f=n.doc.lineAt(h);if(h==e){let d=f.number-l;c+=a*d+u*(e-o-d)}let m=a+u*f.length;s(new xe(f.from,f.length,c,m,0)),c+=m,h=f.to+1}}replace(e,t,n){let i=this.length-t;if(i>0){let o=n[n.length-1];o instanceof r?n[n.length-1]=new r(o.length+i):n.push(null,new r(i-1))}if(e>0){let o=n[0];o instanceof r?n[0]=new r(e+o.length):n.unshift(new r(e-1),null)}return re.of(n)}decomposeLeft(e,t){t.push(new r(e-1),null)}decomposeRight(e,t){t.push(null,new r(this.length-e-1))}updateHeight(e,t=0,n=!1,i){let o=t+this.length;if(i&&i.from<=t+this.length&&i.more){let s=[],l=Math.max(t,i.from),a=-1;for(i.from>t&&s.push(new r(i.from-t-1).updateHeight(e,t));l<=o&&i.more;){let h=e.doc.lineAt(l).length;s.length&&s.push(null);let c=i.heights[i.index++],f=0;c<0&&(f=-c,c=i.heights[i.index++]),a==-1?a=c:Math.abs(c-a)>=Or&&(a=-2);let m=new ye(h,c,f);m.outdated=!1,s.push(m),l+=h+1}l<=o&&s.push(null,new r(o-l).updateHeight(e,l));let u=re.of(s);return(a<0||Math.abs(u.height-this.height)>=Or||Math.abs(a-this.heightMetrics(e,t).perLine)>=Or)&&(vt=!0),Nr(this,u)}else(n||this.outdated)&&(this.setHeight(e.heightForGap(t,t+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}},bo=class extends re{constructor(t,n,i){super(t.length+n+i.length,t.height+i.height,n|(t.outdated||i.outdated?2:0));this.left=t;this.right=i;this.size=t.size+i.size}get break(){return this.flags&1}blockAt(t,n,i,o){let s=i+this.left.height;return t<s?this.left.blockAt(t,n,i,o):this.right.blockAt(t,n,s,o+this.left.length+this.break)}lineAt(t,n,i,o,s){let l=o+this.left.height,a=s+this.left.length+this.break,u=n==1?t<l:t<a,h=u?this.left.lineAt(t,n,i,o,s):this.right.lineAt(t,n,i,l,a);if(this.break||(u?h.to<a:h.from>a))return h;let c=n==2?2:0;return u?h.join(this.right.lineAt(a,c,i,l,a)):this.left.lineAt(a,c,i,o,s).join(h)}forEachLine(t,n,i,o,s,l){let a=o+this.left.height,u=s+this.left.length+this.break;if(this.break)t<u&&this.left.forEachLine(t,n,i,o,s,l),n>=u&&this.right.forEachLine(t,n,i,a,u,l);else{let h=this.lineAt(u,0,i,o,s);t<h.from&&this.left.forEachLine(t,h.from-1,i,o,s,l),h.to>=t&&h.from<=n&&l(h),n>h.to&&this.right.forEachLine(h.to+1,n,i,a,u,l)}}replace(t,n,i){let o=this.left.length+this.break;if(n<o)return this.balanced(this.left.replace(t,n,i),this.right);if(t>this.left.length)return this.balanced(this.left,this.right.replace(t-o,n-o,i));let s=[];t>0&&this.decomposeLeft(t,s);let l=s.length;for(let a of i)s.push(a);if(t>0&&rl(s,l-1),n<this.length){let a=s.length;this.decomposeRight(n,s),rl(s,a)}return re.of(s)}decomposeLeft(t,n){let i=this.left.length;if(t<=i)return this.left.decomposeLeft(t,n);n.push(this.left),this.break&&(i++,t>=i&&n.push(null)),t>i&&this.right.decomposeLeft(t-i,n)}decomposeRight(t,n){let i=this.left.length,o=i+this.break;if(t>=o)return this.right.decomposeRight(t-o,n);t<i&&this.left.decomposeRight(t,n),this.break&&t<o&&n.push(null),n.push(this.right)}balanced(t,n){return t.size>2*n.size||n.size>2*t.size?re.of(this.break?[t,null,n]:[t,n]):(this.left=Nr(this.left,t),this.right=Nr(this.right,n),this.setHeight(t.height+n.height),this.outdated=t.outdated||n.outdated,this.size=t.size+n.size,this.length=t.length+this.break+n.length,this)}updateHeight(t,n=0,i=!1,o){let{left:s,right:l}=this,a=n+s.length+this.break,u=null;return o&&o.from<=n+s.length&&o.more?u=s=s.updateHeight(t,n,i,o):s.updateHeight(t,n,i),o&&o.from<=a+l.length&&o.more?u=l=l.updateHeight(t,a,i,o):l.updateHeight(t,a,i),u?this.balanced(s,l):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}};function rl(r,e){let t,n;r[e]==null&&(t=r[e-1])instanceof et&&(n=r[e+1])instanceof et&&r.splice(e-1,3,new et(t.length+1+n.length))}var Iu=5,yo=class r{constructor(e,t){this.pos=e;this.oracle=t;this.nodes=[];this.lineStart=-1;this.lineEnd=-1;this.covering=null;this.writtenTo=e}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(e,t){if(this.lineStart>-1){let n=Math.min(t,this.lineEnd),i=this.nodes[this.nodes.length-1];i instanceof ye?i.length+=n-this.pos:(n>this.pos||!this.isCovered)&&this.nodes.push(new ye(n-this.pos,-1,0)),this.writtenTo=n,t>n&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=t}point(e,t,n){if(e<t||n.heightRelevant){let i=n.widget?n.widget.estimatedHeight:0,o=n.widget?n.widget.lineBreaks:0;i<0&&(i=this.oracle.lineHeight);let s=t-e;n.block?this.addBlock(new Pr(s,i,n)):(s||o||i>=Iu)&&this.addLineDeco(i,o,s)}else t>e&&this.span(e,t);this.lineEnd>-1&&this.lineEnd<this.pos&&(this.lineEnd=this.oracle.doc.lineAt(this.pos).to)}enterLine(){if(this.lineStart>-1)return;let{from:e,to:t}=this.oracle.doc.lineAt(this.pos);this.lineStart=e,this.lineEnd=t,this.writtenTo<e&&((this.writtenTo<e-1||this.nodes[this.nodes.length-1]==null)&&this.nodes.push(this.blankContent(this.writtenTo,e-1)),this.nodes.push(null)),this.pos>e&&this.nodes.push(new ye(this.pos-e,-1,0)),this.writtenTo=this.pos}blankContent(e,t){let n=new et(t-e);return this.oracle.doc.lineAt(e).to==t&&(n.flags|=4),n}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof ye)return e;let t=new ye(0,-1,0);return this.nodes.push(t),t}addBlock(e){this.enterLine();let t=e.deco;t&&t.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(e),this.writtenTo=this.pos=this.pos+e.length,t&&t.endSide>0&&(this.covering=e)}addLineDeco(e,t,n){let i=this.ensureLine();i.length+=n,i.collapsed+=n,i.widgetHeight=Math.max(i.widgetHeight,e),i.breaks+=t,this.writtenTo=this.pos=this.pos+n}finish(e){let t=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(t instanceof ye)&&!this.isCovered?this.nodes.push(new ye(0,-1,0)):(this.writtenTo<this.pos||t==null)&&this.nodes.push(this.blankContent(this.writtenTo,this.pos));let n=e;for(let i of this.nodes)i instanceof ye&&i.updateHeight(this.oracle,n),n+=i?i.length:1;return this.nodes}static build(e,t,n,i){let o=new r(n,e);return N.spans(t,n,i,o,0),o.finish(n)}};function ol(r,e,t){let n=new xo;return N.compare(r,e,t,n,0),n.changes}var xo=class{constructor(){this.changes=[]}compareRange(){}comparePoint(e,t,n,i){(e<t||n&&n.heightRelevant||i&&i.heightRelevant)&&Je(e,t,this.changes,5)}};function Pu(r,e){let t=r.getBoundingClientRect(),n=r.ownerDocument,i=n.defaultView||window,o=Math.max(0,t.left),s=Math.min(i.innerWidth,t.right),l=Math.max(0,t.top),a=Math.min(i.innerHeight,t.bottom);for(let u=r.parentNode;u&&u!=n.body;)if(u.nodeType==1){let h=u,c=window.getComputedStyle(h);if((h.scrollHeight>h.clientHeight||h.scrollWidth>h.clientWidth)&&c.overflow!="visible"){let f=h.getBoundingClientRect();o=Math.max(o,f.left),s=Math.min(s,f.right),l=Math.max(l,f.top),a=Math.min(u==r.parentNode?i.innerHeight:a,f.bottom)}u=c.position=="absolute"||c.position=="fixed"?h.offsetParent:h.parentNode}else if(u.nodeType==11)u=u.host;else break;return{left:o-t.left,right:Math.max(o,s)-t.left,top:l-(t.top+e),bottom:Math.max(l,a)-(t.top+e)}}function Vu(r){let e=r.getBoundingClientRect(),t=r.ownerDocument.defaultView||window;return e.left<t.innerWidth&&e.right>0&&e.top<t.innerHeight&&e.bottom>0}function Hu(r,e){let t=r.getBoundingClientRect();return{left:0,right:t.right-t.left,top:e,bottom:t.bottom-(t.top+e)}}var Sn=class{constructor(e,t,n,i){this.from=e;this.to=t;this.size=n;this.displaySize=i}static same(e,t){if(e.length!=t.length)return!1;for(let n=0;n<e.length;n++){let i=e[n],o=t[n];if(i.from!=o.from||i.to!=o.to||i.size!=o.size)return!1}return!0}draw(e,t){return V.replace({widget:new To(this.displaySize*(t?e.scaleY:e.scaleX),t)}).range(this.from,this.to)}},To=class extends ke{constructor(t,n){super();this.size=t;this.vertical=n}eq(t){return t.size==this.size&&t.vertical==this.vertical}toDOM(){let t=document.createElement("div");return this.vertical?t.style.height=this.size+"px":(t.style.width=this.size+"px",t.style.height="2px",t.style.display="inline-block"),t}get estimatedHeight(){return this.vertical?this.size:-1}};var Tn=class{constructor(e,t){this.view=e;this.state=t;this.pixelViewport={left:0,right:window.innerWidth,top:0,bottom:0};this.inView=!0;this.paddingTop=0;this.paddingBottom=0;this.contentDOMWidth=0;this.contentDOMHeight=0;this.editorHeight=0;this.editorWidth=0;this.scaleX=1;this.scaleY=1;this.scrollOffset=0;this.scrolledToBottom=!1;this.scrollAnchorPos=0;this.scrollAnchorHeight=-1;this.scaler=sl;this.scrollTarget=null;this.printing=!1;this.mustMeasureContent=!0;this.defaultTextDirection=0;this.visibleRanges=[];this.mustEnforceCursorAssoc=!1;let n=t.facet(dn).some(i=>typeof i!="function"&&i.class=="cm-lineWrapping");this.heightOracle=new Lr(n),this.stateDeco=ll(t),this.heightMap=re.empty().applyChanges(this.stateDeco,A.empty,this.heightOracle.setDoc(t.doc),[new he(0,0,0,t.doc.length)]);for(let i=0;i<2&&(this.viewport=this.getViewport(0,null),!!this.updateForViewport());i++);this.updateViewportLines(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=V.set(this.lineGaps.map(i=>i.draw(this,!1))),this.scrollParent=e.scrollDOM,this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:t}=this.state.selection;for(let n=0;n<=1;n++){let i=n?t.head:t.anchor;if(!e.some(({from:o,to:s})=>i>=o&&i<=s)){let{from:o,to:s}=this.lineBlockAt(i);e.push(new Jt(o,s))}}return this.viewports=e.sort((n,i)=>n.from-i.from),this.updateScaler()}updateScaler(){let e=this.scaler;return this.scaler=this.heightMap.height<=7e6?sl:new wo(this.heightOracle,this.heightMap,this.viewports),e.eq(this.scaler)?0:2}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,e=>{this.viewportLines.push(xn(e,this.scaler))})}update(e,t=null){this.state=e.state;let n=this.stateDeco;this.stateDeco=ll(this.state);let i=e.changedRanges,o=he.extendWithRanges(i,ol(n,this.stateDeco,e?e.changes:G.empty(this.state.doc.length))),s=this.heightMap.height,l=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollOffset);So(),this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),o),(this.heightMap.height!=s||vt)&&(e.flags|=2),l?(this.scrollAnchorPos=e.changes.mapPos(l.from,-1),this.scrollAnchorHeight=l.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=s);let a=o.length?this.mapViewport(this.viewport,e.changes):this.viewport;(t&&(t.range.head<a.from||t.range.head>a.to)||!this.viewportIsAppropriate(a))&&(a=this.getViewport(0,t));let u=a.from!=this.viewport.from||a.to!=this.viewport.to;this.viewport=a,e.flags|=this.updateForViewport(),(u||!e.changes.empty||e.flags&2)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,e.changes))),e.flags|=this.computeVisibleRanges(e.changes),t&&(this.scrollTarget=t),!this.mustEnforceCursorAssoc&&(e.selectionSet||e.focusChanged)&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(fr)&&(this.mustEnforceCursorAssoc=!0)}measure(){let{view:e}=this,t=e.contentDOM,n=window.getComputedStyle(t),i=this.heightOracle,o=n.whiteSpace;this.defaultTextDirection=n.direction=="rtl"?1:0;let s=this.heightOracle.mustRefreshForWrapping(o)||this.mustMeasureContent==="refresh",l=t.getBoundingClientRect(),a=s||this.mustMeasureContent||this.contentDOMHeight!=l.height;this.contentDOMHeight=l.height,this.mustMeasureContent=!1;let u=0,h=0;if(l.width&&l.height){let{scaleX:w,scaleY:x}=Pi(t,l);(w>.005&&Math.abs(this.scaleX-w)>.005||x>.005&&Math.abs(this.scaleY-x)>.005)&&(this.scaleX=w,this.scaleY=x,u|=16,s=a=!0)}let c=(parseInt(n.paddingTop)||0)*this.scaleY,f=(parseInt(n.paddingBottom)||0)*this.scaleY;(this.paddingTop!=c||this.paddingBottom!=f)&&(this.paddingTop=c,this.paddingBottom=f,u|=18),this.editorWidth!=e.scrollDOM.clientWidth&&(i.lineWrapping&&(a=!0),this.editorWidth=e.scrollDOM.clientWidth,u|=16);let m=rr(this.view.contentDOM,!1).y;m!=this.scrollParent&&(this.scrollParent=m,this.scrollAnchorHeight=-1,this.scrollOffset=0);let d=this.getScrollOffset();this.scrollOffset!=d&&(this.scrollAnchorHeight=-1,this.scrollOffset=d),this.scrolledToBottom=or(this.scrollParent||e.win);let p=(this.printing?Hu:Pu)(t,this.paddingTop),g=p.top-this.pixelViewport.top,b=p.bottom-this.pixelViewport.bottom;this.pixelViewport=p;let C=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(C!=this.inView&&(this.inView=C,C&&(a=!0)),!this.inView&&!this.scrollTarget&&!Vu(e.dom))return 0;let v=l.width;if((this.contentDOMWidth!=v||this.editorHeight!=e.scrollDOM.clientHeight)&&(this.contentDOMWidth=l.width,this.editorHeight=e.scrollDOM.clientHeight,u|=16),a){let w=e.docView.measureVisibleLineHeights(this.viewport);if(i.mustRefreshForHeights(w)&&(s=!0),s||i.lineWrapping&&Math.abs(v-this.contentDOMWidth)>i.charWidth){let{lineHeight:x,charWidth:k,textHeight:B}=e.docView.measureTextSize();s=x>0&&i.refresh(o,x,k,B,Math.max(5,v/k),w),s&&(e.docView.minWidth=0,u|=16)}g>0&&b>0?h=Math.max(g,b):g<0&&b<0&&(h=Math.min(g,b)),So();for(let x of this.viewports){let k=x.from==this.viewport.from?w:e.docView.measureVisibleLineHeights(x);this.heightMap=(s?re.empty().applyChanges(this.stateDeco,A.empty,this.heightOracle,[new he(0,0,0,e.state.doc.length)]):this.heightMap).updateHeight(i,0,s,new Ir(x.from,k))}vt&&(u|=2)}let M=!this.viewportIsAppropriate(this.viewport,h)||this.scrollTarget&&(this.scrollTarget.range.head<this.viewport.from||this.scrollTarget.range.head>this.viewport.to);return M&&(u&2&&(u|=this.updateScaler()),this.viewport=this.getViewport(h,this.scrollTarget),u|=this.updateForViewport()),(u&2||M)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(s?[]:this.lineGaps,e)),u|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,e.docView.enforceCursorAssoc()),u}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(e,t){let n=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),i=this.heightMap,o=this.heightOracle,{visibleTop:s,visibleBottom:l}=this,a=new Jt(i.lineAt(s-n*1e3,1,o,0,0).from,i.lineAt(l+(1-n)*1e3,1,o,0,0).to);if(t){let{head:u}=t.range;if(u<a.from||u>a.to){let h=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),c=i.lineAt(u,0,o,0,0),f;t.y=="center"?f=(c.top+c.bottom)/2-h/2:t.y=="start"||t.y=="nearest"&&u<a.from?f=c.top:f=c.bottom-h,a=new Jt(i.lineAt(f-1e3/2,1,o,0,0).from,i.lineAt(f+h+1e3/2,1,o,0,0).to)}}return a}mapViewport(e,t){let n=t.mapPos(e.from,-1),i=t.mapPos(e.to,1);return new Jt(this.heightMap.lineAt(n,0,this.heightOracle,0,0).from,this.heightMap.lineAt(i,0,this.heightOracle,0,0).to)}viewportIsAppropriate({from:e,to:t},n=0){if(!this.inView)return!0;let{top:i}=this.heightMap.lineAt(e,0,this.heightOracle,0,0),{bottom:o}=this.heightMap.lineAt(t,0,this.heightOracle,0,0),{visibleTop:s,visibleBottom:l}=this;return(e==0||i<=s-Math.max(10,Math.min(-n,250)))&&(t==this.state.doc.length||o>=l+Math.max(10,Math.min(n,250)))&&i>s-2*1e3&&o<l+2*1e3}mapLineGaps(e,t){if(!e.length||t.empty)return e;let n=[];for(let i of e)t.touchesRange(i.from,i.to)||n.push(new Sn(t.mapPos(i.from),t.mapPos(i.to),i.size,i.displaySize));return n}ensureLineGaps(e,t){let n=this.heightOracle.lineWrapping,i=n?1e4:2e3,o=i>>1,s=i<<1;if(this.defaultTextDirection!=0&&!n)return[];let l=[],a=(h,c,f,m)=>{if(c-h<o)return;let d=this.state.selection.main,p=[d.from];d.empty||p.push(d.to);for(let b of p)if(b>h&&b<c){a(h,b-10,f,m),a(b+10,c,f,m);return}let g=Wu(e,b=>b.from>=f.from&&b.to<=f.to&&Math.abs(b.from-h)<o&&Math.abs(b.to-c)<o&&!p.some(C=>b.from<C&&b.to>C));if(!g){if(c<f.to&&t&&n&&t.visibleRanges.some(v=>v.from<=c&&v.to>=c)){let v=t.moveToLineBoundary(y.cursor(c),!1,!0).head;v>h&&(c=v)}let b=this.gapSize(f,h,c,m),C=n||b<2e6?b:2e6;g=new Sn(h,c,b,C)}l.push(g)},u=h=>{if(h.length<s||h.type!=0)return;let c=Fu(h.from,h.to,this.stateDeco);if(c.total<s)return;let f=this.scrollTarget?this.scrollTarget.range.head:null,m,d;if(n){let p=i/this.heightOracle.lineLength*this.heightOracle.lineHeight,g,b;if(f!=null){let C=Hr(c,f),v=((this.visibleBottom-this.visibleTop)/2+p)/h.height;g=C-v,b=C+v}else g=(this.visibleTop-h.top-p)/h.height,b=(this.visibleBottom-h.top+p)/h.height;m=Vr(c,g),d=Vr(c,b)}else{let p=c.total*this.heightOracle.charWidth,g=i*this.heightOracle.charWidth,b=0;if(p>2e6)for(let x of e)x.from>=h.from&&x.from<h.to&&x.size!=x.displaySize&&x.from*this.heightOracle.charWidth+b<this.pixelViewport.left&&(b=x.size-x.displaySize);let C=this.pixelViewport.left+b,v=this.pixelViewport.right+b,M,w;if(f!=null){let x=Hr(c,f),k=((v-C)/2+g)/p;M=x-k,w=x+k}else M=(C-g)/p,w=(v+g)/p;m=Vr(c,M),d=Vr(c,w)}m>h.from&&a(h.from,m,h,c),d<h.to&&a(d,h.to,h,c)};for(let h of this.viewportLines)Array.isArray(h.type)?h.type.forEach(u):u(h);return l}gapSize(e,t,n,i){let o=Hr(i,n)-Hr(i,t);return this.heightOracle.lineWrapping?e.height*o:i.total*this.heightOracle.charWidth*o}updateLineGaps(e){Sn.same(e,this.lineGaps)||(this.lineGaps=e,this.lineGapDeco=V.set(e.map(t=>t.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(e){let t=this.stateDeco;this.lineGaps.length&&(t=t.concat(this.lineGapDeco));let n=[];N.spans(t,this.viewport.from,this.viewport.to,{span(o,s){n.push({from:o,to:s})},point(){}},20);let i=0;if(n.length!=this.visibleRanges.length)i=12;else for(let o=0;o<n.length&&!(i&8);o++){let s=this.visibleRanges[o],l=n[o];(s.from!=l.from||s.to!=l.to)&&(i|=4,e&&e.mapPos(s.from,-1)==l.from&&e.mapPos(s.to,1)==l.to||(i|=8))}return this.visibleRanges=n,i}lineBlockAt(e){return e>=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find(t=>t.from<=e&&t.to>=e)||xn(this.heightMap.lineAt(e,0,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(e){return e>=this.viewportLines[0].top&&e<=this.viewportLines[this.viewportLines.length-1].bottom&&this.viewportLines.find(t=>t.top<=e&&t.bottom>=e)||xn(this.heightMap.lineAt(this.scaler.fromDOM(e),1,this.heightOracle,0,0),this.scaler)}getScrollOffset(){return(this.scrollParent==this.view.scrollDOM?this.scrollParent.scrollTop:(this.scrollParent?this.scrollParent.getBoundingClientRect().top:0)-this.view.contentDOM.getBoundingClientRect().top)*this.scaleY}scrollAnchorAt(e){let t=this.lineBlockAtHeight(e+8);return t.from>=this.viewport.from||this.viewportLines[0].top-e>200?t:this.viewportLines[0]}elementAtHeight(e){return xn(this.heightMap.blockAt(this.scaler.fromDOM(e),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}},Jt=class{constructor(e,t){this.from=e;this.to=t}};function Fu(r,e,t){let n=[],i=r,o=0;return N.spans(t,r,e,{span(){},point(s,l){s>i&&(n.push({from:i,to:s}),o+=s-i),i=l}},20),i<e&&(n.push({from:i,to:e}),o+=e-i),{total:o,ranges:n}}function Vr({total:r,ranges:e},t){if(t<=0)return e[0].from;if(t>=1)return e[e.length-1].to;let n=Math.floor(r*t);for(let i=0;;i++){let{from:o,to:s}=e[i],l=s-o;if(n<=l)return o+n;n-=l}}function Hr(r,e){let t=0;for(let{from:n,to:i}of r.ranges){if(e<=i){t+=e-n;break}t+=i-n}return t/r.total}function Wu(r,e){for(let t of r)if(e(t))return t}var sl={toDOM(r){return r},fromDOM(r){return r},scale:1,eq(r){return r==this}};function ll(r){let e=r.facet(St).filter(n=>typeof n!="function"),t=r.facet(Ut).filter(n=>typeof n!="function");return t.length&&e.push(N.join(t)),e}var wo=class r{constructor(e,t,n){let i=0,o=0,s=0;this.viewports=n.map(({from:l,to:a})=>{let u=t.lineAt(l,0,e,0,0).top,h=t.lineAt(a,0,e,0,0).bottom;return i+=h-u,{from:l,to:a,top:u,bottom:h,domTop:0,domBottom:0}}),this.scale=(7e6-i)/(t.height-i);for(let l of this.viewports)l.domTop=s+(l.top-o)*this.scale,s=l.domBottom=l.domTop+(l.bottom-l.top),o=l.bottom}toDOM(e){for(let t=0,n=0,i=0;;t++){let o=t<this.viewports.length?this.viewports[t]:null;if(!o||e<o.top)return i+(e-n)*this.scale;if(e<=o.bottom)return o.domTop+(e-o.top);n=o.bottom,i=o.domBottom}}fromDOM(e){for(let t=0,n=0,i=0;;t++){let o=t<this.viewports.length?this.viewports[t]:null;if(!o||e<o.domTop)return n+(e-i)/this.scale;if(e<=o.domBottom)return o.top+(e-o.domTop);n=o.bottom,i=o.domBottom}}eq(e){return e instanceof r?this.scale==e.scale&&this.viewports.length==e.viewports.length&&this.viewports.every((t,n)=>t.from==e.viewports[n].from&&t.to==e.viewports[n].to):!1}};function xn(r,e){if(e.scale==1)return r;let t=e.toDOM(r.top),n=e.toDOM(r.bottom);return new xe(r.from,r.length,t,n-t,Array.isArray(r._content)?r._content.map(i=>xn(i,e)):r._content)}var wn=T.define({combine:r=>r.join(" ")}),Fr=T.define({combine:r=>r.indexOf(!0)>-1}),Wr=Pe.newName(),Co=Pe.newName(),ko=Pe.newName(),vo={"&light":"."+Co,"&dark":"."+ko};function zr(r,e,t){return new Pe(e,{finish(n){return/&/.test(n)?n.replace(/&\w*/,i=>{if(i=="&")return r;if(!t||!t[i])throw new RangeError(`Unsupported selector: ${i}`);return t[i]}):r+" "+n}})}var al=zr("."+Wr,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0,overflowAnchor:"none"},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",minHeight:"100%",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#ddd"},".cm-selectionHandle":{backgroundColor:"currentColor",width:"1.5px"},".cm-selectionHandle-start::before, .cm-selectionHandle-end::before":{content:'""',backgroundColor:"inherit",borderRadius:"50%",width:"8px",height:"8px",position:"absolute",left:"-3.25px"},".cm-selectionHandle-start::before":{top:"-8px"},".cm-selectionHandle-end::before":{bottom:"-8px"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},".cm-iso":{unicodeBidi:"isolate"},".cm-announced":{position:"fixed",top:"-10000px"},"@media print":{".cm-announced":{display:"none"}},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",zIndex:200},".cm-gutters-before":{insetInlineStart:0},".cm-gutters-after":{insetInlineEnd:0},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",border:"0px solid #ddd","&.cm-gutters-before":{borderRightWidth:"1px"},"&.cm-gutters-after":{borderLeftWidth:"1px"}},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0,zIndex:300},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-dialog":{padding:"2px 19px 4px 6px",position:"relative","& label":{fontSize:"80%"}},".cm-dialog-close":{position:"absolute",top:"3px",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",fontSize:"14px",padding:"0"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top",userSelect:"none"},".cm-highlightSpace":{backgroundImage:"radial-gradient(circle at 50% 55%, #aaa 20%, transparent 5%)",backgroundPosition:"center"},".cm-highlightTab":{backgroundImage:`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="20"><path stroke="%23888" stroke-width="1" fill="none" d="M1 10H196L190 5M190 15L196 10M197 4L197 16"/></svg>')`,backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},vo);var zu={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},Mo=S.ie&&S.ie_version<=11,Kr=class{constructor(e){this.view=e;this.active=!1;this.editContext=null;this.selectionRange=new tr;this.selectionChanged=!1;this.delayedFlush=-1;this.resizeTimeout=-1;this.queue=[];this.delayedAndroidKey=null;this.flushingAndroidKey=-1;this.lastChange=0;this.scrollTargets=[];this.intersection=null;this.resizeScroll=null;this.intersecting=!1;this.gapIntersection=null;this.gaps=[];this.printQuery=null;this.parentCheck=-1;this.dom=e.contentDOM,this.observer=new MutationObserver(t=>{for(let n of t)this.queue.push(n);(S.ie&&S.ie_version<=11||S.ios&&e.composing)&&t.some(n=>n.type=="childList"&&n.removedNodes.length||n.type=="characterData"&&n.oldValue.length>n.target.nodeValue.length)?this.flushSoon():this.flush()}),window.EditContext&&S.android&&e.constructor.EDIT_CONTEXT!==!1&&!(S.chrome&&S.chrome_version<126)&&(this.editContext=new Eo(e),e.state.facet(ce)&&(e.contentDOM.editContext=this.editContext.editContext)),Mo&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),window.matchMedia&&(this.printQuery=window.matchMedia("print")),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{this.view.docView?.lastUpdate<Date.now()-75&&this.onResize()}),this.resizeScroll.observe(e.scrollDOM)),this.addWindowListeners(this.win=e.win),this.start(),typeof IntersectionObserver=="function"&&(this.intersection=new IntersectionObserver(t=>{this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),t.length>0&&t[t.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))},{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(t=>{t.length>0&&t[t.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))},{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers("scroll",e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.editContext&&this.view.requestMeasure(this.editContext.measureReq),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(e){(e.type=="change"||!e.type)&&!e.matches||(this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,this.view.requestMeasure()},500))}updateGaps(e){if(this.gapIntersection&&(e.length!=this.gaps.length||this.gaps.some((t,n)=>t!=e[n]))){this.gapIntersection.disconnect();for(let t of e)this.gapIntersection.observe(t);this.gaps=e}}onSelectionChange(e){let t=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:n}=this,i=this.selectionRange;if(n.state.facet(ce)?n.root.activeElement!=this.dom:!Ye(this.dom,i))return;let o=i.anchorNode&&n.docView.tile.nearest(i.anchorNode);if(o&&o.isWidget()&&o.widget.ignoreEvent(e)){t||(this.selectionChanged=!1);return}(S.ie&&S.ie_version<=11||S.android&&S.chrome)&&!n.state.selection.main.empty&&i.focusNode&&bt(i.focusNode,i.focusOffset,i.anchorNode,i.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,t=$e(e.root);if(!t)return!1;let n=S.safari&&e.root.nodeType==11&&e.root.activeElement==this.dom&&Ku(this.view,t)||t;if(!n||this.selectionRange.eq(n))return!1;let i=Ye(this.dom,n);return i&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime<Date.now()-300&&Ds(this.dom,n)?(this.view.inputState.lastFocusTime=0,e.docView.updateSelection(),!1):(this.selectionRange.setRange(n),i&&(this.selectionChanged=!0),!0)}setSelectionRange(e,t){this.selectionRange.set(e.node,e.offset,t.node,t.offset),this.selectionChanged=!1}clearSelectionRange(){this.selectionRange.set(null,0,null,0)}listenForScroll(){this.parentCheck=-1;let e=0,t=null;for(let n=this.dom;n;)if(n.nodeType==1)!t&&e<this.scrollTargets.length&&this.scrollTargets[e]==n?e++:t||(t=this.scrollTargets.slice(0,e)),t&&t.push(n),n=n.assignedSlot||n.parentNode;else if(n.nodeType==11)n=n.host;else break;if(e<this.scrollTargets.length&&!t&&(t=this.scrollTargets.slice(0,e)),t){for(let n of this.scrollTargets)n.removeEventListener("scroll",this.onScroll);for(let n of this.scrollTargets=t)n.addEventListener("scroll",this.onScroll)}}ignore(e){if(!this.active)return e();try{return this.stop(),e()}finally{this.start(),this.clear()}}start(){this.active||(this.observer.observe(this.dom,zu),Mo&&this.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.active=!0)}stop(){this.active&&(this.active=!1,this.observer.disconnect(),Mo&&this.dom.removeEventListener("DOMCharacterDataModified",this.onCharData))}clear(){this.processRecords(),this.queue.length=0,this.selectionChanged=!1}delayAndroidKey(e,t){if(!this.delayedAndroidKey){let n=()=>{let i=this.delayedAndroidKey;i&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=i.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&i.force&&He(this.dom,i.key,i.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(n)}(!this.delayedAndroidKey||e=="Enter")&&(this.delayedAndroidKey={key:e,keyCode:t,force:this.lastChange<Date.now()-50||!!this.delayedAndroidKey?.force})}clearDelayedAndroidKey(){this.win.cancelAnimationFrame(this.flushingAndroidKey),this.delayedAndroidKey=null,this.flushingAndroidKey=-1}flushSoon(){this.delayedFlush<0&&(this.delayedFlush=this.view.win.requestAnimationFrame(()=>{this.delayedFlush=-1,this.flush()}))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}processRecords(){let e=this.pendingRecords();e.length&&(this.queue=[]);let t=-1,n=-1,i=!1;for(let o of e){let s=this.readMutation(o);s&&(s.typeOver&&(i=!0),t==-1?{from:t,to:n}=s:(t=Math.min(s.from,t),n=Math.max(s.to,n)))}return{from:t,to:n,typeOver:i}}readChange(){let{from:e,to:t,typeOver:n}=this.processRecords(),i=this.selectionChanged&&Ye(this.dom,this.selectionRange);if(e<0&&!i)return null;e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let o=new Mr(this.view,e,t,n);return this.view.docView.domChanged={newSel:o.newSel?o.newSel.main:null},o}flush(e=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;e&&this.readSelectionRange();let t=this.readChange();if(!t)return this.view.requestMeasure(),!1;let n=this.view.state,i=Er(this.view,t);return this.view.state==n&&(t.domChanged||t.newSel&&!bn(this.view.state.selection,t.newSel.main))&&this.view.update([]),i}readMutation(e){let t=this.view.docView.tile.nearest(e.target);if(!t||t.isWidget())return null;if(t.markDirty(e.type=="attributes"),e.type=="childList"){let n=ul(t,e.previousSibling||e.target.previousSibling,-1),i=ul(t,e.nextSibling||e.target.nextSibling,1);return{from:n?t.posAfter(n):t.posAtStart,to:i?t.posBefore(i):t.posAtEnd,typeOver:!1}}else return e.type=="characterData"?{from:t.posAtStart,to:t.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}:null}setWindow(e){e!=this.win&&(this.removeWindowListeners(this.win),this.win=e,this.addWindowListeners(this.win))}addWindowListeners(e){e.addEventListener("resize",this.onResize),this.printQuery?this.printQuery.addEventListener?this.printQuery.addEventListener("change",this.onPrint):this.printQuery.addListener(this.onPrint):e.addEventListener("beforeprint",this.onPrint),e.addEventListener("scroll",this.onScroll),e.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(e){e.removeEventListener("scroll",this.onScroll),e.removeEventListener("resize",this.onResize),this.printQuery?this.printQuery.removeEventListener?this.printQuery.removeEventListener("change",this.onPrint):this.printQuery.removeListener(this.onPrint):e.removeEventListener("beforeprint",this.onPrint),e.document.removeEventListener("selectionchange",this.onSelectionChange)}update(e){this.editContext&&(this.editContext.update(e),e.startState.facet(ce)!=e.state.facet(ce)&&(e.view.contentDOM.editContext=e.state.facet(ce)?this.editContext.editContext:null))}destroy(){this.stop(),this.intersection?.disconnect(),this.gapIntersection?.disconnect(),this.resizeScroll?.disconnect();for(let e of this.scrollTargets)e.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey),this.editContext&&(this.view.contentDOM.editContext=null,this.editContext.destroy())}};function ul(r,e,t){for(;e;){let n=O.get(e);if(n&&n.parent==r)return n;let i=e.parentNode;e=i!=r.dom?i:t>0?e.nextSibling:e.previousSibling}return null}function hl(r,e){let t=e.startContainer,n=e.startOffset,i=e.endContainer,o=e.endOffset,s=r.docView.domAtPos(r.state.selection.main.anchor,1);return bt(s.node,s.offset,i,o)&&([t,n,i,o]=[i,o,t,n]),{anchorNode:t,anchorOffset:n,focusNode:i,focusOffset:o}}function Ku(r,e){if(e.getComposedRanges){let i=e.getComposedRanges(r.root)[0];if(i)return hl(r,i)}let t=null;function n(i){i.preventDefault(),i.stopImmediatePropagation(),t=i.getTargetRanges()[0]}return r.contentDOM.addEventListener("beforeinput",n,!0),r.dom.ownerDocument.execCommand("indent"),r.contentDOM.removeEventListener("beforeinput",n,!0),t?hl(r,t):null}var Eo=class{constructor(e){this.from=0;this.to=0;this.pendingContextChange=null;this.handlers=Object.create(null);this.composing=null;this.resetRange(e.state);let t=this.editContext=new window.EditContext({text:e.state.doc.sliceString(this.from,this.to),selectionStart:this.toContextPos(Math.max(this.from,Math.min(this.to,e.state.selection.main.anchor))),selectionEnd:this.toContextPos(e.state.selection.main.head)});this.handlers.textupdate=n=>{let i=e.state.selection.main,{anchor:o,head:s}=i,l=this.toEditorPos(n.updateRangeStart),a=this.toEditorPos(n.updateRangeEnd);e.inputState.composing>=0&&!this.composing&&(this.composing={contextBase:n.updateRangeStart,editorBase:l,drifted:!1});let u=a-l>n.text.length;l==this.from&&o<this.from?l=o:a==this.to&&o>this.to&&(a=o);let h=ho(e.state.sliceDoc(l,a),n.text,(u?i.from:i.to)-l,u?"end":null);if(!h){let f=y.single(this.toEditorPos(n.selectionStart),this.toEditorPos(n.selectionEnd));bn(f,i)||e.dispatch({selection:f,userEvent:"select"});return}let c={from:h.from+l,to:h.toA+l,insert:A.of(n.text.slice(h.from,h.toB).split(`
+`))};if((S.mac||S.android)&&c.from==s-1&&/^\. ?$/.test(n.text)&&e.contentDOM.getAttribute("autocorrect")=="off"&&(c={from:l,to:a,insert:A.of([n.text.replace("."," ")])}),this.pendingContextChange=c,!e.state.readOnly){let f=this.to-this.from+(c.to-c.from+c.insert.length);yn(e,c,y.single(this.toEditorPos(n.selectionStart,f),this.toEditorPos(n.selectionEnd,f)))}this.pendingContextChange&&(this.revertPending(e.state),this.setSelection(e.state)),c.from<c.to&&!c.insert.length&&e.inputState.composing>=0&&!/[\\p{Alphabetic}\\p{Number}_]/.test(t.text.slice(Math.max(0,n.updateRangeStart-1),Math.min(t.text.length,n.updateRangeStart+1)))&&this.handlers.compositionend(n)},this.handlers.characterboundsupdate=n=>{let i=[],o=null;for(let s=this.toEditorPos(n.rangeStart),l=this.toEditorPos(n.rangeEnd);s<l;s++){let a=e.coordsForChar(s);o=a&&new DOMRect(a.left,a.top,a.right-a.left,a.bottom-a.top)||o||new DOMRect,i.push(o)}t.updateCharacterBounds(n.rangeStart,i)},this.handlers.textformatupdate=n=>{let i=[];for(let o of n.getTextFormats()){let s=o.underlineStyle,l=o.underlineThickness;if(!/none/i.test(s)&&!/none/i.test(l)){let a=this.toEditorPos(o.rangeStart),u=this.toEditorPos(o.rangeEnd);if(a<u){let h=`text-decoration: underline ${/^[a-z]/.test(s)?s+" ":s=="Dashed"?"dashed ":s=="Squiggle"?"wavy ":""}${/thin/i.test(l)?1:2}px`;i.push(V.mark({attributes:{style:h}}).range(a,u))}}}e.dispatch({effects:mr.of(V.set(i))})},this.handlers.compositionstart=()=>{e.inputState.composing<0&&(e.inputState.composing=0,e.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{if(e.inputState.composing=-1,e.inputState.compositionFirstChange=null,this.composing){let{drifted:n}=this.composing;this.composing=null,n&&this.reset(e.state)}};for(let n in this.handlers)t.addEventListener(n,this.handlers[n]);this.measureReq={read:n=>{this.editContext.updateControlBounds(n.contentDOM.getBoundingClientRect());let i=$e(n.root);i&&i.rangeCount&&this.editContext.updateSelectionBounds(i.getRangeAt(0).getBoundingClientRect())}}}applyEdits(e){let t=0,n=!1,i=this.pendingContextChange;return e.changes.iterChanges((o,s,l,a,u)=>{if(n)return;let h=u.length-(s-o);if(i&&s>=i.to)if(i.from==o&&i.to==s&&i.insert.eq(u)){i=this.pendingContextChange=null,t+=h,this.to+=h;return}else i=null,this.revertPending(e.state);if(o+=t,s+=t,s<=this.from)this.from+=h,this.to+=h;else if(o<this.to){if(o<this.from||s>this.to||this.to-this.from+u.length>3e4){n=!0;return}this.editContext.updateText(this.toContextPos(o),this.toContextPos(s),u.toString()),this.to+=h}t+=h}),i&&!n&&this.revertPending(e.state),!n}update(e){let t=this.pendingContextChange,n=e.startState.selection.main;this.composing&&(this.composing.drifted||!e.changes.touchesRange(n.from,n.to)&&e.transactions.some(i=>!i.isUserEvent("input.type")&&i.changes.touchesRange(this.from,this.to)))?(this.composing.drifted=!0,this.composing.editorBase=e.changes.mapPos(this.composing.editorBase)):!this.applyEdits(e)||!this.rangeIsValid(e.state)?(this.pendingContextChange=null,this.reset(e.state)):(e.docChanged||e.selectionSet||t)&&this.setSelection(e.state),(e.geometryChanged||e.docChanged||e.selectionSet)&&e.view.requestMeasure(this.measureReq)}resetRange(e){let{head:t}=e.selection.main;this.from=Math.max(0,t-1e4),this.to=Math.min(e.doc.length,t+1e4)}reset(e){this.resetRange(e),this.editContext.updateText(0,this.editContext.text.length,e.doc.sliceString(this.from,this.to)),this.setSelection(e)}revertPending(e){let t=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(t.from),this.toContextPos(t.from+t.insert.length),e.doc.sliceString(t.from,t.to))}setSelection(e){let{main:t}=e.selection,n=this.toContextPos(Math.max(this.from,Math.min(this.to,t.anchor))),i=this.toContextPos(t.head);(this.editContext.selectionStart!=n||this.editContext.selectionEnd!=i)&&this.editContext.updateSelection(n,i)}rangeIsValid(e){let{head:t}=e.selection.main;return!(this.from>0&&t-this.from<500||this.to<e.doc.length&&this.to-t<500||this.to-this.from>1e4*3)}toEditorPos(e,t=this.to-this.from){e=Math.min(e,t);let n=this.composing;return n&&n.drifted?n.editorBase+(e-n.contextBase):e+this.from}toContextPos(e){let t=this.composing;return t&&t.drifted?t.contextBase+(e-t.editorBase):e-this.from}destroy(){for(let e in this.handlers)this.editContext.removeEventListener(e,this.handlers[e])}};var K=class r{constructor(e={}){this.plugins=[];this.pluginMap=new Map;this.editorAttrs={};this.contentAttrs={};this.bidiCache=[];this.destroyed=!1;this.updateState=2;this.measureScheduled=-1;this.measureRequests=[];this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.className="cm-announced",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),e.parent&&e.parent.appendChild(this.dom);let{dispatch:t}=e;this.dispatchTransactions=e.dispatchTransactions||t&&(n=>n.forEach(i=>t(i,this)))||(n=>this.update(n)),this.dispatch=this.dispatch.bind(this),this._root=e.root||As(e.parent)||document,this.viewState=new Tn(this,e.state||j.create(e)),e.scrollTo&&e.scrollTo.is(fn)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(xt).map(n=>new zt(n));for(let n of this.plugins)n.update(this);this.observer=new Kr(this),this.inputState=new Br(this),this.inputState.ensureHandlers(this.plugins),this.docView=new pn(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),document.fonts?.ready&&document.fonts.ready.then(()=>{this.viewState.mustMeasureContent="refresh",this.requestMeasure()})}get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return!!this.inputState&&this.inputState.composing>0}get compositionStarted(){return!!this.inputState&&this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}dispatch(...e){let t=e.length==1&&e[0]instanceof X?e:e.length==1&&Array.isArray(e[0])?e[0]:[this.state.update(...e)];this.dispatchTransactions(t,this)}update(e){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let t=!1,n=!1,i,o=this.state;for(let f of e){if(f.startState!=o)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");o=f.state}if(this.destroyed){this.viewState.state=o;return}let s=this.hasFocus,l=0,a=null;e.some(f=>f.annotation(po))?(this.inputState.notifiedFocused=s,l=1):s!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=s,a=go(o,s),a||(l=1));let u=this.observer.delayedAndroidKey,h=null;if(u?(this.observer.clearDelayedAndroidKey(),h=this.observer.readChange(),(h&&!this.state.doc.eq(o.doc)||!this.state.selection.eq(o.selection))&&(h=null)):this.observer.clear(),o.facet(j.phrases)!=this.state.facet(j.phrases))return this.setState(o);i=Kt.create(this,o,e),i.flags|=l;let c=this.viewState.scrollTarget;try{this.updateState=2;for(let f of e){if(c&&(c=c.map(f.changes)),f.scrollIntoView){let{main:m}=f.state.selection,{x:d,y:p}=this.state.facet(r.cursorScrollMargin);c=new Wt(m.empty?m:y.cursor(m.head,m.head>m.anchor?-1:1),"nearest","nearest",p,d)}for(let m of f.effects)m.is(fn)&&(c=m.value.clip(this.state))}this.viewState.update(i,c),this.bidiCache=Ur.update(this.bidiCache,i.changes),i.empty||(this.updatePlugins(i),this.inputState.update(i)),t=this.docView.update(i),this.state.facet(qt)!=this.styleModules&&this.mountStyles(),n=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(t,e.some(f=>f.isUserEvent("select.pointer")))}finally{this.updateState=0}if(i.startState.facet(wn)!=i.state.facet(wn)&&(this.viewState.mustMeasureContent=!0),(t||n||c||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),t&&this.docViewUpdate(),!i.empty)for(let f of this.state.facet(ur))try{f(i)}catch(m){_(this.state,m,"update listener")}(a||h)&&Promise.resolve().then(()=>{a&&this.state==a.startState&&this.dispatch(a),h&&!Er(this,h)&&u.force&&He(this.contentDOM,u.key,u.keyCode)})}setState(e){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=e;return}this.updateState=2;let t=this.hasFocus;try{for(let n of this.plugins)n.destroy(this);this.viewState=new Tn(this,e),this.plugins=e.facet(xt).map(n=>new zt(n)),this.pluginMap.clear();for(let n of this.plugins)n.update(this);this.docView.destroy(),this.docView=new pn(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}t&&this.focus(),this.requestMeasure()}updatePlugins(e){let t=e.startState.facet(xt),n=e.state.facet(xt);if(t!=n){let i=[];for(let o of n){let s=t.indexOf(o);if(s<0)i.push(new zt(o));else{let l=this.plugins[s];l.mustUpdate=e,i.push(l)}}for(let o of this.plugins)o.mustUpdate!=e&&o.destroy(this);this.plugins=i,this.pluginMap.clear()}else for(let i of this.plugins)i.mustUpdate=e;for(let i=0;i<this.plugins.length;i++)this.plugins[i].update(this);t!=n&&this.inputState.ensureHandlers(this.plugins)}docViewUpdate(){for(let e of this.plugins){let t=e.value;if(t&&t.docViewUpdate)try{t.docViewUpdate(this)}catch(n){_(this.state,n,"doc view update listener")}}}measure(e=!0){if(this.destroyed)return;if(this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,e&&this.observer.forceFlush();let t=null,n=this.viewState.scrollParent,i=this.viewState.getScrollOffset(),{scrollAnchorPos:o,scrollAnchorHeight:s}=this.viewState;Math.abs(i-this.viewState.scrollOffset)>1&&(s=-1),this.viewState.scrollAnchorHeight=-1;try{for(let l=0;;l++){if(s<0)if(or(n||this.win))o=-1,s=this.viewState.heightMap.height;else{let m=this.viewState.scrollAnchorAt(i);o=m.from,s=m.top}this.updateState=1;let a=this.viewState.measure();if(!a&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(l>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let u=[];a&4||([this.measureRequests,u]=[u,this.measureRequests]);let h=u.map(m=>{try{return m.read(this)}catch(d){return _(this.state,d),cl}}),c=Kt.create(this,this.state,[]),f=!1;c.flags|=a,t?t.flags|=a:t=c,this.updateState=2,c.empty||(this.updatePlugins(c),this.inputState.update(c),this.updateAttrs(),f=this.docView.update(c),f&&this.docViewUpdate());for(let m=0;m<u.length;m++)if(h[m]!=cl)try{let d=u[m];d.write&&d.write(h[m],this)}catch(d){_(this.state,d)}if(f&&this.docView.updateSelection(!0),!c.viewportChanged&&this.measureRequests.length==0){if(this.viewState.editorHeight)if(this.viewState.scrollTarget){this.docView.scrollIntoView(this.viewState.scrollTarget),this.viewState.scrollTarget=null,s=-1;continue}else{let d=((o<0?this.viewState.heightMap.height:this.viewState.lineBlockAt(o).top)-s)/this.scaleY;if((d>1||d<-1)&&(n==this.scrollDOM||this.hasFocus||Math.max(this.inputState.lastWheelEvent,this.inputState.lastTouchTime)>Date.now()-100)){i=i+d,n?n.scrollTop+=d:this.win.scrollBy(0,d),s=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(t&&!t.empty)for(let l of this.state.facet(ur))l(t)}get themeClasses(){return Wr+" "+(this.state.facet(Fr)?ko:Co)+" "+this.state.facet(wn)}updateAttrs(){let e=fl(this,$i,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),t={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",translate:"no",contenteditable:this.state.facet(ce)?"true":"false",class:"cm-content",style:`${S.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(t["aria-readonly"]="true"),fl(this,dn,t);let n=this.observer.ignore(()=>{let i=Ni(this.contentDOM,this.contentAttrs,t),o=Ni(this.dom,this.editorAttrs,e);return i||o});return this.editorAttrs=e,this.contentAttrs=t,n}showAnnouncements(e){let t=!0;for(let n of e)for(let i of n.effects)if(i.is(r.announce)){t&&(this.announceDOM.textContent=""),t=!1;let o=this.announceDOM.appendChild(document.createElement("div"));o.textContent=i.value}}mountStyles(){this.styleModules=this.state.facet(qt);let e=this.state.facet(r.cspNonce);Pe.mount(this.root,this.styleModules.concat(al).reverse(),e?{nonce:e}:void 0)}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),e){if(this.measureRequests.indexOf(e)>-1)return;if(e.key!=null){for(let t=0;t<this.measureRequests.length;t++)if(this.measureRequests[t].key===e.key){this.measureRequests[t]=e;return}}this.measureRequests.push(e)}}plugin(e){let t=this.pluginMap.get(e);return(t===void 0||t&&t.plugin!=e)&&this.pluginMap.set(e,t=this.plugins.find(n=>n.plugin==e)||null),t&&t.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,t,n){return Cr(this,e,uo(this,e,t,n))}moveByGroup(e,t){return Cr(this,e,uo(this,e,t,n=>zs(this,e.head,n)))}visualLineSide(e,t){let n=this.bidiSpans(e),i=this.textDirectionAt(e.from),o=n[t?n.length-1:0];return y.cursor(o.side(t,i)+e.from,o.forward(!t,i)?1:-1)}moveToLineBoundary(e,t,n=!0){return Ws(this,e,t,n)}moveVertically(e,t,n){return Cr(this,e,Ks(this,e,t,n))}domAtPos(e,t=1){return this.docView.domAtPos(e,t)}posAtDOM(e,t=0){return this.docView.posFromDOM(e,t)}posAtCoords(e,t=!0){this.readMeasured();let n=kr(this,e,t);return n&&n.pos}posAndSideAtCoords(e,t=!0){return this.readMeasured(),kr(this,e,t)}coordsAtPos(e,t=1){this.readMeasured();let n=this.docView.coordsAt(e,t);if(!n||n.left==n.right)return n;let i=this.state.doc.lineAt(e),o=this.bidiSpans(i),s=o[te.find(o,e-i.from,-1,t)];return Ft(n,s.dir==0==t>0)}coordsForChar(e){return this.readMeasured(),this.docView.coordsForChar(e)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet(Ji)||e<this.viewport.from||e>this.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>Uu)return qi(e.length);let t=this.textDirectionAt(e.from),n;for(let o of this.bidiCache)if(o.from==e.from&&o.dir==t&&(o.fresh||Ui(o.isolates,n=Xi(this,e))))return o.order;n||(n=Xi(this,e));let i=Os(e.text,t,n);return this.bidiCache.push(new Ur(e.from,e.to,t,n,!0,i)),i}get hasFocus(){return(this.dom.ownerDocument.hasFocus()||S.safari&&this.inputState?.lastContextMenu>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{ir(this.contentDOM),this.docView.updateSelection()})}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((e.nodeType==9?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){this.root.activeElement==this.contentDOM&&this.contentDOM.blur();for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,t={}){return fn.of(new Wt(typeof e=="number"?y.cursor(e):e,t.y??"nearest",t.x??"nearest",t.yMargin??5,t.xMargin??5))}scrollSnapshot(){let{scrollTop:e,scrollLeft:t}=this.scrollDOM,n=this.viewState.scrollAnchorAt(e);return fn.of(new Wt(y.cursor(n.from),"start","start",n.top-e,t,!0))}setTabFocusMode(e){e==null?this.inputState.tabFocusMode=this.inputState.tabFocusMode<0?0:-1:typeof e=="boolean"?this.inputState.tabFocusMode=e?0:-1:this.inputState.tabFocusMode!=0&&(this.inputState.tabFocusMode=Date.now()+e)}static{this.styleModule=qt}static domEventHandlers(e){return ge.define(()=>({}),{eventHandlers:e})}static domEventObservers(e){return ge.define(()=>({}),{eventObservers:e})}static{this.inputHandler=hr}static{this.clipboardInputFilter=hn}static{this.clipboardOutputFilter=cn}static{this.scrollHandler=dr}static{this.focusChangeEffect=cr}static{this.perLineTextDirection=Ji}static{this.exceptionSink=ji}static{this.updateListener=ur}static{this.editable=ce}static{this.mouseSelectionStyle=ar}static{this.dragMovesSelection=lr}static{this.clickAddsSelectionRange=sr}static{this.decorations=St}static{this.blockWrappers=pr}static{this.outerDecorations=Ut}static{this.atomicRanges=ze}static{this.bidiIsolatedRanges=Yi}static{this.cursorScrollMargin=T.define({combine:e=>{let t=5,n=5;for(let i of e)typeof i=="number"?t=n=i:{x:t,y:n}=i;return{x:t,y:n}}})}static{this.scrollMargins=Qi}static theme(e,t){let n=Pe.newName(),i=[wn.of(n),qt.of(zr(`.${n}`,e))];return t&&t.dark&&i.push(Fr.of(!0)),i}static{this.darkTheme=Fr}static baseTheme(e){return ct.lowest(qt.of(zr("."+Wr,e,vo)))}static{this.cspNonce=T.define({combine:e=>e.length?e[0]:""})}static{this.contentAttributes=dn}static{this.editorAttributes=$i}static{this.lineWrapping=r.contentAttributes.of({class:"cm-lineWrapping"})}static{this.announce=W.define()}static findFromDOM(e){let t=e.querySelector(".cm-content");return(t&&O.get(t)||O.get(e))?.root?.view||null}},Uu=4096,cl={},Ur=class r{constructor(e,t,n,i,o,s){this.from=e;this.to=t;this.dir=n;this.isolates=i;this.fresh=o;this.order=s}static update(e,t){if(t.empty&&!e.some(o=>o.fresh))return e;let n=[],i=e.length?e[e.length-1].dir:0;for(let o=Math.max(0,e.length-10);o<e.length;o++){let s=e[o];s.dir==i&&!t.touchesRange(s.from,s.to)&&n.push(new r(t.mapPos(s.from,1),t.mapPos(s.to,-1),s.dir,s.isolates,!1,s.order))}return n}};function fl(r,e,t){for(let n=r.state.facet(e),i=n.length-1;i>=0;i--){let o=n[i],s=typeof o=="function"?o(r):o;s&&Pt(s,t)}return t}var Ke={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},$t={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},qu=typeof navigator<"u"&&/Mac/.test(navigator.platform),Gu=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(U=0;U<10;U++)Ke[48+U]=Ke[96+U]=String(U);var U;for(U=1;U<=24;U++)Ke[U+111]="F"+U;var U;for(U=65;U<=90;U++)Ke[U]=String.fromCharCode(U+32),$t[U]=String.fromCharCode(U);var U;for(qr in Ke)$t.hasOwnProperty(qr)||($t[qr]=Ke[qr]);var qr;function dl(r){var e=qu&&r.metaKey&&r.shiftKey&&!r.ctrlKey&&!r.altKey||Gu&&r.shiftKey&&r.key&&r.key.length==1||r.key=="Unidentified",t=!e&&r.key||(r.shiftKey?$t:Ke)[r.keyCode]||r.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}var ju=S.mac?"mac":S.windows?"win":S.linux?"linux":"key";function Ju(r,e){let t=r.split(/-(?!$)/),n=t[t.length-1];n=="Space"&&(n=" ");let i,o,s,l;for(let a=0;a<t.length-1;++a){let u=t[a];if(/^(cmd|meta|m)$/i.test(u))l=!0;else if(/^a(lt)?$/i.test(u))i=!0;else if(/^(c|ctrl|control)$/i.test(u))o=!0;else if(/^s(hift)?$/i.test(u))s=!0;else if(/^mod$/i.test(u))e=="mac"?l=!0:o=!0;else throw new Error("Unrecognized modifier name: "+u)}return i&&(n="Alt-"+n),o&&(n="Ctrl-"+n),l&&(n="Meta-"+n),s&&(n="Shift-"+n),n}function Gr(r,e,t){return e.altKey&&(r="Alt-"+r),e.ctrlKey&&(r="Ctrl-"+r),e.metaKey&&(r="Meta-"+r),t!==!1&&e.shiftKey&&(r="Shift-"+r),r}var $u=ct.default(K.domEventHandlers({keydown(r,e){return Zu(Yu(e.state),r,e,"editor")}})),Do=T.define({enables:$u}),ml=new WeakMap;function Yu(r){let e=r.facet(Do),t=ml.get(e);return t||ml.set(e,t=Qu(e.reduce((n,i)=>n.concat(i),[]))),t}var tt=null,Xu=4e3;function Qu(r,e=ju){let t=Object.create(null),n=Object.create(null),i=(s,l)=>{let a=n[s];if(a==null)n[s]=l;else if(a!=l)throw new Error("Key binding "+s+" is used both as a regular binding and as a multi-stroke prefix")},o=(s,l,a,u,h)=>{let c=t[s]||(t[s]=Object.create(null)),f=l.split(/ (?!$)/).map(p=>Ju(p,e));for(let p=1;p<f.length;p++){let g=f.slice(0,p).join(" ");i(g,!0),c[g]||(c[g]={preventDefault:!0,stopPropagation:!1,run:[b=>{let C=tt={view:b,prefix:g,scope:s};return setTimeout(()=>{tt==C&&(tt=null)},Xu),!0}]})}let m=f.join(" ");i(m,!1);let d=c[m]||(c[m]={preventDefault:!1,stopPropagation:!1,run:c._any?.run?.slice()||[]});a&&d.run.push(a),u&&(d.preventDefault=!0),h&&(d.stopPropagation=!0)};for(let s of r){let l=s.scope?s.scope.split(" "):["editor"];if(s.any)for(let u of l){let h=t[u]||(t[u]=Object.create(null));h._any||(h._any={preventDefault:!1,stopPropagation:!1,run:[]});let{any:c}=s;for(let f in h)h[f].run.push(m=>c(m,Ao))}let a=s[e]||s.key;if(a)for(let u of l)o(u,a,s.run,s.preventDefault,s.stopPropagation),s.shift&&o(u,"Shift-"+a,s.shift,s.preventDefault,s.stopPropagation)}return t}var Ao=null;function Zu(r,e,t,n){Ao=e;let i=dl(e),o=hi(i,0),s=ci(o)==i.length&&i!=" ",l="",a=!1,u=!1,h=!1;tt&&tt.view==t&&tt.scope==n&&(l=tt.prefix+" ",mo.indexOf(e.keyCode)<0&&(u=!0,tt=null));let c=new Set,f=g=>{if(g){for(let b of g.run)if(!c.has(b)&&(c.add(b),b(t)))return g.stopPropagation&&(h=!0),!0;g.preventDefault&&(g.stopPropagation&&(h=!0),u=!0)}return!1},m=r[n],d,p;return m&&(f(m[l+Gr(i,e,!s)])?a=!0:s&&(e.altKey||e.metaKey||e.ctrlKey)&&!(S.windows&&e.ctrlKey&&e.altKey)&&!(S.mac&&e.altKey&&!(e.ctrlKey||e.metaKey))&&(d=Ke[e.keyCode])&&d!=i?(f(m[l+Gr(d,e,!0)])||e.shiftKey&&(p=$t[e.keyCode])!=i&&p!=d&&f(m[l+Gr(p,e,!1)]))&&(a=!0):s&&e.shiftKey&&f(m[l+Gr(i,e,!0)])&&(a=!0),!a&&f(m._any)&&(a=!0)),u&&(a=!0),a&&h&&e.stopPropagation(),Ao=null,a}var nt=class r{constructor(e,t,n,i,o){this.className=e;this.left=t;this.top=n;this.width=i;this.height=o}draw(){let e=document.createElement("div");return e.className=this.className,this.adjust(e),e}update(e,t){return t.className!=this.className?!1:(this.adjust(e),!0)}adjust(e){e.style.left=this.left+"px",e.style.top=this.top+"px",this.width!=null&&(e.style.width=this.width+"px"),e.style.height=this.height+"px"}eq(e){return this.left==e.left&&this.top==e.top&&this.width==e.width&&this.height==e.height&&this.className==e.className}static forRange(e,t,n){if(n.empty){let i=e.coordsAtPos(n.head,n.assoc||1);if(!i)return[];let o=gl(e);return[new r(t,i.left-o.left,i.top-o.top,null,i.bottom-i.top)]}else return _u(e,t,n)}};function gl(r){let e=r.scrollDOM.getBoundingClientRect();return{left:(r.textDirection==0?e.left:e.right-r.scrollDOM.clientWidth*r.scaleX)-r.scrollDOM.scrollLeft*r.scaleX,top:e.top-r.scrollDOM.scrollTop*r.scaleY}}function pl(r,e,t,n){let i=r.coordsAtPos(e,t*2);if(!i)return n;let o=r.dom.getBoundingClientRect(),s=(i.top+i.bottom)/2,l=r.posAtCoords({x:o.left+1,y:s}),a=r.posAtCoords({x:o.right-1,y:s});return l==null||a==null?n:{from:Math.max(n.from,Math.min(l,a)),to:Math.min(n.to,Math.max(l,a))}}function _u(r,e,t){if(t.to<=r.viewport.from||t.from>=r.viewport.to)return[];let n=Math.max(t.from,r.viewport.from),i=Math.min(t.to,r.viewport.to),o=r.textDirection==0,s=r.contentDOM,l=s.getBoundingClientRect(),a=gl(r),u=s.querySelector(".cm-line"),h=u&&window.getComputedStyle(u),c=l.left+(h?parseInt(h.paddingLeft)+Math.min(0,parseInt(h.textIndent)):0),f=l.right-(h?parseInt(h.paddingRight):0),m=Tr(r,n,1),d=Tr(r,i,-1),p=m.type==0?m:null,g=d.type==0?d:null;if(p&&(r.lineWrapping||m.widgetLineBreaks)&&(p=pl(r,n,1,p)),g&&(r.lineWrapping||d.widgetLineBreaks)&&(g=pl(r,i,-1,g)),p&&g&&p.from==g.from&&p.to==g.to)return C(v(t.from,t.to,p));{let w=p?v(t.from,null,p):M(m,!1),x=g?v(null,t.to,g):M(d,!0),k=[];return(p||m).to<(g||d).from-(p&&g?1:0)||m.widgetLineBreaks>1&&w.bottom+r.defaultLineHeight/2<x.top?k.push(b(c,w.bottom,f,x.top)):w.bottom<x.top&&r.elementAtHeight((w.bottom+x.top)/2).type==0&&(w.bottom=x.top=(w.bottom+x.top)/2),C(w).concat(k).concat(C(x))}function b(w,x,k,B){return new nt(e,w-a.left,x-a.top,Math.max(0,k-w),B-x)}function C({top:w,bottom:x,horizontal:k}){let B=[];for(let R=0;R<k.length;R+=2)B.push(b(k[R],w,k[R+1],x));return B}function v(w,x,k){let B=1e9,R=-1e9,D=[];function E(F,J,fe,de,ie){let me=r.coordsAtPos(F,F==k.to?-2:2),q=r.coordsAtPos(fe,fe==k.from?2:-2);!me||!q||(B=Math.min(me.top,q.top,B),R=Math.max(me.bottom,q.bottom,R),ie==0?D.push(o&&J?c:me.left,o&&de?f:q.right):D.push(!o&&de?c:q.left,!o&&J?f:me.right))}let L=w??k.from,I=x??k.to;for(let F of r.visibleRanges)if(F.to>L&&F.from<I)for(let J=Math.max(F.from,L),fe=Math.min(F.to,I);;){let de=r.state.doc.lineAt(J);for(let ie of r.bidiSpans(de)){let me=ie.from+de.from,q=ie.to+de.from;if(me>=fe)break;q>J&&E(Math.max(me,J),w==null&&me<=L,Math.min(q,fe),x==null&&q>=I,ie.dir)}if(J=de.to+1,J>=fe)break}return D.length==0&&E(L,w==null,I,x==null,r.textDirection),{top:B,bottom:R,horizontal:D}}function M(w,x){let k=l.top+(x?w.top:w.bottom);return{top:k,bottom:k,horizontal:[]}}}function eh(r,e){return r.constructor==e.constructor&&r.eq(e)}var Bo=class{constructor(e,t){this.view=e;this.layer=t;this.drawn=[];this.scaleX=1;this.scaleY=1;this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=e.scrollDOM.appendChild(document.createElement("div")),this.dom.classList.add("cm-layer"),t.above&&this.dom.classList.add("cm-layer-above"),t.class&&this.dom.classList.add(t.class),this.scale(),this.dom.setAttribute("aria-hidden","true"),this.setOrder(e.state),e.requestMeasure(this.measureReq),t.mount&&t.mount(this.dom,e)}update(e){e.startState.facet(jr)!=e.state.facet(jr)&&this.setOrder(e.state),(this.layer.update(e,this.dom)||e.geometryChanged)&&(this.scale(),e.view.requestMeasure(this.measureReq))}docViewUpdate(e){this.layer.updateOnDocViewUpdate!==!1&&e.requestMeasure(this.measureReq)}setOrder(e){let t=0,n=e.facet(jr);for(;t<n.length&&n[t]!=this.layer;)t++;this.dom.style.zIndex=String((this.layer.above?150:-1)-t)}measure(){return this.layer.markers(this.view)}scale(){let{scaleX:e,scaleY:t}=this.view;(e!=this.scaleX||t!=this.scaleY)&&(this.scaleX=e,this.scaleY=t,this.dom.style.transform=`scale(${1/e}, ${1/t})`)}draw(e){if(e.length!=this.drawn.length||e.some((t,n)=>!eh(t,this.drawn[n]))){let t=this.dom.firstChild,n=0;for(let i of e)i.update&&t&&i.constructor&&this.drawn[n].constructor&&i.update(t,this.drawn[n])?(t=t.nextSibling,n++):this.dom.insertBefore(i.draw(),t);for(;t;){let i=t.nextSibling;t.remove(),t=i}this.drawn=e,S.webkit&&(this.dom.style.display=this.dom.firstChild?"":"none")}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}},jr=T.define();function Ro(r){return[ge.define(e=>new Bo(e,r)),jr.of(r)]}var Yt=T.define({combine(r){return dt(r,{cursorBlinkRate:1200,drawRangeCursor:!0,iosSelectionHandles:!0},{cursorBlinkRate:(e,t)=>Math.min(e,t),drawRangeCursor:(e,t)=>e||t})}});function yl(r={}){return[Yt.of(r),th,nh,rh,fr.of(!0)]}function xl(r){return r.startState.facet(Yt)!=r.state.facet(Yt)}var th=Ro({above:!0,markers(r){let{state:e}=r,t=e.facet(Yt),n=[];for(let i of e.selection.ranges){let o=i==e.selection.main;if(i.empty||t.drawRangeCursor&&!(o&&S.ios&&t.iosSelectionHandles)){let s=o?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",l=i.empty?i:y.cursor(i.head,i.assoc);for(let a of nt.forRange(r,s,l))n.push(a)}}return n},update(r,e){r.transactions.some(n=>n.selection)&&(e.style.animationName=e.style.animationName=="cm-blink"?"cm-blink2":"cm-blink");let t=xl(r);return t&&bl(r.state,e),r.docChanged||r.selectionSet||t},mount(r,e){bl(e.state,r)},class:"cm-cursorLayer"});function bl(r,e){e.style.animationDuration=r.facet(Yt).cursorBlinkRate+"ms"}var nh=Ro({above:!1,markers(r){let e=[],{main:t,ranges:n}=r.state.selection;for(let i of n)if(!i.empty)for(let o of nt.forRange(r,"cm-selectionBackground",i))e.push(o);if(S.ios&&!t.empty&&r.state.facet(Yt).iosSelectionHandles){for(let i of nt.forRange(r,"cm-selectionHandle cm-selectionHandle-start",y.cursor(t.from,1)))e.push(i);for(let i of nt.forRange(r,"cm-selectionHandle cm-selectionHandle-end",y.cursor(t.to,1)))e.push(i)}return e},update(r,e){return r.docChanged||r.selectionSet||r.viewportChanged||xl(r)},class:"cm-selectionLayer"}),rh=ct.highest(K.theme({".cm-line":{"& ::selection, &::selection":{backgroundColor:"transparent !important"},caretColor:"transparent !important"},".cm-content":{caretColor:"transparent !important","& :focus":{caretColor:"initial !important","&::selection, & ::selection":{backgroundColor:"Highlight !important"}}}}));var Cl=1024,ih=0,Mt=class{constructor(e,t){this.from=e;this.to=t}},H=class r{constructor(e={}){this.id=ih++,this.perNode=!!e.perNode,this.deserialize=e.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")}),this.combine=e.combine||null}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=Ee.match(e)),t=>{let n=e(t);return n===void 0?null:[this,n]}}static{this.closedBy=new r({deserialize:e=>e.split(" ")})}static{this.openedBy=new r({deserialize:e=>e.split(" ")})}static{this.group=new r({deserialize:e=>e.split(" ")})}static{this.isolate=new r({deserialize:e=>{if(e&&e!="rtl"&&e!="ltr"&&e!="auto")throw new RangeError("Invalid value for isolate: "+e);return e||"auto"}})}static{this.contextHash=new r({perNode:!0})}static{this.lookAhead=new r({perNode:!0})}static{this.mounted=new r({perNode:!0})}},Ue=class{constructor(e,t,n,i=!1){this.tree=e;this.overlay=t;this.parser=n;this.bracketed=i}static get(e){return e&&e.props&&e.props[H.mounted.id]}};var oh=Object.create(null),Ee=class r{constructor(e,t,n,i=0){this.name=e;this.props=t;this.id=n;this.flags=i}static define(e){let t=e.props&&e.props.length?Object.create(null):oh,n=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),i=new r(e.name||"",t,e.id,n);if(e.props){for(let o of e.props)if(Array.isArray(o)||(o=o(i)),o){if(o[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[o[0].id]=o[1]}}return i}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e=="string"){if(this.name==e)return!0;let t=this.prop(H.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static{this.none=new r("",Object.create(null),0,8)}static match(e){let t=Object.create(null);for(let n in e)for(let i of n.split(" "))t[i]=e[n];return n=>{for(let i=n.prop(H.group),o=-1;o<(i?i.length:0);o++){let s=t[o<0?n.name:i[o]];if(s)return s}}}};var Jr=new WeakMap,Sl=new WeakMap;var $=class r{constructor(e,t,n,i,o){this.type=e;this.children=t;this.positions=n;this.length=i;this.props=null;if(o&&o.length){this.props=Object.create(null);for(let[s,l]of o)this.props[typeof s=="number"?s:s.id]=l}}toString(){let e=Ue.get(this);if(e&&!e.overlay)return e.tree.toString();let t="";for(let n of this.children){let i=n.toString();i&&(t&&(t+=","),t+=i)}return this.type.name?(/\W/.test(this.type.name)&&!this.type.isError?JSON.stringify(this.type.name):this.type.name)+(t.length?"("+t+")":""):t}static{this.empty=new r(Ee.none,[],[],0)}cursor(e=0){return new Et(this.topNode,e)}cursorAt(e,t=0,n=0){let i=Jr.get(this)||this.topNode,o=new Et(i);return o.moveTo(e,t),Jr.set(this,o._tree),o}get topNode(){return new Ae(this,0,0,null)}resolve(e,t=0){let n=Cn(Jr.get(this)||this.topNode,e,t,!1);return Jr.set(this,n),n}resolveInner(e,t=0){let n=Cn(Sl.get(this)||this.topNode,e,t,!0);return Sl.set(this,n),n}resolveStack(e,t=0){return sh(this,e,t)}iterate(e){let{enter:t,leave:n,from:i=0,to:o=this.length}=e,s=e.mode||0,l=(s&2)>0;for(let a=this.cursor(s|2);;){let u=!1;if(a.from<=o&&a.to>=i&&(!l&&a.type.isAnonymous||t(a)!==!1)){if(a.firstChild())continue;u=!0}for(;u&&n&&(l||!a.type.isAnonymous)&&n(a),!a.nextSibling();){if(!a.parent())return;u=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:Vo(Ee.none,this.children,this.positions,0,this.children.length,0,this.length,(t,n,i)=>new r(this.type,t,n,i,this.propValues),e.makeTree||((t,n,i)=>new r(Ee.none,t,n,i)))}static build(e){return lh(e)}},Oo=class r{constructor(e,t){this.buffer=e;this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new r(this.buffer,this.index)}},qe=class r{constructor(e,t,n){this.buffer=e;this.length=t;this.set=n}get type(){return Ee.none}toString(){let e=[];for(let t=0;t<this.buffer.length;)e.push(this.childString(t)),t=this.buffer[t+3];return e.join(",")}childString(e){let t=this.buffer[e],n=this.buffer[e+3],i=this.set.types[t],o=i.name;if(/\W/.test(o)&&!i.isError&&(o=JSON.stringify(o)),e+=4,n==e)return o;let s=[];for(;e<n;)s.push(this.childString(e)),e=this.buffer[e+3];return o+"("+s.join(",")+")"}findChild(e,t,n,i,o){let{buffer:s}=this,l=-1;for(let a=e;a!=t&&!(kl(o,i,s[a+1],s[a+2])&&(l=a,n>0));a=s[a+3]);return l}slice(e,t,n){let i=this.buffer,o=new Uint16Array(t-e),s=0;for(let l=e,a=0;l<t;){o[a++]=i[l++],o[a++]=i[l++]-n;let u=o[a++]=i[l++]-n;o[a++]=i[l++]-e,s=Math.max(s,u)}return new r(o,s,this.set)}};function kl(r,e,t,n){switch(r){case-2:return t<e;case-1:return n>=e&&t<e;case 0:return t<e&&n>e;case 1:return t<=e&&n>e;case 2:return n>e;case 4:return!0}}function Cn(r,e,t,n){for(;r.from==r.to||(t<1?r.from>=e:r.from>e)||(t>-1?r.to<=e:r.to<e);){let o=!n&&r instanceof Ae&&r.index<0?null:r.parent;if(!o)return r;r=o}let i=n?0:8;if(n)for(let o=r,s=o.parent;s;o=s,s=o.parent)o instanceof Ae&&o.index<0&&s.enter(e,t,i)?.from!=o.from&&(r=s);for(;;){let o=r.enter(e,t,i);if(!o)return r;r=o}}var Yr=class{cursor(e=0){return new Et(this,e)}getChild(e,t=null,n=null){let i=Tl(this,e,t,n);return i.length?i[0]:null}getChildren(e,t=null,n=null){return Tl(this,e,t,n)}resolve(e,t=0){return Cn(this,e,t,!1)}resolveInner(e,t=0){return Cn(this,e,t,!0)}matchContext(e){return Lo(this.parent,e)}enterUnfinishedNodesBefore(e){let t=this.childBefore(e),n=this;for(;t;){let i=t.lastChild;if(!i||i.to!=t.to)break;i.type.isError&&i.from==i.to?(n=t,t=i.prevSibling):t=i}return n}get node(){return this}get next(){return this.parent}},Ae=class r extends Yr{constructor(t,n,i,o){super();this._tree=t;this.from=n;this.index=i;this._parent=o}get type(){return this._tree.type}get name(){return this._tree.type.name}get to(){return this.from+this._tree.length}nextChild(t,n,i,o,s=0){for(let l=this;;){for(let{children:a,positions:u}=l._tree,h=n>0?a.length:-1;t!=h;t+=n){let c=a[t],f=u[t]+l.from,m;if(!(!(s&16&&c instanceof $&&(m=Ue.get(c))&&!m.overlay&&m.bracketed&&i>=f&&i<=f+c.length)&&!kl(o,i,f,f+c.length))){if(c instanceof qe){if(s&1)continue;let d=c.findChild(0,c.buffer.length,n,i-f,o);if(d>-1)return new kn(new Io(l,c,t,f),null,d)}else if(s&2||!c.type.isAnonymous||Po(c)){let d;if(!(s&4)&&(d=Ue.get(c))&&!d.overlay)return new r(d.tree,f,t,l);let p=new r(c,f,t,l);return s&2||!p.type.isAnonymous?p:p.nextChild(n<0?c.children.length-1:0,n,i,o,s)}}}if(s&2||!l.type.isAnonymous||(l.index>=0?t=l.index+n:t=n<0?-1:l._parent._tree.children.length,l=l._parent,!l))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(t){return this.nextChild(0,1,t,2)}childBefore(t){return this.nextChild(this._tree.children.length-1,-1,t,-2)}prop(t){return this._tree.prop(t)}enter(t,n,i=0){let o;if(!(i&8)&&(o=Ue.get(this._tree))&&o.overlay){let s=t-this.from,l=i&16&&o.bracketed;for(let{from:a,to:u}of o.overlay)if((n>0||l?a<=s:a<s)&&(n<0||l?u>=s:u>s))return new r(o.tree,o.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,t,n,i)}nextSignificantParent(){let t=this;for(;t.type.isAnonymous&&t._parent;)t=t._parent;return t}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get tree(){return this._tree}toTree(){return this._tree}toString(){return this._tree.toString()}};function Tl(r,e,t,n){let i=r.cursor(),o=[];if(!i.firstChild())return o;if(t!=null){for(let s=!1;!s;)if(s=i.type.is(t),!i.nextSibling())return o}for(;;){if(n!=null&&i.type.is(n))return o;if(i.type.is(e)&&o.push(i.node),!i.nextSibling())return n==null?o:[]}}function Lo(r,e,t=e.length-1){for(let n=r;t>=0;n=n.parent){if(!n)return!1;if(!n.type.isAnonymous){if(e[t]&&e[t]!=n.name)return!1;t--}}return!0}var Io=class{constructor(e,t,n,i){this.parent=e;this.buffer=t;this.index=n;this.start=i}},kn=class r extends Yr{constructor(t,n,i){super();this.context=t;this._parent=n;this.index=i;this.type=t.buffer.set.types[t.buffer.buffer[i]]}get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}child(t,n,i){let{buffer:o}=this.context,s=o.findChild(this.index+4,o.buffer[this.index+3],t,n-this.context.start,i);return s<0?null:new r(this.context,this,s)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(t){return this.child(1,t,2)}childBefore(t){return this.child(-1,t,-2)}prop(t){return this.type.prop(t)}enter(t,n,i=0){if(i&1)return null;let{buffer:o}=this.context,s=o.findChild(this.index+4,o.buffer[this.index+3],n>0?1:-1,t-this.context.start,n);return s<0?null:new r(this.context,this,s)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(t){return this._parent?null:this.context.parent.nextChild(this.context.index+t,t,0,4)}get nextSibling(){let{buffer:t}=this.context,n=t.buffer[this.index+3];return n<(this._parent?t.buffer[this._parent.index+3]:t.buffer.length)?new r(this.context,this._parent,n):this.externalSibling(1)}get prevSibling(){let{buffer:t}=this.context,n=this._parent?this._parent.index+4:0;return this.index==n?this.externalSibling(-1):new r(this.context,this._parent,t.findChild(n,this.index,-1,0,4))}get tree(){return null}toTree(){let t=[],n=[],{buffer:i}=this.context,o=this.index+4,s=i.buffer[this.index+3];if(s>o){let l=i.buffer[this.index+1];t.push(i.slice(o,s,l)),n.push(0)}return new $(this.type,t,n,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}};function vl(r){if(!r.length)return null;let e=0,t=r[0];for(let o=1;o<r.length;o++){let s=r[o];(s.from>t.from||s.to<t.to)&&(t=s,e=o)}let n=t instanceof Ae&&t.index<0?null:t.parent,i=r.slice();return n?i[e]=n:i.splice(e,1),new No(i,t)}var No=class{constructor(e,t){this.heads=e;this.node=t}get next(){return vl(this.heads)}};function sh(r,e,t){let n=r.resolveInner(e,t),i=null;for(let o=n instanceof Ae?n:n.context.parent;o;o=o.parent)if(o.index<0){let s=o.parent;(i||(i=[n])).push(s.resolve(e,t)),o=s}else{let s=Ue.get(o.tree);if(s&&s.overlay&&s.overlay[0].from<=e&&s.overlay[s.overlay.length-1].to>=e){let l=new Ae(s.tree,s.overlay[0].from+o.from,-1,o);(i||(i=[n])).push(Cn(l,e,t,!1))}}return i?vl(i):n}var Et=class{constructor(e,t=0){this.buffer=null;this.stack=[];this.index=0;this.bufferNode=null;if(this.mode=t&-17,e instanceof Ae)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let n=e._parent;n;n=n._parent)this.stack.unshift(n.index);this.bufferNode=e,this.yieldBuf(e.index)}}get name(){return this.type.name}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,t){this.index=e;let{start:n,buffer:i}=this.buffer;return this.type=t||i.set.types[i.buffer[e]],this.from=n+i.buffer[e+1],this.to=n+i.buffer[e+2],!0}yield(e){return e?e instanceof Ae?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,n){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,n,this.mode));let{buffer:i}=this.buffer,o=i.findChild(this.index+4,i.buffer[this.index+3],e,t-this.buffer.start,n);return o<0?!1:(this.stack.push(this.index),this.yieldBuf(o))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,n=this.mode){return this.buffer?n&1?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,n))}parent(){if(!this.buffer)return this.yieldNode(this.mode&2?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&2?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:t}=this.buffer,n=this.stack.length-1;if(e<0){let i=n<0?0:this.stack[n]+4;if(this.index!=i)return this.yieldBuf(t.findChild(i,this.index,-1,0,4))}else{let i=t.buffer[this.index+3];if(i<(n<0?t.buffer.length:t.buffer[this.stack[n]+3]))return this.yieldBuf(i)}return n<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,n,{buffer:i}=this;if(i){if(e>0){if(this.index<i.buffer.buffer.length)return!1}else for(let o=0;o<this.index;o++)if(i.buffer.buffer[o+3]<this.index)return!1;({index:t,parent:n}=i)}else({index:t,_parent:n}=this._tree);for(;n;{index:t,_parent:n}=n)if(t>-1)for(let o=t+e,s=e<0?-1:n._tree.children.length;o!=s;o+=e){let l=n._tree.children[o];if(this.mode&2||l instanceof qe||!l.type.isAnonymous||Po(l))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to<e))&&this.parent(););for(;this.enterChild(1,e,t););return this}get node(){if(!this.buffer)return this._tree;let e=this.bufferNode,t=null,n=0;if(e&&e.context==this.buffer)e:for(let i=this.index,o=this.stack.length;o>=0;){for(let s=e;s;s=s._parent)if(s.index==i){if(i==this.index)return s;t=s,n=o+1;break e}i=this.stack[--o]}for(let i=n;i<this.stack.length;i++)t=new kn(this.buffer,t,this.stack[i]);return this.bufferNode=new kn(this.buffer,t,this.index)}get tree(){return this.buffer?null:this._tree._tree}iterate(e,t){for(let n=0;;){let i=!1;if(this.type.isAnonymous||e(this)!==!1){if(this.firstChild()){n++;continue}this.type.isAnonymous||(i=!0)}for(;;){if(i&&t&&t(this),i=this.type.isAnonymous,!n)return;if(this.nextSibling())break;this.parent(),n--,i=!0}}}matchContext(e){if(!this.buffer)return Lo(this.node.parent,e);let{buffer:t}=this.buffer,{types:n}=t.set;for(let i=e.length-1,o=this.stack.length-1;i>=0;o--){if(o<0)return Lo(this._tree,e,i);let s=n[t.buffer[this.stack[o]]];if(!s.isAnonymous){if(e[i]&&e[i]!=s.name)return!1;i--}}return!0}};function Po(r){return r.children.some(e=>e instanceof qe||!e.type.isAnonymous||Po(e))}function lh(r){let{buffer:e,nodeSet:t,maxBufferLength:n=Cl,reused:i=[],minRepeatType:o=t.types.length}=r,s=Array.isArray(e)?new Oo(e,e.length):e,l=t.types,a=0,u=0;function h(M,w,x,k,B,R){let{id:D,start:E,end:L,size:I}=s,F=u,J=a;if(I<0)if(s.next(),I==-1){let q=i[D];x.push(q),k.push(E-M);return}else if(I==-3){a=D;return}else if(I==-4){u=D;return}else throw new RangeError(`Unrecognized record size: ${I}`);let fe=l[D],de,ie,me=E-M;if(L-E<=n&&(ie=p(s.pos-w,B))){let q=new Uint16Array(ie.size-ie.skip),pe=s.pos-ie.size,Le=q.length;for(;s.pos>pe;)Le=g(ie.start,q,Le);de=new qe(q,L-ie.start,t),me=ie.start-M}else{let q=s.pos-I;s.next();let pe=[],Le=[],ot=D>=o?D:-1,Bt=0,In=L;for(;s.pos>q;)ot>=0&&s.id==ot&&s.size>=0?(s.end<=In-n&&(m(pe,Le,E,Bt,s.end,In,ot,F,J),Bt=pe.length,In=s.end),s.next()):R>2500?c(E,q,pe,Le):h(E,q,pe,Le,ot,R+1);if(ot>=0&&Bt>0&&Bt<pe.length&&m(pe,Le,E,Bt,E,In,ot,F,J),pe.reverse(),Le.reverse(),ot>-1&&Bt>0){let Qo=f(fe,J);de=Vo(fe,pe,Le,0,pe.length,0,L-E,Qo,Qo)}else de=d(fe,pe,Le,L-E,F-L,J)}x.push(de),k.push(me)}function c(M,w,x,k){let B=[],R=0,D=-1;for(;s.pos>w;){let{id:E,start:L,end:I,size:F}=s;if(F>4)s.next();else{if(D>-1&&L<D)break;D<0&&(D=I-n),B.push(E,L,I),R++,s.next()}}if(R){let E=new Uint16Array(R*4),L=B[B.length-2];for(let I=B.length-3,F=0;I>=0;I-=3)E[F++]=B[I],E[F++]=B[I+1]-L,E[F++]=B[I+2]-L,E[F++]=F;x.push(new qe(E,B[2]-L,t)),k.push(L-M)}}function f(M,w){return(x,k,B)=>{let R=0,D=x.length-1,E,L;if(D>=0&&(E=x[D])instanceof $){if(!D&&E.type==M&&E.length==B)return E;(L=E.prop(H.lookAhead))&&(R=k[D]+E.length+L)}return d(M,x,k,B,R,w)}}function m(M,w,x,k,B,R,D,E,L){let I=[],F=[];for(;M.length>k;)I.push(M.pop()),F.push(w.pop()+x-B);M.push(d(t.types[D],I,F,R-B,E-R,L)),w.push(B-x)}function d(M,w,x,k,B,R,D){if(R){let E=[H.contextHash,R];D=D?[E].concat(D):[E]}if(B>25){let E=[H.lookAhead,B];D=D?[E].concat(D):[E]}return new $(M,w,x,k,D)}function p(M,w){let x=s.fork(),k=0,B=0,R=0,D=x.end-n,E={size:0,start:0,skip:0};e:for(let L=x.pos-M;x.pos>L;){let I=x.size;if(x.id==w&&I>=0){E.size=k,E.start=B,E.skip=R,R+=4,k+=4,x.next();continue}let F=x.pos-I;if(I<0||F<L||x.start<D)break;let J=x.id>=o?4:0,fe=x.start;for(x.next();x.pos>F;){if(x.size<0)if(x.size==-3||x.size==-4)J+=4;else break e;else x.id>=o&&(J+=4);x.next()}B=fe,k+=I,R+=J}return(w<0||k==M)&&(E.size=k,E.start=B,E.skip=R),E.size>4?E:void 0}function g(M,w,x){let{id:k,start:B,end:R,size:D}=s;if(s.next(),D>=0&&k<o){let E=x;if(D>4){let L=s.pos-(D-4);for(;s.pos>L;)x=g(M,w,x)}w[--x]=E,w[--x]=R-M,w[--x]=B-M,w[--x]=k}else D==-3?a=k:D==-4&&(u=k);return x}let b=[],C=[];for(;s.pos>0;)h(r.start||0,r.bufferStart||0,b,C,-1,0);let v=r.length??(b.length?C[0]+b[0].length:0);return new $(l[r.topID],b.reverse(),C.reverse(),v)}var wl=new WeakMap;function $r(r,e){if(!r.isAnonymous||e instanceof qe||e.type!=r)return 1;let t=wl.get(e);if(t==null){t=1;for(let n of e.children){if(n.type!=r||!(n instanceof $)){t=1;break}t+=$r(r,n)}wl.set(e,t)}return t}function Vo(r,e,t,n,i,o,s,l,a){let u=0;for(let d=n;d<i;d++)u+=$r(r,e[d]);let h=Math.ceil(u*1.5/8),c=[],f=[];function m(d,p,g,b,C){for(let v=g;v<b;){let M=v,w=p[v],x=$r(r,d[v]);for(v++;v<b;v++){let k=$r(r,d[v]);if(x+k>=h)break;x+=k}if(v==M+1){if(x>h){let k=d[M];m(k.children,k.positions,0,k.children.length,p[M]+C);continue}c.push(d[M])}else{let k=p[v-1]+d[v-1].length-w;c.push(Vo(r,d,p,M,v,w,k,null,a))}f.push(w+C-o)}}return m(e,t,n,i,0),(l||a)(c,f,s)}var Ge=class r{constructor(e,t,n,i,o=!1,s=!1){this.from=e;this.to=t;this.tree=n;this.offset=i;this.open=(o?1:0)|(s?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(e,t=[],n=!1){let i=[new r(0,e.length,e,0,!1,n)];for(let o of t)o.to>e.length&&i.push(o);return i}static applyChanges(e,t,n=128){if(!t.length)return e;let i=[],o=1,s=e.length?e[0]:null;for(let l=0,a=0,u=0;;l++){let h=l<t.length?t[l]:null,c=h?h.fromA:1e9;if(c-a>=n)for(;s&&s.from<c;){let f=s;if(a>=f.from||c<=f.to||u){let m=Math.max(f.from,a)-u,d=Math.min(f.to,c)-u;f=m>=d?null:new r(m,d,f.tree,f.offset+u,l>0,!!h)}if(f&&i.push(f),s.to>c)break;s=o<e.length?e[o++]:null}if(!h)break;a=h.toA,u=h.toA-h.toB}return i}},vn=class{startParse(e,t,n){return typeof e=="string"&&(e=new Ho(e)),n=n?n.length?n.map(i=>new Mt(i.from,i.to)):[new Mt(0,0)]:[new Mt(0,e.length)],this.createParse(e,t||[],n)}parse(e,t,n){let i=this.startParse(e,t,n);for(;;){let o=i.advance();if(o)return o}}},Ho=class{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}};var Yg=new H({perNode:!0});var En=new H;var Dl=new H,De=class{constructor(e,t,n=[],i=""){this.data=e;this.name=i;j.prototype.hasOwnProperty("tree")||Object.defineProperty(j.prototype,"tree",{get(){return Se(this)}}),this.parser=t,this.extension=[At.of(this),j.languageData.of((o,s,l)=>{let a=El(o,s,l),u=a.type.prop(En);if(!u)return[];let h=o.facet(u),c=a.type.prop(Dl);if(c){let f=a.resolve(s-a.from,l);for(let m of c)if(m.test(f,o)){let d=o.facet(m.facet);return m.type=="replace"?d:d.concat(h)}}return h})].concat(n)}isActiveAt(e,t,n=-1){return El(e,t,n).type.prop(En)==this.data}findRegions(e){let t=e.facet(At);if(t?.data==this.data)return[{from:0,to:e.doc.length}];if(!t||!t.allowsNesting)return[];let n=[],i=(o,s)=>{if(o.prop(En)==this.data){n.push({from:s,to:s+o.length});return}let l=o.prop(H.mounted);if(l){if(l.tree.prop(En)==this.data){if(l.overlay)for(let a of l.overlay)n.push({from:a.from+s,to:a.to+s});else n.push({from:s,to:s+o.length});return}else if(l.overlay){let a=n.length;if(i(l.tree,l.overlay[0].from+s),n.length>a)return}}for(let a=0;a<o.children.length;a++){let u=o.children[a];u instanceof $&&i(u,o.positions[a]+s)}};return i(Se(e),0),n}get allowsNesting(){return!0}static{this.setState=W.define()}};function El(r,e,t){let n=r.facet(At),i=Se(r).topNode;if(!n||n.allowsNesting)for(let o=i;o;o=o.enter(e,t,17))o.type.isTop&&(i=o);return i}function Se(r){let e=r.field(De.state,!1);return e?e.tree:$.empty}var Xr=class{constructor(e){this.doc=e;this.cursorPos=0;this.string="";this.cursor=e.iter()}get length(){return this.doc.length}syncTo(e){return this.string=this.cursor.next(e-this.cursorPos).value,this.cursorPos=e+this.string.length,this.cursorPos-this.string.length}chunk(e){return this.syncTo(e),this.string}get lineChunks(){return!0}read(e,t){let n=this.cursorPos-this.string.length;return e<n||t>=this.cursorPos?this.doc.sliceString(e,t):this.string.slice(e-n,t-n)}};var Mn=null,Qr=class r{constructor(e,t,n=[],i,o,s,l,a){this.parser=e;this.state=t;this.fragments=n;this.tree=i;this.treeLen=o;this.viewport=s;this.skipped=l;this.scheduleOn=a;this.parse=null;this.tempSkipped=[]}static create(e,t,n){return new r(e,t,[],$.empty,0,n,[],null)}startParse(){return this.parser.startParse(new Xr(this.state.doc),this.fragments)}work(e,t){return t!=null&&t>=this.state.doc.length&&(t=void 0),this.tree!=$.empty&&this.isDone(t??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{if(typeof e=="number"){let n=Date.now()+e;e=()=>Date.now()>n}for(this.parse||(this.parse=this.startParse()),t!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>t)&&t<this.state.doc.length&&this.parse.stopAt(t);;){let n=this.parse.advance();if(n)if(this.fragments=this.withoutTempSkipped(Ge.addTree(n,this.fragments,this.parse.stoppedAt!=null)),this.treeLen=this.parse.stoppedAt??this.state.doc.length,this.tree=n,this.parse=null,this.treeLen<(t??this.state.doc.length))this.parse=this.startParse();else return!0;if(e())return!1}})}takeTree(){let e,t;this.parse&&(e=this.parse.parsedPos)>=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>e)&&this.parse.stopAt(e),this.withContext(()=>{for(;!(t=this.parse.advance()););}),this.treeLen=e,this.tree=t,this.fragments=this.withoutTempSkipped(Ge.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let t=Mn;Mn=this;try{return e()}finally{Mn=t}}withoutTempSkipped(e){for(let t;t=this.tempSkipped.pop();)e=Al(e,t.from,t.to);return e}changes(e,t){let{fragments:n,tree:i,treeLen:o,viewport:s,skipped:l}=this;if(this.takeTree(),!e.empty){let a=[];if(e.iterChangedRanges((u,h,c,f)=>a.push({fromA:u,toA:h,fromB:c,toB:f})),n=Ge.applyChanges(n,a),i=$.empty,o=0,s={from:e.mapPos(s.from,-1),to:e.mapPos(s.to,1)},this.skipped.length){l=[];for(let u of this.skipped){let h=e.mapPos(u.from,1),c=e.mapPos(u.to,-1);h<c&&l.push({from:h,to:c})}}}return new r(this.parser,t,n,i,o,s,l,this.scheduleOn)}updateViewport(e){if(this.viewport.from==e.from&&this.viewport.to==e.to)return!1;this.viewport=e;let t=this.skipped.length;for(let n=0;n<this.skipped.length;n++){let{from:i,to:o}=this.skipped[n];i<e.to&&o>e.from&&(this.fragments=Al(this.fragments,i,o),this.skipped.splice(n--,1))}return this.skipped.length>=t?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(e,t){this.skipped.push({from:e,to:t})}static getSkippingParser(e){return new class extends vn{createParse(t,n,i){let o=i[0].from,s=i[i.length-1].to;return{parsedPos:o,advance(){let a=Mn;if(a){for(let u of i)a.tempSkipped.push(u);e&&(a.scheduleOn=a.scheduleOn?Promise.all([a.scheduleOn,e]):e)}return this.parsedPos=s,new $(Ee.none,[],[],s-o)},stoppedAt:null,stopAt(){}}}}}isDone(e){e=Math.min(e,this.state.doc.length);let t=this.fragments;return this.treeLen>=e&&t.length&&t[0].from==0&&t[0].to>=e}static get(){return Mn}};function Al(r,e,t){return Ge.applyChanges(r,[{fromA:e,toA:t,fromB:e,toB:t}])}var An=class r{constructor(e){this.context=e;this.tree=e.tree}apply(e){if(!e.docChanged&&this.tree==this.context.tree)return this;let t=this.context.changes(e.changes,e.state),n=this.context.treeLen==e.startState.doc.length?void 0:Math.max(e.changes.mapPos(this.context.treeLen),t.viewport.to);return t.work(20,n)||t.takeTree(),new r(t)}static init(e){let t=Math.min(3e3,e.doc.length),n=Qr.create(e.facet(At).parser,e,{from:0,to:t});return n.work(20,t)||n.takeTree(),new r(n)}};De.state=se.define({create:An.init,update(r,e){for(let t of e.effects)if(t.is(De.setState))return t.value;return e.startState.facet(At)!=e.state.facet(At)?An.init(e.state):r.apply(e)}});var Bl=r=>{let e=setTimeout(()=>r(),500);return()=>clearTimeout(e)};typeof requestIdleCallback<"u"&&(Bl=r=>{let e=-1,t=setTimeout(()=>{e=requestIdleCallback(r,{timeout:400})},100);return()=>e<0?clearTimeout(t):cancelIdleCallback(e)});var Fo=typeof navigator<"u"&&navigator.scheduling?.isInputPending?()=>navigator.scheduling.isInputPending():null,ah=ge.fromClass(class{constructor(e){this.view=e;this.working=null;this.workScheduled=0;this.chunkEnd=-1;this.chunkBudget=-1;this.work=this.work.bind(this),this.scheduleWork()}update(e){let t=this.view.state.field(De.state).context;(t.updateViewport(e.view.viewport)||this.view.viewport.to>t.treeLen)&&this.scheduleWork(),(e.docChanged||e.selectionSet)&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(t)}scheduleWork(){if(this.working)return;let{state:e}=this.view,t=e.field(De.state);(t.tree!=t.context.tree||!t.context.isDone(e.doc.length))&&(this.working=Bl(this.work))}work(e){this.working=null;let t=Date.now();if(this.chunkEnd<t&&(this.chunkEnd<0||this.view.hasFocus)&&(this.chunkEnd=t+3e4,this.chunkBudget=3e3),this.chunkBudget<=0)return;let{state:n,viewport:{to:i}}=this.view,o=n.field(De.state);if(o.tree==o.context.tree&&o.context.isDone(i+1e5))return;let s=Date.now()+Math.min(this.chunkBudget,100,e&&!Fo?Math.max(25,e.timeRemaining()-5):1e9),l=o.context.treeLen<i&&n.doc.length>i+1e3,a=o.context.work(()=>Fo&&Fo()||Date.now()>s,i+(l?0:1e5));this.chunkBudget-=Date.now()-t,(a||this.chunkBudget<=0)&&(o.context.takeTree(),this.view.dispatch({effects:De.setState.of(new An(o.context))})),this.chunkBudget>0&&!(a&&!l)&&this.scheduleWork(),this.checkAsyncSchedule(o.context)}checkAsyncSchedule(e){e.scheduleOn&&(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(t=>_(this.view.state,t)).then(()=>this.workScheduled--),e.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),At=T.define({combine(r){return r.length?r[0]:null},enables:r=>[De.state,ah,K.contentAttributes.compute([r],e=>{let t=e.facet(r);return t&&t.name?{"data-language":t.name}:{}})]});var Rl=T.define(),Dn=T.define({combine:r=>{if(!r.length)return" ";let e=r[0];if(!e||/\S/.test(e)||Array.from(e).some(t=>t!=e[0]))throw new Error("Invalid indent unit: "+JSON.stringify(r[0]));return e}});function Xt(r){let e=r.facet(Dn);return e.charCodeAt(0)==9?r.tabSize*e.length:e.length}function Qt(r,e){let t="",n=r.tabSize,i=r.facet(Dn)[0];if(i==" "){for(;e>=n;)t+=" ",e-=n;i=" "}for(let o=0;o<e;o++)t+=i;return t}function _r(r,e){r instanceof j&&(r=new rt(r));for(let n of r.state.facet(Rl)){let i=n(r,e);if(i!==void 0)return i}let t=Se(r.state);return t.length>=e?uh(r,t,e):null}var rt=class{constructor(e,t={}){this.state=e;this.options=t;this.unit=Xt(e)}lineAt(e,t=1){let n=this.state.doc.lineAt(e),{simulateBreak:i,simulateDoubleBreak:o}=this.options;return i!=null&&i>=n.from&&i<=n.to?o&&i==e?{text:"",from:e}:(t<0?i<e:i<=e)?{text:n.text.slice(i-n.from),from:i}:{text:n.text.slice(0,i-n.from),from:n.from}:n}textAfterPos(e,t=1){if(this.options.simulateDoubleBreak&&e==this.options.simulateBreak)return"";let{text:n,from:i}=this.lineAt(e,t);return n.slice(e-i,Math.min(n.length,e+100-i))}column(e,t=1){let{text:n,from:i}=this.lineAt(e,t),o=this.countColumn(n,e-i),s=this.options.overrideIndentation?this.options.overrideIndentation(i):-1;return s>-1&&(o+=s-this.countColumn(n,n.search(/\S|$/))),o}countColumn(e,t=e.length){return pt(e,this.state.tabSize,t)}lineIndent(e,t=1){let{text:n,from:i}=this.lineAt(e,t),o=this.options.overrideIndentation;if(o){let s=o(i);if(s>-1)return s}return this.countColumn(n,n.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}},Ol=new H;function uh(r,e,t){let n=e.resolveStack(t),i=e.resolveInner(t,-1).resolve(t,0).enterUnfinishedNodesBefore(t);if(i!=n.node){let o=[];for(let s=i;s&&!(s.from<n.node.from||s.to>n.node.to||s.from==n.node.from&&s.type==n.node.type);s=s.parent)o.push(s);for(let s=o.length-1;s>=0;s--)n={node:o[s],next:n}}return Ll(n,r,t)}function Ll(r,e,t){for(let n=r;n;n=n.next){let i=ch(n.node);if(i)return i(Zr.create(e,t,n))}return 0}function hh(r){return r.pos==r.options.simulateBreak&&r.options.simulateDoubleBreak}function ch(r){let e=r.type.prop(Ol);if(e)return e;let t=r.firstChild,n;if(t&&(n=t.type.prop(H.closedBy))){let i=r.lastChild,o=i&&n.indexOf(i.name)>-1;return s=>ph(s,!0,1,void 0,o&&!hh(s)?i.from:void 0)}return r.parent==null?fh:null}function fh(){return 0}var Zr=class r extends rt{constructor(t,n,i){super(t.state,t.options);this.base=t;this.pos=n;this.context=i}get node(){return this.context.node}static create(t,n,i){return new r(t,n,i)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(t){let n=this.state.doc.lineAt(t.from);for(;;){let i=t.resolve(n.from);for(;i.parent&&i.parent.from==i.from;)i=i.parent;if(dh(i,t))break;n=this.state.doc.lineAt(i.from)}return this.lineIndent(n.from)}continue(){return Ll(this.context.next,this.base,this.pos)}};function dh(r,e){for(let t=e;t;t=t.parent)if(r==t)return!0;return!1}function mh(r){let e=r.node,t=e.childAfter(e.from),n=e.lastChild;if(!t)return null;let i=r.options.simulateBreak,o=r.state.doc.lineAt(t.from),s=i==null||i<=o.from?o.to:Math.min(o.to,i);for(let l=t.to;;){let a=e.childAfter(l);if(!a||a==n)return null;if(!a.type.isSkipped){if(a.from>=s)return null;let u=/^ */.exec(o.text.slice(t.to-o.from))[0].length;return{from:t.from,to:t.to+u}}l=a.to}}function ph(r,e,t,n,i){let o=r.textAfter,s=o.match(/^\s*/)[0].length,l=n&&o.slice(s,s+n.length)==n||i==r.pos+s,a=e?mh(r):null;return a?l?r.column(a.from):r.column(a.to):r.baseIndent+(l?0:r.unit*t)}var Zb=K.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),Nl=1e4,Pl="()[]{}",gh=T.define({combine(r){return dt(r,{afterCursor:!0,brackets:Pl,maxScanDistance:Nl,renderMatch:xh})}}),bh=V.mark({class:"cm-matchingBracket"}),yh=V.mark({class:"cm-nonmatchingBracket"});function xh(r){let e=[],t=r.matched?bh:yh;return e.push(t.range(r.start.from,r.start.to)),r.end&&e.push(t.range(r.end.from,r.end.to)),e}function Il(r){let e=[],t=r.facet(gh);for(let n of r.selection.ranges){if(!n.empty)continue;let i=Te(r,n.head,-1,t)||n.head>0&&Te(r,n.head-1,1,t)||t.afterCursor&&(Te(r,n.head,1,t)||n.head<r.doc.length&&Te(r,n.head+1,-1,t));i&&(e=e.concat(t.renderMatch(i,r)))}return V.set(e,!0)}var _b=ge.fromClass(class{constructor(r){this.paused=!1;this.decorations=Il(r.state)}update(r){(r.docChanged||r.selectionSet||this.paused)&&(r.view.composing?(this.decorations=this.decorations.map(r.changes),this.paused=!0):(this.decorations=Il(r.state),this.paused=!1))}},{decorations:r=>r.decorations});var Vl=new H;function Wo(r,e,t){let n=r.prop(e<0?H.openedBy:H.closedBy);if(n)return n;if(r.name.length==1){let i=t.indexOf(r.name);if(i>-1&&i%2==(e<0?1:0))return[t[i+e]]}return null}function zo(r){let e=r.type.prop(Vl);return e?e(r.node):r}function Te(r,e,t,n={}){let i=n.maxScanDistance||Nl,o=n.brackets||Pl,s=Se(r),l=s.resolveInner(e,t);for(let a=l;a;a=a.parent){let u=Wo(a.type,t,o);if(u&&a.from<a.to){let h=zo(a);if(h&&(t>0?e>=h.from&&e<h.to:e>h.from&&e<=h.to))return Sh(r,e,t,a,h,u,o)}}return Th(r,e,t,s,l.type,i,o)}function Sh(r,e,t,n,i,o,s){let l=n.parent,a={from:i.from,to:i.to},u=0,h=l?.cursor();if(h&&(t<0?h.childBefore(n.from):h.childAfter(n.to)))do if(t<0?h.to<=n.from:h.from>=n.to){if(u==0&&o.indexOf(h.type.name)>-1&&h.from<h.to){let c=zo(h);return{start:a,end:c?{from:c.from,to:c.to}:void 0,matched:!0}}else if(Wo(h.type,t,s))u++;else if(Wo(h.type,-t,s)){if(u==0){let c=zo(h);return{start:a,end:c&&c.from<c.to?{from:c.from,to:c.to}:void 0,matched:!1}}u--}}while(t<0?h.prevSibling():h.nextSibling());return{start:a,matched:!1}}function Th(r,e,t,n,i,o,s){if(t<0?!e:e==r.doc.length)return null;let l=t<0?r.sliceDoc(e-1,e):r.sliceDoc(e,e+1),a=s.indexOf(l);if(a<0||a%2==0!=t>0)return null;let u={from:t<0?e-1:e,to:t>0?e+1:e},h=r.doc.iterRange(e,t>0?r.doc.length:0),c=0;for(let f=0;!h.next().done&&f<=o;){let m=h.value;t<0&&(f+=m.length);let d=e+f*t;for(let p=t>0?0:m.length-1,g=t>0?m.length:-1;p!=g;p+=t){let b=s.indexOf(m[p]);if(!(b<0||n.resolveInner(d+p,1).type!=i))if(b%2==0==t>0)c++;else{if(c==1)return{start:u,end:{from:d+p,to:d+p+1},matched:b>>1==a>>1};c--}}t>0&&(f+=m.length)}return h.done?{start:u,matched:!1}:null}var Hl=r=>{let{state:e}=r,t=e.doc.lineAt(e.selection.main.from),n=Ko(r.state,t.from);return n.line?wh(r):n.block?Ch(r):!1};function Dt(r,e){return({state:t,dispatch:n})=>{if(t.readOnly)return!1;let i=r(e,t);return i?(n(t.update(i)),!0):!1}}var wh=Dt(Uo,0),Cy=Dt(Uo,1),ky=Dt(Uo,2),Fl=Dt(ei,0),vy=Dt(ei,1),My=Dt(ei,2),Ch=Dt((r,e)=>ei(r,e,vh(e)),0);function Ko(r,e){let t=r.languageDataAt("commentTokens",e,1);return t.length?t[0]:{}}var Bn=50;function kh(r,{open:e,close:t},n,i){let o=r.sliceDoc(n-Bn,n),s=r.sliceDoc(i,i+Bn),l=/\s*$/.exec(o)[0].length,a=/^\s*/.exec(s)[0].length,u=o.length-l;if(o.slice(u-e.length,u)==e&&s.slice(a,a+t.length)==t)return{open:{pos:n-l,margin:l&&1},close:{pos:i+a,margin:a&&1}};let h,c;i-n<=2*Bn?h=c=r.sliceDoc(n,i):(h=r.sliceDoc(n,n+Bn),c=r.sliceDoc(i-Bn,i));let f=/^\s*/.exec(h)[0].length,m=/\s*$/.exec(c)[0].length,d=c.length-m-t.length;return h.slice(f,f+e.length)==e&&c.slice(d,d+t.length)==t?{open:{pos:n+f+e.length,margin:/\s/.test(h.charAt(f+e.length))?1:0},close:{pos:i-m-t.length,margin:/\s/.test(c.charAt(d-1))?1:0}}:null}function vh(r){let e=[];for(let t of r.selection.ranges){let n=r.doc.lineAt(t.from),i=t.to<=n.to?n:r.doc.lineAt(t.to);i.from>n.from&&i.from==t.to&&(i=t.to==n.to+1?n:r.doc.lineAt(t.to-1));let o=e.length-1;o>=0&&e[o].to>n.from?e[o].to=i.to:e.push({from:n.from+/^\s*/.exec(n.text)[0].length,to:i.to})}return e}function ei(r,e,t=e.selection.ranges){let n=t.map(o=>Ko(e,o.from).block);if(!n.every(o=>o))return null;let i=t.map((o,s)=>kh(e,n[s],o.from,o.to));if(r!=2&&!i.every(o=>o))return{changes:e.changes(t.map((o,s)=>i[s]?[]:[{from:o.from,insert:n[s].open+" "},{from:o.to,insert:" "+n[s].close}]))};if(r!=1&&i.some(o=>o)){let o=[];for(let s=0,l;s<i.length;s++)if(l=i[s]){let a=n[s],{open:u,close:h}=l;o.push({from:u.pos-a.open.length,to:u.pos+u.margin},{from:h.pos-h.margin,to:h.pos+a.close.length})}return{changes:o}}return null}function Uo(r,e,t=e.selection.ranges){let n=[],i=-1;e:for(let{from:o,to:s}of t){let l=n.length,a=1e9,u;for(let h=o;h<=s;){let c=e.doc.lineAt(h);if(u==null&&(u=Ko(e,c.from).line,!u))continue e;if(c.from>i&&(o==s||s>c.from)){i=c.from;let f=/^\s*/.exec(c.text)[0].length,m=f==c.length,d=c.text.slice(f,f+u.length)==u?f:-1;f<c.text.length&&f<a&&(a=f),n.push({line:c,comment:d,token:u,indent:f,empty:m,single:!1})}h=c.to+1}if(a<1e9)for(let h=l;h<n.length;h++)n[h].indent<n[h].line.text.length&&(n[h].indent=a);n.length==l+1&&(n[l].single=!0)}if(r!=2&&n.some(o=>o.comment<0&&(!o.empty||o.single))){let o=[];for(let{line:l,token:a,indent:u,empty:h,single:c}of n)(c||!h)&&o.push({from:l.from+u,insert:a+" "});let s=e.changes(o);return{changes:s,selection:e.selection.map(s,1)}}else if(r!=1&&n.some(o=>o.comment>=0)){let o=[];for(let{line:s,comment:l,token:a}of n)if(l>=0){let u=s.from+l,h=u+a.length;s.text[h-s.from]==" "&&h++,o.push({from:u,to:h})}return{changes:o}}return null}var Go=le.define(),jo=le.define(),Wl=T.define(),zl=T.define({combine(r){return dt(r,{minDepth:100,newGroupDelay:500,joinToEvent:(e,t)=>t},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,t)=>(n,i)=>e(n,i)||t(n,i)})}}),Jo=se.define({create(){return Rn.empty},update(r,e){let t=e.state.facet(zl),n=e.annotation(Go);if(n){let a=Be.fromTransaction(e,n.selection),u=n.side,h=u==0?r.undone:r.done;return a?h=ti(h,h.length,t.minDepth,a):h=Jl(h,e.startState.selection),new Rn(u==0?n.rest:h,u==0?h:n.rest)}let i=e.annotation(jo);if((i=="full"||i=="before")&&(r=r.isolate()),e.annotation(X.addToHistory)===!1)return e.changes.empty?r:r.addMapping(e.changes.desc);let o=Be.fromTransaction(e),s=e.annotation(X.time),l=e.annotation(X.userEvent);return o?r=r.addChanges(o,s,l,t,e):e.selection&&(r=r.addSelection(e.startState.selection,s,l,t.newGroupDelay)),(i=="full"||i=="after")&&(r=r.isolate()),r},toJSON(r){return{done:r.done.map(e=>e.toJSON()),undone:r.undone.map(e=>e.toJSON())}},fromJSON(r){return new Rn(r.done.map(Be.fromJSON),r.undone.map(Be.fromJSON))}});function Kl(r={}){return[Jo,zl.of(r),K.domEventHandlers({beforeinput(e,t){let n=e.inputType=="historyUndo"?ri:e.inputType=="historyRedo"?On:null;return n?(e.preventDefault(),n(t)):!1}})]}function ni(r,e){return function({state:t,dispatch:n}){if(!e&&t.readOnly)return!1;let i=t.field(Jo,!1);if(!i)return!1;let o=i.pop(r,t,e);return o?(n(o),!0):!1}}var ri=ni(0,!1),On=ni(1,!1),Ul=ni(0,!0),ql=ni(1,!0);function Gl(r){return function(e){let t=e.field(Jo,!1);if(!t)return 0;let n=r==0?t.done:t.undone;return n.length-(n.length&&!n[0].changes?1:0)}}var Mh=Gl(0),Eh=Gl(1),Be=class r{constructor(e,t,n,i,o){this.changes=e;this.effects=t;this.mapped=n;this.startSelection=i;this.selectionsAfter=o}setSelAfter(e){return new r(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){return{changes:this.changes?.toJSON(),mapped:this.mapped?.toJSON(),startSelection:this.startSelection?.toJSON(),selectionsAfter:this.selectionsAfter.map(e=>e.toJSON())}}static fromJSON(e){return new r(e.changes&&G.fromJSON(e.changes),[],e.mapped&&Ie.fromJSON(e.mapped),e.startSelection&&y.fromJSON(e.startSelection),e.selectionsAfter.map(y.fromJSON))}static fromTransaction(e,t){let n=we;for(let i of e.startState.facet(Wl)){let o=i(e);o.length&&(n=n.concat(o))}return!n.length&&e.changes.empty?null:new r(e.changes.invert(e.startState.doc),n,void 0,t||e.startState.selection,we)}static selection(e){return new r(void 0,we,void 0,void 0,e)}};function ti(r,e,t,n){let i=e+1>t+20?e-t-1:0,o=r.slice(i,e);return o.push(n),o}function Ah(r,e){let t=[],n=!1;return r.iterChangedRanges((i,o)=>t.push(i,o)),e.iterChangedRanges((i,o,s,l)=>{for(let a=0;a<t.length;){let u=t[a++],h=t[a++];l>=u&&s<=h&&(n=!0)}}),n}function Dh(r,e){return r.ranges.length==e.ranges.length&&r.ranges.filter((t,n)=>t.empty!=e.ranges[n].empty).length===0}function jl(r,e){return r.length?e.length?r.concat(e):r:e}var we=[],Bh=200;function Jl(r,e){if(r.length){let t=r[r.length-1],n=t.selectionsAfter.slice(Math.max(0,t.selectionsAfter.length-Bh));return n.length&&n[n.length-1].eq(e)?r:(n.push(e),ti(r,r.length-1,1e9,t.setSelAfter(n)))}else return[Be.selection([e])]}function Rh(r){let e=r[r.length-1],t=r.slice();return t[r.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),t}function qo(r,e){if(!r.length)return r;let t=r.length,n=we;for(;t;){let i=Oh(r[t-1],e,n);if(i.changes&&!i.changes.empty||i.effects.length){let o=r.slice(0,t);return o[t-1]=i,o}else e=i.mapped,t--,n=i.selectionsAfter}return n.length?[Be.selection(n)]:we}function Oh(r,e,t){let n=jl(r.selectionsAfter.length?r.selectionsAfter.map(l=>l.map(e)):we,t);if(!r.changes)return Be.selection(n);let i=r.changes.map(e),o=e.mapDesc(r.changes,!0),s=r.mapped?r.mapped.composeDesc(o):o;return new Be(i,W.mapEffects(r.effects,e),s,r.startSelection.map(o),n)}var Lh=/^(input\.type|delete)($|\.)/,Rn=class r{constructor(e,t,n=0,i=void 0){this.done=e;this.undone=t;this.prevTime=n;this.prevUserEvent=i}isolate(){return this.prevTime?new r(this.done,this.undone):this}addChanges(e,t,n,i,o){let s=this.done,l=s[s.length-1];return l&&l.changes&&!l.changes.empty&&e.changes&&(!n||Lh.test(n))&&(!l.selectionsAfter.length&&t-this.prevTime<i.newGroupDelay&&i.joinToEvent(o,Ah(l.changes,e.changes))||n=="input.type.compose")?s=ti(s,s.length-1,i.minDepth,new Be(e.changes.compose(l.changes),jl(W.mapEffects(e.effects,l.changes),l.effects),l.mapped,l.startSelection,we)):s=ti(s,s.length,i.minDepth,e),new r(s,we,t,n)}addSelection(e,t,n,i){let o=this.done.length?this.done[this.done.length-1].selectionsAfter:we;return o.length>0&&t-this.prevTime<i&&n==this.prevUserEvent&&n&&/^select($|\.)/.test(n)&&Dh(o[o.length-1],e)?this:new r(Jl(this.done,e),this.undone,t,n)}addMapping(e){return new r(qo(this.done,e),qo(this.undone,e),this.prevTime,this.prevUserEvent)}pop(e,t,n){let i=e==0?this.done:this.undone;if(i.length==0)return null;let o=i[i.length-1],s=o.selectionsAfter[0]||(o.startSelection?o.startSelection.map(o.changes.invertedDesc,1):t.selection);if(n&&o.selectionsAfter.length)return t.update({selection:o.selectionsAfter[o.selectionsAfter.length-1],annotations:Go.of({side:e,rest:Rh(i),selection:s}),userEvent:e==0?"select.undo":"select.redo",scrollIntoView:!0});if(o.changes){let l=i.length==1?we:i.slice(0,i.length-1);return o.mapped&&(l=qo(l,o.mapped)),t.update({changes:o.changes,selection:o.startSelection,effects:o.effects,annotations:Go.of({side:e,rest:l,selection:s}),filter:!1,userEvent:e==0?"undo":"redo",scrollIntoView:!0})}else return null}static{this.empty=new r(we,we)}},$l=[{key:"Mod-z",run:ri,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:On,preventDefault:!0},{linux:"Ctrl-Shift-z",run:On,preventDefault:!0},{key:"Mod-u",run:Ul,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:ql,preventDefault:!0}];function Zt(r,e){return y.create(r.ranges.map(e),r.mainIndex)}function Re(r,e){return r.update({selection:e,scrollIntoView:!0,userEvent:"select"})}function Oe({state:r,dispatch:e},t){let n=Zt(r.selection,t);return n.eq(r.selection,!0)?!1:(e(Re(r,n)),!0)}function oi(r,e){return y.cursor(e?r.to:r.from)}function ra(r,e){return Oe(r,t=>t.empty?r.moveByChar(t,e):oi(t,e))}function Q(r){return r.textDirectionAt(r.state.selection.main.head)==0}var ia=r=>ra(r,!Q(r)),oa=r=>ra(r,Q(r));function sa(r,e){return Oe(r,t=>t.empty?r.moveByGroup(t,e):oi(t,e))}var Ih=r=>sa(r,!Q(r)),Nh=r=>sa(r,Q(r));var Zy=typeof Intl<"u"&&Intl.Segmenter?new Intl.Segmenter(void 0,{granularity:"word"}):null;function Ph(r,e,t){if(e.type.prop(t))return!0;let n=e.to-e.from;return n&&(n>2||/[^\s,.;:]/.test(r.sliceDoc(e.from,e.to)))||e.firstChild}function si(r,e,t){let n=Se(r).resolveInner(e.head),i=t?H.closedBy:H.openedBy;for(let a=e.head;;){let u=t?n.childAfter(a):n.childBefore(a);if(!u)break;Ph(r,u,i)?n=u:a=t?u.to:u.from}let o=n.type.prop(i),s,l;return o&&(s=t?Te(r,n.from,1):Te(r,n.to,-1))&&s.matched?l=t?s.end.to:s.end.from:l=t?n.to:n.from,y.cursor(l,t?-1:1)}var Vh=r=>Oe(r,e=>si(r.state,e,!Q(r))),Hh=r=>Oe(r,e=>si(r.state,e,Q(r)));function la(r,e){return Oe(r,t=>{if(!t.empty)return oi(t,e);let n=r.moveVertically(t,e);return n.head!=t.head?n:r.moveToLineBoundary(t,e)})}var aa=r=>la(r,!1),ua=r=>la(r,!0);function ha(r){let e=r.scrollDOM.clientHeight<r.scrollDOM.scrollHeight-2,t=0,n=0,i;if(e){for(let o of r.state.facet(K.scrollMargins)){let s=o(r);s?.top&&(t=Math.max(s?.top,t)),s?.bottom&&(n=Math.max(s?.bottom,n))}i=r.scrollDOM.clientHeight-t-n}else i=(r.dom.ownerDocument.defaultView||window).innerHeight;return{marginTop:t,marginBottom:n,selfScroll:e,height:Math.max(r.defaultLineHeight,i-5)}}function ca(r,e){let t=ha(r),{state:n}=r,i=Zt(n.selection,s=>s.empty?r.moveVertically(s,e,t.height):oi(s,e));if(i.eq(n.selection))return!1;let o;if(t.selfScroll){let s=r.coordsAtPos(n.selection.main.head),l=r.scrollDOM.getBoundingClientRect(),a=l.top+t.marginTop,u=l.bottom-t.marginBottom;s&&s.top>a&&s.bottom<u&&(o=K.scrollIntoView(i.main.head,{y:"start",yMargin:s.top-a}))}return r.dispatch(Re(n,i),{effects:o}),!0}var Yl=r=>ca(r,!1),$o=r=>ca(r,!0);function it(r,e,t){let n=r.lineBlockAt(e.head),i=r.moveToLineBoundary(e,t);if(i.head==e.head&&i.head!=(t?n.to:n.from)&&(i=r.moveToLineBoundary(e,t,!1)),!t&&i.head==n.from&&n.length){let o=/^\s*/.exec(r.state.sliceDoc(n.from,Math.min(n.from+100,n.to)))[0].length;o&&e.head!=n.from+o&&(i=y.cursor(n.from+o))}return i}var Fh=r=>Oe(r,e=>it(r,e,!0)),Wh=r=>Oe(r,e=>it(r,e,!1)),zh=r=>Oe(r,e=>it(r,e,!Q(r))),Kh=r=>Oe(r,e=>it(r,e,Q(r))),Uh=r=>Oe(r,e=>y.cursor(r.lineBlockAt(e.head).from,1)),qh=r=>Oe(r,e=>y.cursor(r.lineBlockAt(e.head).to,-1));function Gh(r,e,t){let n=!1,i=Zt(r.selection,o=>{let s=Te(r,o.head,-1)||Te(r,o.head,1)||o.head>0&&Te(r,o.head-1,1)||o.head<r.doc.length&&Te(r,o.head+1,-1);if(!s||!s.end)return o;n=!0;let l=s.start.from==o.head?s.end.to:s.end.from;return t?y.range(o.anchor,l):y.cursor(l)});return n?(e(Re(r,i)),!0):!1}var jh=({state:r,dispatch:e})=>Gh(r,e,!1);function Ce(r,e){let t=Zt(r.state.selection,n=>{let i=e(n);return y.range(n.anchor,i.head,i.goalColumn,i.bidiLevel||void 0,i.assoc)});return t.eq(r.state.selection)?!1:(r.dispatch(Re(r.state,t)),!0)}function fa(r,e){return Ce(r,t=>r.moveByChar(t,e))}var da=r=>fa(r,!Q(r)),ma=r=>fa(r,Q(r));function pa(r,e){return Ce(r,t=>r.moveByGroup(t,e))}var Jh=r=>pa(r,!Q(r)),$h=r=>pa(r,Q(r));var Yh=r=>Ce(r,e=>si(r.state,e,!Q(r))),Xh=r=>Ce(r,e=>si(r.state,e,Q(r)));function ga(r,e){return Ce(r,t=>r.moveVertically(t,e))}var ba=r=>ga(r,!1),ya=r=>ga(r,!0);function xa(r,e){return Ce(r,t=>r.moveVertically(t,e,ha(r).height))}var Xl=r=>xa(r,!1),Ql=r=>xa(r,!0),Qh=r=>Ce(r,e=>it(r,e,!0)),Zh=r=>Ce(r,e=>it(r,e,!1)),_h=r=>Ce(r,e=>it(r,e,!Q(r))),ec=r=>Ce(r,e=>it(r,e,Q(r))),tc=r=>Ce(r,e=>y.cursor(r.lineBlockAt(e.head).from)),nc=r=>Ce(r,e=>y.cursor(r.lineBlockAt(e.head).to)),Zl=({state:r,dispatch:e})=>(e(Re(r,{anchor:0})),!0),_l=({state:r,dispatch:e})=>(e(Re(r,{anchor:r.doc.length})),!0),ea=({state:r,dispatch:e})=>(e(Re(r,{anchor:r.selection.main.anchor,head:0})),!0),ta=({state:r,dispatch:e})=>(e(Re(r,{anchor:r.selection.main.anchor,head:r.doc.length})),!0),rc=({state:r,dispatch:e})=>(e(r.update({selection:{anchor:0,head:r.doc.length},userEvent:"select"})),!0),ic=({state:r,dispatch:e})=>{let t=li(r).map(({from:n,to:i})=>y.range(n,Math.min(i+1,r.doc.length)));return e(r.update({selection:y.create(t),userEvent:"select"})),!0},oc=({state:r,dispatch:e})=>{let t=Zt(r.selection,n=>{let i=Se(r),o=i.resolveStack(n.from,1);if(n.empty){let s=i.resolveStack(n.from,-1);s.node.from>=o.node.from&&s.node.to<=o.node.to&&(o=s)}for(let s=o;s;s=s.next){let{node:l}=s;if((l.from<n.from&&l.to>=n.to||l.to>n.to&&l.from<=n.from)&&s.next)return y.range(l.to,l.from)}return n});return t.eq(r.selection)?!1:(e(Re(r,t)),!0)};function Sa(r,e){let{state:t}=r,n=t.selection,i=t.selection.ranges.slice();for(let o of t.selection.ranges){let s=t.doc.lineAt(o.head);if(e?s.to<r.state.doc.length:s.from>0)for(let l=o;;){let a=r.moveVertically(l,e);if(a.head<s.from||a.head>s.to){i.some(u=>u.head==a.head)||i.push(a);break}else{if(a.head==l.head)break;l=a}}}return i.length==n.ranges.length?!1:(r.dispatch(Re(t,y.create(i,i.length-1))),!0)}var sc=r=>Sa(r,!1),lc=r=>Sa(r,!0),ac=({state:r,dispatch:e})=>{let t=r.selection,n=null;return t.ranges.length>1?n=y.create([t.main]):t.main.empty||(n=y.create([y.cursor(t.main.head)])),n?(e(Re(r,n)),!0):!1};function Ln(r,e){if(r.state.readOnly)return!1;let t="delete.selection",{state:n}=r,i=n.changeByRange(o=>{let{from:s,to:l}=o;if(s==l){let a=e(o);a<s?(t="delete.backward",a=ii(r,a,!1)):a>s&&(t="delete.forward",a=ii(r,a,!0)),s=Math.min(s,a),l=Math.max(l,a)}else s=ii(r,s,!1),l=ii(r,l,!0);return s==l?{range:o}:{changes:{from:s,to:l},range:y.cursor(s,s<o.head?-1:1)}});return i.changes.empty?!1:(r.dispatch(n.update(i,{scrollIntoView:!0,userEvent:t,effects:t=="delete.selection"?K.announce.of(n.phrase("Selection deleted")):void 0})),!0)}function ii(r,e,t){if(r instanceof K)for(let n of r.state.facet(K.atomicRanges).map(i=>i(r)))n.between(e,e,(i,o)=>{i<e&&o>e&&(e=t?o:i)});return e}var Ta=(r,e,t)=>Ln(r,n=>{let i=n.from,{state:o}=r,s=o.doc.lineAt(i),l,a;if(t&&!e&&i>s.from&&i<s.from+200&&!/[^ \t]/.test(l=s.text.slice(0,i-s.from))){if(l[l.length-1]==" ")return i-1;let u=pt(l,o.tabSize),h=u%Xt(o)||Xt(o);for(let c=0;c<h&&l[l.length-1-c]==" ";c++)i--;a=i}else a=z(s.text,i-s.from,e,e)+s.from,a==i&&s.number!=(e?o.doc.lines:1)?a+=e?1:-1:!e&&/[\ufe00-\ufe0f]/.test(s.text.slice(a-s.from,i-s.from))&&(a=z(s.text,a-s.from,!1,!1)+s.from);return a}),Yo=r=>Ta(r,!1,!0);var wa=r=>Ta(r,!0,!1),Ca=(r,e)=>Ln(r,t=>{let n=t.head,{state:i}=r,o=i.doc.lineAt(n),s=i.charCategorizer(n);for(let l=null;;){if(n==(e?o.to:o.from)){n==t.head&&o.number!=(e?i.doc.lines:1)&&(n+=e?1:-1);break}let a=z(o.text,n-o.from,e)+o.from,u=o.text.slice(Math.min(n,a)-o.from,Math.max(n,a)-o.from),h=s(u);if(l!=null&&h!=l)break;(u!=" "||n!=t.head)&&(l=h),n=a}return n}),ka=r=>Ca(r,!1),uc=r=>Ca(r,!0);var hc=r=>Ln(r,e=>{let t=r.lineBlockAt(e.head).to;return e.head<t?t:Math.min(r.state.doc.length,e.head+1)});var cc=r=>Ln(r,e=>{let t=r.moveToLineBoundary(e,!1).head;return e.head>t?t:Math.max(0,e.head-1)}),fc=r=>Ln(r,e=>{let t=r.moveToLineBoundary(e,!0).head;return e.head<t?t:Math.min(r.state.doc.length,e.head+1)});var dc=({state:r,dispatch:e})=>{if(r.readOnly)return!1;let t=r.changeByRange(n=>({changes:{from:n.from,to:n.to,insert:A.of(["",""])},range:y.cursor(n.from)}));return e(r.update(t,{scrollIntoView:!0,userEvent:"input"})),!0},mc=({state:r,dispatch:e})=>{if(r.readOnly)return!1;let t=r.changeByRange(n=>{if(!n.empty||n.from==0||n.from==r.doc.length)return{range:n};let i=n.from,o=r.doc.lineAt(i),s=i==o.from?i-1:z(o.text,i-o.from,!1)+o.from,l=i==o.to?i+1:z(o.text,i-o.from,!0)+o.from;return{changes:{from:s,to:l,insert:r.doc.slice(i,l).append(r.doc.slice(s,i))},range:y.cursor(l)}});return t.changes.empty?!1:(e(r.update(t,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function li(r){let e=[],t=-1;for(let n of r.selection.ranges){let i=r.doc.lineAt(n.from),o=r.doc.lineAt(n.to);if(!n.empty&&n.to==o.from&&(o=r.doc.lineAt(n.to-1)),t>=i.number){let s=e[e.length-1];s.to=o.to,s.ranges.push(n)}else e.push({from:i.from,to:o.to,ranges:[n]});t=o.number+1}return e}function va(r,e,t){if(r.readOnly)return!1;let n=[],i=[];for(let o of li(r)){if(t?o.to==r.doc.length:o.from==0)continue;let s=r.doc.lineAt(t?o.to+1:o.from-1),l=s.length+1;if(t){n.push({from:o.to,to:s.to},{from:o.from,insert:s.text+r.lineBreak});for(let a of o.ranges)i.push(y.range(Math.min(r.doc.length,a.anchor+l),Math.min(r.doc.length,a.head+l)))}else{n.push({from:s.from,to:o.from},{from:o.to,insert:r.lineBreak+s.text});for(let a of o.ranges)i.push(y.range(a.anchor-l,a.head-l))}}return n.length?(e(r.update({changes:n,scrollIntoView:!0,selection:y.create(i,r.selection.mainIndex),userEvent:"move.line"})),!0):!1}var pc=({state:r,dispatch:e})=>va(r,e,!1),gc=({state:r,dispatch:e})=>va(r,e,!0);function Ma(r,e,t){if(r.readOnly)return!1;let n=[];for(let o of li(r))t?n.push({from:o.from,insert:r.doc.slice(o.from,o.to)+r.lineBreak}):n.push({from:o.to,insert:r.lineBreak+r.doc.slice(o.from,o.to)});let i=r.changes(n);return e(r.update({changes:i,selection:r.selection.map(i,t?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}var bc=({state:r,dispatch:e})=>Ma(r,e,!1),yc=({state:r,dispatch:e})=>Ma(r,e,!0),xc=r=>{if(r.state.readOnly)return!1;let{state:e}=r,t=e.changes(li(e).map(({from:i,to:o})=>(i>0?i--:o<e.doc.length&&o++,{from:i,to:o}))),n=Zt(e.selection,i=>{let o;if(r.lineWrapping){let s=r.lineBlockAt(i.head),l=r.coordsAtPos(i.head,i.assoc||1);l&&(o=s.bottom+r.documentTop-l.bottom+r.defaultLineHeight/2)}return r.moveVertically(i,!0,o)}).map(t);return r.dispatch({changes:t,selection:n,scrollIntoView:!0,userEvent:"delete.line"}),!0},Sc=({state:r,dispatch:e})=>(e(r.update(r.replaceSelection(r.lineBreak),{scrollIntoView:!0,userEvent:"input"})),!0);function Tc(r,e){if(/\(\)|\[\]|\{\}/.test(r.sliceDoc(e-1,e+1)))return{from:e,to:e};let t=Se(r).resolveInner(e),n=t.childBefore(e),i=t.childAfter(e),o;return n&&i&&n.to<=e&&i.from>=e&&(o=n.type.prop(H.closedBy))&&o.indexOf(i.name)>-1&&r.doc.lineAt(n.to).from==r.doc.lineAt(i.from).from&&!/\S/.test(r.sliceDoc(n.to,i.from))?{from:n.to,to:i.from}:null}var na=Ea(!1),wc=Ea(!0);function Ea(r){return({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(i=>{let{from:o,to:s}=i,l=e.doc.lineAt(o),a=!r&&o==s&&Tc(e,o);r&&(o=s=(s<=l.to?l:e.doc.lineAt(s)).to);let u=new rt(e,{simulateBreak:o,simulateDoubleBreak:!!a}),h=_r(u,o);for(h==null&&(h=pt(/^\s*/.exec(e.doc.lineAt(o).text)[0],e.tabSize));s<l.to&&/\s/.test(l.text[s-l.from]);)s++;a?{from:o,to:s}=a:o>l.from&&o<l.from+100&&!/\S/.test(l.text.slice(0,o))&&(o=l.from);let c=["",Qt(e,h)];return a&&c.push(Qt(e,u.lineIndent(l.from,-1))),{changes:{from:o,to:s,insert:A.of(c)},range:y.cursor(o+1+c[1].length)}});return t(e.update(n,{scrollIntoView:!0,userEvent:"input"})),!0}}function Xo(r,e){let t=-1;return r.changeByRange(n=>{let i=[];for(let s=n.from;s<=n.to;){let l=r.doc.lineAt(s);l.number>t&&(n.empty||n.to>l.from)&&(e(l,i,n),t=l.number),s=l.to+1}let o=r.changes(i);return{changes:i,range:y.range(o.mapPos(n.anchor,1),o.mapPos(n.head,1))}})}var Cc=({state:r,dispatch:e})=>{if(r.readOnly)return!1;let t=Object.create(null),n=new rt(r,{overrideIndentation:o=>{let s=t[o];return s??-1}}),i=Xo(r,(o,s,l)=>{let a=_r(n,o.from);if(a==null)return;/\S/.test(o.text)||(a=0);let u=/^\s*/.exec(o.text)[0],h=Qt(r,a);(u!=h||l.from<o.from+u.length)&&(t[o.from]=a,s.push({from:o.from,to:o.from+u.length,insert:h}))});return i.changes.empty||e(r.update(i,{userEvent:"indent"})),!0},kc=({state:r,dispatch:e})=>r.readOnly?!1:(e(r.update(Xo(r,(t,n)=>{n.push({from:t.from,insert:r.facet(Dn)})}),{userEvent:"input.indent"})),!0),vc=({state:r,dispatch:e})=>r.readOnly?!1:(e(r.update(Xo(r,(t,n)=>{let i=/^\s*/.exec(t.text)[0];if(!i)return;let o=pt(i,r.tabSize),s=0,l=Qt(r,Math.max(0,o-Xt(r)));for(;s<i.length&&s<l.length&&i.charCodeAt(s)==l.charCodeAt(s);)s++;n.push({from:t.from+s,to:t.from+i.length,insert:l.slice(s)})}),{userEvent:"delete.dedent"})),!0),Mc=r=>(r.setTabFocusMode(),!0);var Ec=[{key:"Ctrl-b",run:ia,shift:da,preventDefault:!0},{key:"Ctrl-f",run:oa,shift:ma},{key:"Ctrl-p",run:aa,shift:ba},{key:"Ctrl-n",run:ua,shift:ya},{key:"Ctrl-a",run:Uh,shift:tc},{key:"Ctrl-e",run:qh,shift:nc},{key:"Ctrl-d",run:wa},{key:"Ctrl-h",run:Yo},{key:"Ctrl-k",run:hc},{key:"Ctrl-Alt-h",run:ka},{key:"Ctrl-o",run:dc},{key:"Ctrl-t",run:mc},{key:"Ctrl-v",run:$o}],Aa=[{key:"ArrowLeft",run:ia,shift:da,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:Ih,shift:Jh,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:zh,shift:_h,preventDefault:!0},{key:"ArrowRight",run:oa,shift:ma,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:Nh,shift:$h,preventDefault:!0},{mac:"Cmd-ArrowRight",run:Kh,shift:ec,preventDefault:!0},{key:"ArrowUp",run:aa,shift:ba,preventDefault:!0},{mac:"Cmd-ArrowUp",run:Zl,shift:ea},{mac:"Ctrl-ArrowUp",run:Yl,shift:Xl},{key:"ArrowDown",run:ua,shift:ya,preventDefault:!0},{mac:"Cmd-ArrowDown",run:_l,shift:ta},{mac:"Ctrl-ArrowDown",run:$o,shift:Ql},{key:"PageUp",run:Yl,shift:Xl},{key:"PageDown",run:$o,shift:Ql},{key:"Home",run:Wh,shift:Zh,preventDefault:!0},{key:"Mod-Home",run:Zl,shift:ea},{key:"End",run:Fh,shift:Qh,preventDefault:!0},{key:"Mod-End",run:_l,shift:ta},{key:"Enter",run:na,shift:na},{key:"Mod-a",run:rc},{key:"Backspace",run:Yo,shift:Yo,preventDefault:!0},{key:"Delete",run:wa,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:ka,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:uc,preventDefault:!0},{mac:"Mod-Backspace",run:cc,preventDefault:!0},{mac:"Mod-Delete",run:fc,preventDefault:!0}].concat(Ec.map(r=>({mac:r.key,run:r.run,shift:r.shift}))),_y=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:Vh,shift:Yh},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:Hh,shift:Xh},{key:"Alt-ArrowUp",run:pc},{key:"Shift-Alt-ArrowUp",run:bc},{key:"Alt-ArrowDown",run:gc},{key:"Shift-Alt-ArrowDown",run:yc},{key:"Mod-Alt-ArrowUp",run:sc},{key:"Mod-Alt-ArrowDown",run:lc},{key:"Escape",run:ac},{key:"Mod-Enter",run:wc},{key:"Alt-l",mac:"Ctrl-l",run:ic},{key:"Mod-i",run:oc,preventDefault:!0},{key:"Mod-[",run:vc},{key:"Mod-]",run:kc},{key:"Mod-Alt-\\",run:Cc},{key:"Shift-Mod-k",run:xc},{key:"Shift-Mod-\\",run:jh},{key:"Mod-/",run:Hl},{key:"Alt-A",run:Fl},{key:"Ctrl-m",mac:"Shift-Alt-m",run:Mc}].concat(Aa);export{ht as Compartment,V as Decoration,y as EditorSelection,j as EditorState,K as EditorView,W as StateEffect,se as StateField,X as Transaction,ke as WidgetType,yl as drawSelection,Kl as history,$l as historyKeymap,Sc as insertNewline,jo as isolateHistory,Do as keymap,On as redo,Aa as standardKeymap,ri as undo};
diff --git a/ext/demo-site/dist/definition-inspector.js b/ext/demo-site/dist/definition-inspector.js
@@ -1,23 +1,9 @@
-import { tokenize } from './syntax.js';
+export { definitionSites } from './syntax.js';
import { outputType, valueText } from './codecs.js';
import { interpretationLabels } from './auto-interpretation.js';
-// Decoration only. The runtime resolves names; this never parses executable code.
-export function definitionSites(source) {
- const seen = new Set();
- return tokenize(source).filter(token => {
- if (token.kind !== 'definition' || token.start > 0 && source[token.start - 1] !== '\n' || seen.has(token.text))
- return false;
- seen.add(token.text);
- return true;
- }).map(token => ({ name: token.text, start: token.start }));
-}
export { valueText as inspectionText } from './codecs.js';
export function definitionInspector(input, request, io) {
- const wrapper = input.parentElement;
- wrapper.classList.add('has-definition-inspector');
- const targets = document.createElement('div');
- targets.className = 'definition-targets';
- wrapper.append(targets);
+ const wrapper = input.dom;
const card = document.createElement('section');
card.className = 'definition-card';
card.hidden = true;
@@ -136,138 +122,104 @@ export function definitionInspector(input, request, io) {
clear();
let selected, source = '', ready = false, busy = false, serial = 0;
let pending, last = '', generation = 0, wasReady = false, scheduled = false;
- const buttons = new Map();
- const declarationIndices = new Map();
- const fragments = new Map();
+ let published;
+ const wired = new WeakSet();
function selectName(name) {
- if (busy || input.disabled || wrapper.classList.contains('composing'))
- return;
- const site = definitionSites(input.value).find(site => site.name === name);
- if (!site)
+ if (busy || input.isDisabled || input.isReadOnly || wrapper.classList.contains('composing'))
return;
- hide();
- input.focus({ preventScroll: true });
- input.setSelectionRange(site.start, site.start + site.name.length);
- input.dispatchEvent(new Event('select'));
+ const site = input.declarations().find(site => site.name === name);
+ if (site) {
+ hide();
+ input.select(site.start, site.start + site.name.length);
+ }
}
- function makeTarget(name) {
- const button = document.createElement('button');
- button.type = 'button';
- button.textContent = name;
- button.dataset.definition = name;
- button.setAttribute('aria-label', `Inspect compiled definition ${name}`);
- button.setAttribute('aria-controls', card.id);
- button.setAttribute('aria-expanded', String(selected === name));
+ function wireTarget(target) {
+ if (wired.has(target))
+ return;
+ wired.add(target);
+ const name = () => target.dataset.definition ?? '';
+ const enabled = () => ready && !busy && target.matches('.definition-name[aria-disabled="false"]') && !wrapper.classList.contains('composing');
let gesture;
let hold;
- const cancelHold = () => { clearTimeout(hold); hold = undefined; };
- button.onpointerdown = event => {
- cancelHold();
+ const cancel = () => { clearTimeout(hold); hold = undefined; };
+ target.onpointerdown = event => {
+ cancel();
const current = { x: event.clientX, y: event.clientY, time: performance.now(), cancelled: false, moved: false, touch: event.pointerType === 'touch' || event.pointerType === 'pen' };
gesture = current;
- if (current.touch)
- hold = setTimeout(() => {
- if (gesture === current && !current.cancelled) {
- current.cancelled = true;
- if (button.isConnected && !button.disabled && !button.hidden)
- selectName(name);
- }
- }, 500);
- };
- button.onpointermove = event => {
- if (gesture && Math.hypot(event.clientX - gesture.x, event.clientY - gesture.y) > 8) {
- gesture.cancelled = gesture.moved = true;
- cancelHold();
+ // Short taps inspect; holds select the identifier for editing. Pointer
+ // cancellation preserves native scrolling.
+ if (current.touch) {
+ event.preventDefault();
+ hold = setTimeout(() => { if (gesture === current && !current.cancelled && enabled()) {
+ current.cancelled = true;
+ selectName(name());
+ } }, 500);
}
};
- button.onpointerup = () => {
- cancelHold();
- // Repeat selection in the release's user gesture: mobile keyboard focus
- // must not depend solely on a timer callback's transient activation.
- if (gesture?.touch && !gesture.moved && performance.now() - gesture.time >= 500 && button.isConnected && !button.disabled && !button.hidden) {
- gesture.cancelled = true;
- selectName(name);
- }
- };
- // Touch generates a compatibility mousedown on release. After a hold it
- // must not steal focus back from the textarea selection we just created.
- button.onmousedown = event => { if (gesture?.touch && gesture.cancelled && !gesture.moved)
- event.preventDefault(); };
- button.onpointercancel = () => { if (gesture)
- gesture.cancelled = true; cancelHold(); };
- button.oncontextmenu = () => {
- cancelHold();
- if (gesture) {
- if (gesture.touch && !gesture.moved && button.isConnected && !button.disabled && !button.hidden)
- selectName(name);
- gesture.cancelled = true;
- }
- };
- button.onclick = event => {
- cancelHold();
+ target.onpointermove = event => { if (gesture && Math.hypot(event.clientX - gesture.x, event.clientY - gesture.y) > 8) {
+ gesture.cancelled = gesture.moved = true;
+ cancel();
+ } };
+ target.onpointerup = () => { cancel(); if (gesture?.touch && !gesture.moved && performance.now() - gesture.time >= 500 && enabled()) {
+ gesture.cancelled = true;
+ selectName(name());
+ } };
+ target.onpointercancel = () => { if (gesture)
+ gesture.cancelled = true; cancel(); };
+ target.oncontextmenu = () => { cancel(); if (gesture) {
+ if (gesture.touch && !gesture.moved && enabled())
+ selectName(name());
+ gesture.cancelled = true;
+ } };
+ target.onclick = event => {
+ cancel();
+ if (event.detail && gesture && (gesture.cancelled || performance.now() - gesture.time > 500))
+ return;
+ if (!enabled())
+ return;
const selection = document.getSelection();
- if (event.detail && (gesture && (gesture.cancelled || performance.now() - gesture.time > 500) ||
- selection && !selection.isCollapsed && (button.contains(selection.anchorNode) || button.contains(selection.focusNode))))
+ if (event.detail > 1)
return;
- if (ready && !busy && !wrapper.classList.contains('composing')) {
- choose(name);
- if (!event.detail && !card.hidden)
- result.focus({ preventScroll: true });
- }
+ // Touch gesture state distinguishes taps, holds and pans even when the
+ // browser retains a previous DOM selection.
+ if (event.detail && !gesture?.touch && selection && !selection.isCollapsed && (target.contains(selection.anchorNode) || target.contains(selection.focusNode)))
+ return;
+ choose(name());
+ if (!card.hidden)
+ result.focus({ preventScroll: true });
};
- targets.append(button);
- return button;
- }
- function position() {
- const mirror = wrapper.querySelector('.syntax-viewport pre');
- if (!mirror)
- return;
- const declarations = [...mirror.querySelectorAll('.syntax-definition')];
- const rect = targets.getBoundingClientRect();
- const style = getComputedStyle(input), visibleHeight = input.clientHeight;
- const height = Math.max(1, Number.parseFloat(style.lineHeight) - 2), font = style.font;
- // Read text geometry before writing overlay styles (no per-name layout flush).
- const geometry = new Map([...buttons.keys()].map(name => {
- const span = declarations[declarationIndices.get(name) ?? -1];
- return [name, span ? [...span.getClientRects()] : []];
- }));
- for (const [name, primary] of buttons) {
- const boxes = geometry.get(name);
- const group = fragments.get(name);
- // A wrapped identifier has separate hit areas, never a large bounding
- // rectangle that also intercepts the expression beside its last line.
- while (group.length < boxes.length) {
- const button = makeTarget(name);
- group[group.length - 1].after(button);
- group.push(button);
- }
- let tabStop = false;
- for (let i = 0; i < group.length; i++) {
- const button = group[i], text = boxes[i];
- button.disabled = primary.disabled;
- button.title = primary.title;
- button.setAttribute('aria-expanded', String(selected === name && !card.hidden));
- const top = text ? text.top + text.height / 2 - rect.top - height / 2 : -100;
- button.hidden = (primary.disabled && !(ready && selected === name && !card.hidden)) || !text || top < 0 || top + height > visibleHeight;
- button.tabIndex = !button.hidden && !button.disabled && !tabStop ? 0 : -1;
- if (button.tabIndex === 0)
- tabStop = true;
- if (text) {
- button.style.top = `${top}px`;
- button.style.left = `${text.left - rect.left}px`;
- button.style.width = `${text.width}px`;
- button.style.height = `${height}px`;
- button.style.font = font;
+ target.addEventListener('keydown', event => {
+ if (['Enter', ' '].includes(event.key)) {
+ event.preventDefault();
+ event.stopPropagation();
+ if (enabled()) {
+ choose(name());
+ if (!card.hidden)
+ result.focus({ preventScroll: true });
}
}
- }
- edit.hidden = input.hidden || !selected || !buttons.has(selected);
- edit.disabled = busy || input.disabled || input.readOnly;
- edit.title = input.readOnly ? 'This source is read-only.' : 'Select the declaration name in the editor.';
- card.style.maxHeight = `${input.hidden ? Math.min(540, innerHeight * .75) : Math.min(input.clientHeight - 16, innerHeight * .75, ioDetected ? 540 : 260)}px`;
- if (selected && !card.hidden && !input.hidden) {
- const top = Number.parseFloat(buttons.get(selected)?.style.top ?? '0') + height + 4;
- card.style.top = `${Math.max(8, Math.min(top, input.clientHeight - card.offsetHeight - 8))}px`;
+ if (event.key === 'Escape') {
+ event.preventDefault();
+ event.stopPropagation();
+ hide();
+ }
+ }, true);
+ }
+ function position() {
+ input.setDefinitions({ ready, busy, ...(selected && !card.hidden ? { selected } : {}), ...(published ? { published } : {}) });
+ for (const target of wrapper.querySelectorAll('.definition-name'))
+ wireTarget(target);
+ const available = selected && input.declarations().some(site => site.name === selected);
+ edit.hidden = input.dom.hidden || !available;
+ edit.disabled = busy || input.isDisabled || input.isReadOnly;
+ edit.title = input.isReadOnly ? 'This source is read-only.' : 'Select the declaration name in the editor.';
+ const height = input.dom.clientHeight;
+ card.style.maxHeight = `${input.dom.hidden ? Math.min(540, innerHeight * .75) : Math.min(height - 16, innerHeight * .75, ioDetected ? 540 : 260)}px`;
+ if (selected && !card.hidden && !input.dom.hidden) {
+ const site = input.declarations().find(site => site.name === selected);
+ const rect = site ? input.view.coordsAtPos(site.start + site.name.length) : null;
+ const top = rect ? rect.bottom - wrapper.getBoundingClientRect().top + 4 : 8;
+ card.style.top = `${Math.max(8, Math.min(top, height - card.offsetHeight - 8))}px`;
}
}
function inspect() {
@@ -309,8 +261,6 @@ export function definitionInspector(input, request, io) {
card.hidden = false;
last = '';
result.textContent = '';
- for (const [key, button] of buttons)
- button.setAttribute('aria-expanded', String(key === name));
position();
schedule();
}
@@ -320,23 +270,26 @@ export function definitionInspector(input, request, io) {
const name = selected;
selected = undefined;
card.hidden = true;
- for (const button of targets.querySelectorAll('button'))
- button.setAttribute('aria-expanded', 'false');
- const target = fragments.get(name ?? '')?.find(button => !button.hidden && !button.disabled);
- (target ?? (busy ? document.getElementById('stop') : undefined))?.focus({ preventScroll: true });
+ position();
+ const target = [...wrapper.querySelectorAll('.definition-name')].find(target => target.dataset.definition === name && target.getAttribute('aria-disabled') === 'false');
+ if (target)
+ target.focus({ preventScroll: true });
+ else if (busy)
+ document.getElementById('stop')?.focus({ preventScroll: true });
}
close.onclick = hide;
card.addEventListener('keydown', event => { if (event.key === 'Escape') {
event.preventDefault();
hide();
} });
- edit.onclick = () => { if (selected && !input.readOnly)
+ edit.onclick = () => { if (selected && !input.isReadOnly)
selectName(selected); };
format.onchange = () => { suspended = false; last = ''; schedule(); };
function update(current, working, publishedNames) {
ready = current;
busy = working;
- if (!input.hidden && card.parentElement !== wrapper) {
+ published = publishedNames;
+ if (!input.dom.hidden && card.parentElement !== wrapper) {
wrapper.append(card);
card.classList.remove('external-definition');
}
@@ -345,23 +298,12 @@ export function definitionInspector(input, request, io) {
last = '';
}
wasReady = ready;
- if (source !== input.value) {
+ if (source !== input.getSource()) {
ioDetected = false;
ioPanel.hidden = true;
clear();
- source = input.value;
- targets.replaceChildren();
- buttons.clear();
- fragments.clear();
- declarationIndices.clear();
- const declarations = tokenize(source).filter(token => token.kind === 'definition');
- for (const site of definitionSites(source)) {
- declarationIndices.set(site.name, declarations.findIndex(token => token.start === site.start));
- const button = makeTarget(site.name);
- buttons.set(site.name, button);
- fragments.set(site.name, [button]);
- }
- if (selected && !buttons.has(selected)) {
+ source = input.getSource();
+ if (selected && !input.declarations().some(site => site.name === selected)) {
selected = undefined;
card.hidden = true;
result.textContent = '';
@@ -374,12 +316,6 @@ export function definitionInspector(input, request, io) {
card.hidden = true;
result.textContent = '';
}
- targets.hidden = input.hidden;
- for (const [name, button] of buttons) {
- const available = !publishedNames || publishedNames.includes(name);
- button.disabled = !ready || busy || !available;
- button.title = available ? `Inspect ${name}` : `${name} is private in this published package. Edit source to compile locally.`;
- }
format.disabled = !ready || busy;
run.disabled = !ready || busy || !ioDetected;
stop.disabled = !ioRunning;
@@ -399,12 +335,10 @@ export function definitionInspector(input, request, io) {
position();
schedule();
}
- input.addEventListener('scroll', position, { passive: true });
- new ResizeObserver(position).observe(input);
+ input.onLayout(position);
new ResizeObserver(position).observe(card);
- new MutationObserver(position).observe(wrapper.querySelector('.syntax-viewport'), { childList: true, subtree: true });
return {
- open(name) { card.classList.toggle('external-definition', input.hidden); if (input.hidden) {
+ open(name) { card.classList.toggle('external-definition', input.dom.hidden); if (input.dom.hidden) {
card.style.top = '';
document.getElementById('package-definition-view').append(card);
}
@@ -438,11 +372,9 @@ export function definitionInspector(input, request, io) {
}
position();
},
- // Stop is an explicit suspension, not an invitation to re-observe a divergent
- // binding automatically as soon as the same source is compiled again.
+ // Stop suspends observation until the user reopens the definition.
stopped(message, suspend = false) { suspended = suspend; ioRunning = false; inputForm.hidden = true; next.disabled = true; stop.disabled = true; status.textContent = message; },
- reset() { suspended = false; ioRunning = false; ioDetected = false; ioPanel.hidden = true; clear(); selected = undefined; pending = undefined; last = ''; card.hidden = true; result.textContent = ''; for (const button of targets.querySelectorAll('button'))
- button.setAttribute('aria-expanded', 'false'); },
+ reset() { suspended = false; ioRunning = false; ioDetected = false; ioPanel.hidden = true; clear(); selected = undefined; pending = undefined; last = ''; card.hidden = true; result.textContent = ''; position(); },
update,
reply(message) {
if (message.id !== pending)
diff --git a/ext/demo-site/dist/import-folds.js b/ext/demo-site/dist/import-folds.js
@@ -0,0 +1,109 @@
+// Hash decorations project canonical UTF-16 document ranges. Editing a revealed
+// hash uses ordinary character-level selection and deletion.
+import { StateField, StateEffect, Transaction, EditorSelection, EditorView, Decoration, WidgetType } from './codemirror.js';
+import { tokenize } from './syntax.js';
+const cachedSites = new WeakMap();
+export function importSites(state) {
+ const cached = cachedSites.get(state.doc);
+ if (cached)
+ return cached;
+ const source = state.doc.toString();
+ const sites = tokenize(source).filter(token => token.kind === 'directive' && token.text === '!import').flatMap(token => {
+ const line = state.doc.lineAt(token.start);
+ if (source.slice(line.from, token.start).trim())
+ return [];
+ const match = /^[ \t]+([a-f0-9]{64})(?=[ \t\r\n]|$)/.exec(source.slice(token.end));
+ if (!match)
+ return [];
+ const from = token.end + match[0].length - 64;
+ return [{ from, to: from + 64, hash: match[1], line: line.number }];
+ });
+ cachedSites.set(state.doc, sites);
+ return sites;
+}
+export const importFocus = StateEffect.define();
+const toggle = StateEffect.define();
+const short = (hash) => hash.slice(0, 3) + '...' + hash.slice(-3);
+class ImportHash extends WidgetType {
+ site;
+ expanded;
+ constructor(site, expanded) {
+ super();
+ this.site = site;
+ this.expanded = expanded;
+ }
+ eq(other) { return this.site.from === other.site.from && this.site.hash === other.site.hash && this.expanded === other.expanded; }
+ toDOM(view) {
+ const button = document.createElement('button');
+ button.type = 'button';
+ button.className = 'import-hash';
+ button.textContent = this.expanded ? this.site.hash : short(this.site.hash);
+ button.dataset.hashFrom = String(this.site.from);
+ button.setAttribute('aria-expanded', String(this.expanded));
+ button.setAttribute('aria-label', `${this.expanded ? 'Collapse' : 'Expand'} import hash ${this.site.hash}`);
+ button.onclick = () => {
+ view.dispatch({ effects: toggle.of(this.site.from), annotations: Transaction.addToHistory.of(false) });
+ view.dom.querySelector(`[data-hash-from="${this.site.from}"]`)?.focus({ preventScroll: true });
+ };
+ // Ctrl+A on a hash control selects the complete canonical program.
+ button.onkeydown = event => {
+ if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'a') {
+ event.preventDefault();
+ view.dispatch({ selection: EditorSelection.single(0, view.state.doc.length), effects: importFocus.of(true) });
+ view.focus();
+ }
+ };
+ return button;
+ }
+ ignoreEvent() { return true; }
+}
+export function selectedImportLines(state, active) {
+ const lines = new Set();
+ for (const range of state.selection.ranges) {
+ if (!active && range.empty)
+ continue;
+ const from = state.doc.lineAt(range.from).number, to = state.doc.lineAt(range.empty ? range.to : Math.max(range.from, range.to - 1)).number;
+ for (let line = from; line <= to; line++)
+ lines.add(line);
+ }
+ return lines;
+}
+function decorate(state, open, active) {
+ const sites = importSites(state), selected = selectedImportLines(state, active), ranges = [];
+ for (const site of sites)
+ ranges.push((selected.has(site.line) ? Decoration.mark({ class: 'import-hash-full' }) :
+ Decoration.replace({ widget: new ImportHash(site, open.has(site.from)) })).range(site.from, site.to));
+ return { open, active, sites, decorations: Decoration.set(ranges, true) };
+}
+export const importFolds = StateField.define({
+ create: state => decorate(state, new Set(), false),
+ update: (old, tr) => {
+ let active = old.active;
+ const open = tr.docChanged ? new Set(old.sites.filter(site => old.open.has(site.from) && !tr.changes.touchesRange(site.from, site.to))
+ .map(site => tr.changes.mapPos(site.from, 1))) : new Set(old.open);
+ if (tr.selection && tr.isUserEvent('select'))
+ active = true;
+ for (const effect of tr.effects) {
+ if (effect.is(toggle)) {
+ if (open.has(effect.value))
+ open.delete(effect.value);
+ else
+ open.add(effect.value);
+ }
+ if (effect.is(importFocus))
+ active = effect.value;
+ }
+ if (!tr.docChanged && !tr.selection && active === old.active && open.size === old.open.size && [...open].every(pos => old.open.has(pos)))
+ return old;
+ return decorate(tr.state, open, active);
+ },
+ provide: field => EditorView.decorations.from(field, value => value.decorations)
+});
+export function syncImportFocus(view) {
+ queueMicrotask(() => {
+ const old = view.state.field(importFolds).active, element = view.dom.ownerDocument.activeElement;
+ const active = element === view.contentDOM ? true : view.dom.contains(element) ? old : false;
+ if (old !== active)
+ view.dispatch({ effects: importFocus.of(active), annotations: Transaction.addToHistory.of(false) });
+ });
+}
diff --git a/ext/demo-site/dist/import-picker.js b/ext/demo-site/dist/import-picker.js
@@ -183,7 +183,7 @@ export function importPicker(options) {
open.onclick = () => {
if (!options.available())
return;
- snapshot = options.source.value;
+ snapshot = options.source.getSource();
backend = options.backend();
search.value = '';
dialog.showModal();
@@ -227,7 +227,7 @@ export function importPicker(options) {
};
get('copy-import').onclick = () => { void navigator.clipboard.writeText(statement()).then(() => message('Import copied.'), () => message('Select and copy the import preview.')); };
function applyPlan() {
- if (!plan || !options.available() || options.source.value !== snapshot || options.backend() !== backend) {
+ if (!plan || !options.available() || options.source.getSource() !== snapshot || options.backend() !== backend) {
stop();
insert.disabled = true;
message('The editor changed. Close and reopen the picker to use the current source.');
@@ -237,17 +237,11 @@ export function importPicker(options) {
finish();
options.source.focus();
if (checked.existing) {
- options.source.setSelectionRange(checked.existing.start, checked.existing.end);
+ options.source.select(checked.existing.start, checked.existing.end);
return;
}
- // Native textarea editing supplies one undo transaction on supported browsers.
- options.source.setSelectionRange(0, 0);
- if (!document.execCommand('insertText', false, checked.statement)) {
- message('Your browser could not insert an undoable edit. Copy the import from the picker.');
- dialog.showModal();
- return;
- }
- options.source.setSelectionRange(0, checked.statement.length);
+ options.source.edit(0, 0, checked.statement);
+ options.source.select(0, checked.statement.length);
}
insert.onclick = () => applyPlan();
return { cancel: () => { if (dialog.open)
diff --git a/ext/demo-site/dist/source-editor.js b/ext/demo-site/dist/source-editor.js
@@ -0,0 +1,177 @@
+import { importFolds, importFocus, importSites, syncImportFocus } from './import-folds.js';
+import { EditorState, StateField, StateEffect, Transaction, EditorSelection, Compartment, EditorView, Decoration, keymap, drawSelection, history, historyKeymap, standardKeymap, isolateHistory, undo, redo, insertNewline } from './codemirror.js';
+import { tokenize, bracketPair, definitionSites } from './syntax.js';
+// Enter inserts a plain newline, preserving explicit source indentation.
+const plainNewline = (view) => !view.state.readOnly && insertNewline(view);
+const definitions = StateEffect.define();
+const definitionState = StateField.define({
+ create: () => ({ ready: false, busy: false }),
+ update: (old, tr) => { for (const effect of tr.effects)
+ if (effect.is(definitions))
+ return effect.value; return old; }
+});
+const presentations = new WeakMap();
+function presentation(state) {
+ let cached = presentations.get(state.doc);
+ if (!cached) {
+ const source = state.doc.toString(), tokens = tokenize(source);
+ cached = { tokens, sites: definitionSites(source, tokens) };
+ presentations.set(state.doc, cached);
+ }
+ return cached;
+}
+function decorations(state) {
+ const { tokens, sites } = presentation(state), selection = state.selection.main;
+ const pair = selection.empty ? bracketPair(tokens, selection.head) : [];
+ const marks = [], imports = importSites(state);
+ for (const token of tokens)
+ if (token.kind && !imports.some(site => token.start >= site.from && token.end <= site.to)) {
+ const match = pair.includes(token.start) ? pair.length === 2 ? ' bracket-match' : ' bracket-unmatched' : '';
+ marks.push(Decoration.mark({ class: `syntax-${token.kind}${match}` }).range(token.start, token.end));
+ }
+ const controls = state.field(definitionState);
+ if (controls.ready)
+ for (const site of sites) {
+ if (controls.published && !controls.published.includes(site.name) || controls.busy && controls.selected !== site.name)
+ continue;
+ marks.push(Decoration.mark({ class: 'definition-name', attributes: {
+ role: 'button', tabindex: controls.busy ? '-1' : '0', 'data-definition': site.name,
+ 'aria-label': `Inspect compiled definition ${site.name}`, 'aria-controls': 'inline-definition',
+ 'aria-expanded': String(controls.selected === site.name), 'aria-disabled': String(controls.busy)
+ } }).range(site.start, site.start + site.name.length));
+ }
+ return Decoration.set(marks, true);
+}
+const syntax = StateField.define({
+ create: decorations,
+ update: (old, tr) => tr.docChanged || tr.selection || tr.effects.some(effect => effect.is(definitions)) ? decorations(tr.state) : old,
+ provide: field => EditorView.decorations.from(field)
+});
+// Symbol.for shares the mounted component across independently bundled test
+// and application entrypoints.
+const editorKey = Symbol.for('tricu.source-editor');
+// Controller and browser fixtures access the same EditorState document,
+// selection and history through the mounted component.
+export function editorFor(element) {
+ const editor = element[editorKey];
+ if (!editor)
+ throw Error('Source editor is not initialized');
+ return editor;
+}
+export class SourceEditor {
+ dom;
+ view;
+ configuration;
+ currentDefinitions = { ready: false, busy: false };
+ availability = new Compartment();
+ changes = new Set();
+ layouts = new Set();
+ locked = false;
+ readonlySource = false;
+ controls = '';
+ pendingEpoch;
+ epoch = 0;
+ constructor(dom) {
+ this.dom = dom;
+ dom.classList.add('source-editor');
+ this.configuration = [
+ definitionState, syntax, importFolds, history(), drawSelection(), EditorState.tabSize.of(2),
+ keymap.of([{ key: 'Enter', run: plainNewline, shift: plainNewline }, ...historyKeymap, ...standardKeymap]), EditorView.lineWrapping,
+ this.availability.of([EditorState.readOnly.of(false), EditorView.editable.of(true)]),
+ EditorView.domEventHandlers({ focus: (_event, view) => syncImportFocus(view), blur: (_event, view) => syncImportFocus(view) }),
+ EditorView.contentAttributes.of({ 'aria-label': 'tricu source (up to 16,384 characters)', spellcheck: 'false', autocorrect: 'off', autocapitalize: 'off' }),
+ EditorView.updateListener.of(update => {
+ if (update.docChanged)
+ this.notify();
+ // Schedule external listeners after EditorView.update so controller
+ // effects can dispatch their own transactions.
+ queueMicrotask(() => { for (const listener of this.layouts)
+ listener(); });
+ }),
+ EditorView.theme({ '&': { height: '100%' }, '.cm-scroller': { overflow: 'auto', fontFamily: 'inherit', lineHeight: 'inherit' },
+ '.cm-content': { padding: '18px 20px', fontFamily: 'inherit', fontVariantLigatures: 'none', minHeight: '100%' },
+ '.cm-line': { padding: '0' }, '.cm-cursor': { borderLeftColor: 'var(--syntax-ink)' },
+ '.cm-selectionBackground, &.cm-focused .cm-selectionBackground': { background: '#799ea066' } })
+ ];
+ this.view = new EditorView({ parent: dom, state: EditorState.create({ extensions: this.configuration }) });
+ this.view.scrollDOM.addEventListener('scroll', () => { for (const listener of this.layouts)
+ listener(); }, { passive: true });
+ new ResizeObserver(() => { for (const listener of this.layouts)
+ listener(); }).observe(dom);
+ dom.addEventListener('compositionstart', () => dom.classList.add('composing'));
+ dom.addEventListener('compositionend', () => dom.classList.remove('composing'));
+ dom[editorKey] = this;
+ }
+ notify() {
+ const epoch = this.epoch;
+ if (this.pendingEpoch === epoch)
+ return;
+ this.pendingEpoch = epoch;
+ queueMicrotask(() => { if (this.pendingEpoch === epoch)
+ this.flushChange(); });
+ }
+ // Controller edits notify after the view update returns; native-input edits
+ // notify at the microtask boundary. Both refresh revisions before the next
+ // user event. Document epochs discard notifications from previous loads.
+ flushChange() {
+ if (this.pendingEpoch !== this.epoch)
+ return;
+ this.pendingEpoch = undefined;
+ for (const listener of this.changes)
+ listener();
+ }
+ undo() { const result = undo(this.view); this.flushChange(); return result; }
+ redo() { const result = redo(this.view); this.flushChange(); return result; }
+ getSource() { return this.view.state.doc.toString(); }
+ getSelection() { const { from, to } = this.view.state.selection.main; return { from, to }; }
+ focus() { this.view.focus(); }
+ declarations() { return presentation(this.view.state).sites; }
+ revealDefinition(name) {
+ const site = this.declarations().find(site => site.name === name);
+ if (!site)
+ return false;
+ this.view.dispatch({ effects: EditorView.scrollIntoView(site.start, { y: 'center' }) });
+ return true;
+ }
+ select(from, to = from) { this.view.dispatch({ selection: EditorSelection.single(from, to), effects: importFocus.of(true), scrollIntoView: true }); this.focus(); }
+ // Loading/restoring documents retires old history; import insertion is a
+ // separate, isolated undoable edit. Notification is explicit for controller edits.
+ replaceSource(source, notify = false) {
+ this.epoch++;
+ this.pendingEpoch = undefined;
+ const state = EditorState.create({ doc: source, extensions: this.configuration });
+ this.view.setState(state.update({ effects: [definitions.of(this.currentDefinitions),
+ this.availability.reconfigure([EditorState.readOnly.of(this.locked || this.readonlySource), EditorView.editable.of(!this.locked && !this.readonlySource)])] }).state);
+ if (notify) {
+ this.pendingEpoch = this.epoch;
+ this.flushChange();
+ }
+ }
+ edit(from, to, text) {
+ this.view.dispatch({ changes: { from, to, insert: text }, selection: EditorSelection.single(from + text.length),
+ annotations: [Transaction.userEvent.of('input'), isolateHistory.of('full')] });
+ this.focus();
+ this.flushChange();
+ }
+ get isDisabled() { return this.locked; }
+ get isReadOnly() { return this.readonlySource; }
+ setAvailability(disabled, readOnly) {
+ if (this.locked === disabled && this.readonlySource === readOnly)
+ return;
+ this.locked = disabled;
+ this.readonlySource = readOnly;
+ this.dom.classList.toggle('disabled', disabled);
+ this.view.dispatch({ effects: this.availability.reconfigure([EditorState.readOnly.of(disabled || readOnly), EditorView.editable.of(!disabled && !readOnly)]) });
+ }
+ setDefinitions(value) {
+ const key = JSON.stringify(value);
+ if (key === this.controls)
+ return;
+ this.controls = key;
+ this.currentDefinitions = value;
+ this.view.dispatch({ effects: definitions.of(value) });
+ }
+ onChange(listener) { this.changes.add(listener); return () => this.changes.delete(listener); }
+ onLayout(listener) { this.layouts.add(listener); }
+ refresh() { this.view.requestMeasure(); }
+}
diff --git a/ext/demo-site/dist/syntax.js b/ext/demo-site/dist/syntax.js
@@ -146,55 +146,13 @@ export function paintSyntax(target, tokens, pair = []) {
}
target.replaceChildren(fragment);
}
-export function syntaxEditor(input) {
- const wrapper = document.createElement('div');
- wrapper.className = 'syntax-editor';
- input.before(wrapper);
- wrapper.append(input);
- const viewport = document.createElement('div');
- viewport.className = 'syntax-viewport';
- viewport.setAttribute('aria-hidden', 'true');
- const mirror = document.createElement('pre');
- viewport.append(mirror);
- wrapper.prepend(viewport);
- let value, tokens = [], lastPair = '', composing = false;
- function scroll() { mirror.style.transform = `translate(${-input.scrollLeft}px, ${-input.scrollTop}px)`; }
- function refresh() {
- wrapper.hidden = input.hidden;
- wrapper.classList.toggle('modified', input.classList.contains('modified'));
- wrapper.classList.toggle('disabled', input.disabled);
- wrapper.classList.toggle('composing', composing);
- const style = getComputedStyle(input);
- // Use the textarea's actual content box, excluding scrollbar and border.
- mirror.style.width = `${input.clientWidth}px`;
- viewport.style.inset = `${style.borderTopWidth} ${style.borderRightWidth} ${style.borderBottomWidth} ${style.borderLeftWidth}`;
- for (const property of ['font-family', 'font-size', 'line-height', 'font-weight', 'font-style', 'font-stretch', 'font-variant-ligatures', 'font-kerning', 'font-feature-settings', 'font-variation-settings', 'letter-spacing', 'padding', 'tab-size', 'text-align'])
- mirror.style.setProperty(property, style.getPropertyValue(property));
- const changed = value !== input.value;
- if (changed) {
- value = input.value;
- tokens = tokenize(value);
- }
- const pair = !composing && document.activeElement === input && input.selectionStart === input.selectionEnd ? bracketPair(tokens, input.selectionStart) : [];
- if (changed || pair.join() !== lastPair) {
- paintSyntax(mirror, tokens, pair);
- lastPair = pair.join();
- // Preserve a trailing empty line without introducing a new line.
- if (!value || value.endsWith('\n'))
- mirror.append(document.createTextNode(' '));
- }
- scroll();
- }
- input.classList.add('syntax-input');
- for (const event of ['input', 'click', 'keyup', 'select', 'focus', 'blur'])
- input.addEventListener(event, refresh);
- input.addEventListener('compositionstart', () => { composing = true; refresh(); });
- input.addEventListener('compositionend', () => { composing = false; refresh(); });
- input.addEventListener('scroll', scroll, { passive: true });
- document.addEventListener('selectionchange', () => { if (document.activeElement === input)
- refresh(); });
- new ResizeObserver(refresh).observe(input);
- new MutationObserver(refresh).observe(input, { attributes: true, attributeFilter: ['hidden', 'disabled', 'class'] });
- refresh();
- return refresh;
+// Unique top-level declaration heads recognized by lexical layout.
+export function definitionSites(source, tokens = tokenize(source)) {
+ const seen = new Set();
+ return tokens.filter(token => {
+ if (token.kind !== 'definition' || token.start > 0 && source[token.start - 1] !== '\n' || seen.has(token.text))
+ return false;
+ seen.add(token.text);
+ return true;
+ }).map(token => ({ name: token.text, start: token.start }));
}
diff --git a/ext/demo-site/index.html b/ext/demo-site/index.html
@@ -52,8 +52,8 @@
<div class="source-heading"><h2 id="source-title">Source</h2><span id="source-label">tricu / stable</span></div>
<p id="playground-intro" class="hint" hidden><strong>Try the Playground:</strong> click an underlined definition name to inspect its compiled tree and choose an interpretation. Write calls as source definitions. IO programs offer an explicit <strong>Run IO</strong> button inside their card.</p>
<p id="authorship">Published package</p><p id="source-availability" class="hint" hidden></p>
- <label class="sr-only" for="source-editor">tricu source (up to 16,384 characters)</label>
- <textarea id="source-editor" rows="18" maxlength="32768" spellcheck="false" autocapitalize="off" autocorrect="off" hidden></textarea>
+ <label class="sr-only" id="source-editor-label">tricu source (up to 16,384 characters)</label>
+ <div id="source-editor" hidden></div>
<pre id="source-notes"><code id="source">Loading Names and values…</code></pre>
<section id="package-definitions" hidden><label for="package-definition-search">Search stored definitions</label><input id="package-definition-search" type="search"><div id="package-definition-list"></div><div id="package-definition-view"></div></section>
<p id="operation-diagnostic" class="error" role="status" hidden></p>
diff --git a/ext/demo-site/javascript.nix b/ext/demo-site/javascript.nix
@@ -0,0 +1,24 @@
+{ pkgs }:
+let
+ editor = import ./codemirror { inherit pkgs; };
+ lock = builtins.fromJSON (builtins.readFile ./codemirror/sources.json);
+ paths = builtins.listToAttrs (map (row: {
+ name = row.name;
+ value = [ (if pkgs.lib.hasSuffix ".js" row.entry
+ then "${editor}/deps/${row.slug}/${pkgs.lib.removeSuffix ".js" row.entry}.d.ts"
+ else "${editor}/types/${row.slug}/${pkgs.lib.removeSuffix ".ts" row.entry}.d.ts") ];
+ }) lock);
+in pkgs.runCommand "arboricx-site-javascript" { nativeBuildInputs = [pkgs.typescript pkgs.python3]; } ''
+ cp -r ${./src} src
+ cp ${./tsconfig.json} tsconfig.json
+ cat > build.json <<'JSON'
+ {"extends":"./tsconfig.json","compilerOptions":{"paths":${builtins.toJSON paths},"skipLibCheck":true}}
+ JSON
+ tsc -p build.json
+ cp ${editor}/codemirror.js dist/
+ for file in ${editor}/licenses/*.txt; do
+ printf '\n--- %s ---\n' "$(basename "$file")"
+ cat "$file"
+ done > dist/codemirror.LICENSE.txt
+ cp -r dist $out
+''
diff --git a/ext/demo-site/release.nix b/ext/demo-site/release.nix
@@ -11,6 +11,7 @@ let
"images" "compiler.json" "packages.json" "environments.json" "tsconfig.json"
];
};
+ javascript = import ./javascript.nix { inherit pkgs; };
artwork = import ./artwork.nix { inherit pkgs; };
dependencies = pkgs.runCommand "arboricx-site-deps" {
nativeBuildInputs = [ pkgs.python3 pkgs.makeWrapper ];
@@ -30,7 +31,7 @@ let
passthru.dependencies = dependencies;
} ''
cd ${siteSource}
- tsc -p tsconfig.json --outDir "$TMPDIR/dist"
+ cp -r ${javascript} "$TMPDIR/dist"
diff -ru dist "$TMPDIR/dist"
mkdir -p $out
cp index.html style.css theme.js catalogue.json compiler.json packages.json environments.json $out/
@@ -39,6 +40,7 @@ let
cmp images/$name ${artwork}/$name
done
cp -r "$TMPDIR/dist" $out/dist
+ chmod -R u+w $out/dist
# JS evaluator drivers/checkpoints are conformance tools, not a site backend.
rm -r $out/dist/conformance
mkdir -p $out/runtime/zig
diff --git a/ext/demo-site/src/app.ts b/ext/demo-site/src/app.ts
@@ -1,8 +1,9 @@
+import { SourceEditor } from './source-editor.js';
import { definitionInspector } from './definition-inspector.js';
import { exampleGroups, exampleGroup, libraryLabel } from './program-catalogue.js';
import { importPicker } from './import-picker.js';
import { localModulesUI } from './local-modules-ui.js';
-import { syntaxEditor, tokenize, paintSyntax } from './syntax.js';
+import { tokenize, paintSyntax } from './syntax.js';
import { backend, backends, runtimeStats, type Backend } from './runtime-backends.js';
import { setupInspector } from './inspector.js';
import { ActiveClock } from './clock.js';
@@ -16,7 +17,7 @@ import type { CompilerMessage } from './compiler-protocol.js';
function el<T extends HTMLElement = HTMLElement>(id: string): T {
const element = document.getElementById(id); if (!element) throw new Error(`Missing element ${id}`); return element as T;
}
-const sourceEditor = el<HTMLTextAreaElement>('source-editor'), refreshSourceSyntax = syntaxEditor(sourceEditor);
+const sourceEditor = new SourceEditor(el('source-editor'));
const compileButton = el<HTMLButtonElement>('compile'), restoreButton = el<HTMLButtonElement>('restore-source');
const downloadButton = el<HTMLButtonElement>('download-bundle'), exportModuleButton = el<HTMLButtonElement>('export-compiled-module');
const backendPicker = el<HTMLSelectElement>('runtime-backend'), programPicker = el<HTMLSelectElement>('program-picker');
@@ -55,7 +56,7 @@ const definitions = definitionInspector(sourceEditor, (id, name, output) => {
worker.postMessage({ type: 'inspect', id, name, output });
}, {
run(name, output, step) {
- if (busy || !worker || draft && (!compiled || sourceEditor.value !== compiledSource || editRevision !== compiledRevision)) return;
+ if (busy || !worker || draft && (!compiled || sourceEditor.getSource() !== compiledSource || editRevision !== compiledRevision)) return;
currentName = name; operation = 'running'; controls(true); deadline.reset(Infinity); deadline.start(); diagnostic();
el('status').textContent = `Running IO · ${name}`;
worker.postMessage({ type: 'run-io', name, output, step });
@@ -69,11 +70,11 @@ const definitions = definitionInspector(sourceEditor, (id, name, output) => {
},
});
const imports = importPicker({ source: sourceEditor, backend: () => backendPicker.value,
- available: () => !busy, editable: () => !busy && !sourceEditor.hidden && !sourceEditor.readOnly,
+ available: () => !busy, editable: () => !busy && !sourceEditor.dom.hidden && !sourceEditor.isReadOnly,
tryLibrary: (library, definition) => { preferredExport = definition; loadBundle(library); },
local: () => localModules.entries(), inputs: () => localModules.inputs() });
function diagnostic(message = ''): void { el('operation-diagnostic').textContent = message; el('operation-diagnostic').hidden = !message; }
-function ready(): boolean { return !!worker && (draft ? compiled && sourceEditor.value === compiledSource && editRevision === compiledRevision : loaded); }
+function ready(): boolean { return !!worker && (draft ? compiled && sourceEditor.getSource() === compiledSource && editRevision === compiledRevision : loaded); }
function controls(working: boolean): void {
busy = working; localModules.disable(busy);
backendPicker.disabled = busy; programPicker.disabled = busy || !entries.length;
@@ -83,22 +84,22 @@ function controls(working: boolean): void {
compileButton.disabled = busy || !draft || ready(); compileButton.hidden = !draft; restoreButton.hidden = !draft;
restoreButton.disabled = busy || originalSource === undefined;
exportModuleButton.disabled = busy || !draft || !ready(); downloadButton.disabled = busy || draft || downloadHash() === undefined;
- sourceEditor.disabled = busy && operation !== 'compiling'; sourceEditor.readOnly = originalSource === undefined && !draft;
- const editable = !sourceEditor.hidden && (draft || originalSource !== undefined);
+ sourceEditor.setAvailability(busy && operation !== 'compiling', originalSource === undefined && !draft);
+ const editable = !sourceEditor.dom.hidden && (draft || originalSource !== undefined);
el('playground-intro').hidden = selected?.id !== 'names-values' || !editable;
el('source-title').textContent = editable ? 'Source' : sourceAvailable ? 'Read-only source' : loaded ? 'Compiled package' : 'Package information';
el('source-availability').hidden = editable || !loaded;
el('source-availability').textContent = 'Browse stored definitions below, or import this module into your own source. Inspection does not execute IO.';
- el('package-definitions').hidden = !loaded || !sourceEditor.hidden;
+ el('package-definitions').hidden = !loaded || !sourceEditor.dom.hidden;
el<HTMLButtonElement>('reload-package').hidden = draft || !selection || !!worker;
el<HTMLButtonElement>('stored-download').disabled = busy || draft || !loaded || !worker;
el<HTMLSelectElement>('stored-definition').disabled = el<HTMLSelectElement>('stored-format').disabled = busy || draft || !loaded;
el('authorship').textContent = draft ? 'Local draft · your authored code (not published)' : loaded ? 'Published package · verified executable' : 'Published selection · not yet verified';
- const modified = draft && !ready(); el('authorship').classList.toggle('modified', modified); sourceEditor.classList.toggle('modified', modified);
+ const modified = draft && !ready(); el('authorship').classList.toggle('modified', modified); sourceEditor.dom.classList.toggle('modified', modified);
for (const button of document.querySelectorAll<HTMLButtonElement>('[data-compiler-example]')) button.disabled = busy;
stopButton.disabled = !busy && !draft; stopButton.hidden = !busy; shareButton.disabled = busy || draft || !loaded;
el<HTMLButtonElement>('reset').disabled = busy;
- refreshSourceSyntax(); definitions.update(!sourceEditor.hidden && ready() || sourceEditor.hidden && loaded && !!worker, busy, draft ? undefined : publishedNames);
+ sourceEditor.refresh(); definitions.update(!sourceEditor.dom.hidden && ready() || sourceEditor.dom.hidden && loaded && !!worker, busy, draft ? undefined : publishedNames);
for (const button of el('package-definition-list').querySelectorAll<HTMLButtonElement>('button')) button.disabled = busy || !loaded;
}
function renderPublishedNames(): void {
@@ -198,12 +199,12 @@ function newWorker(preserveSource = false): void {
if (publishedNames.includes(currentName)) el<HTMLSelectElement>('stored-definition').value = currentName;
el('compiler-stats').textContent = 'Published package · no local compilation.';
el('package-info').textContent = `SHA-256 verified · ${data.nodes.toLocaleString()} stored DAG nodes · ${publishedNames.length} export(s) · ${data.hash}`;
- if (!preserveSource || originalSource === undefined) { originalSource = selected?.environment !== undefined && data.source !== null ? data.source : undefined; sourceEditor.value = originalSource ?? ''; }
- sourceEditor.hidden = originalSource === undefined; el('source-notes').hidden = !sourceEditor.hidden;
+ if (!preserveSource || originalSource === undefined) { originalSource = selected?.environment !== undefined && data.source !== null ? data.source : undefined; sourceEditor.replaceSource(originalSource ?? ''); }
+ sourceEditor.dom.hidden = originalSource === undefined; el('source-notes').hidden = !sourceEditor.dom.hidden;
sourceAvailable = data.source !== null; el('source-label').textContent = sourceAvailable ? 'Curated tricu / stable' : 'Package metadata';
el('source').textContent = data.source ?? `Verified package metadata\n${JSON.stringify(data.metadata,null,2)}`;
if (data.source !== null) paintSyntax(el('source'), tokenize(data.source));
- el<HTMLInputElement>('package-definition-search').value = sourceEditor.hidden && requested && publishedNames.includes(requested) ? requested : ''; renderPublishedNames(); idle(); el('status').textContent = 'Ready';
+ el<HTMLInputElement>('package-definition-search').value = sourceEditor.dom.hidden && requested && publishedNames.includes(requested) ? requested : ''; renderPublishedNames(); idle(); el('status').textContent = 'Ready';
};
current.onerror = event => { if (worker === current) { event.preventDefault(); loaded = false; finish(event.message || 'Worker failed.',true); } };
current.postMessage({type:'load',...selection});
@@ -215,13 +216,13 @@ function selectExample(entry: CatalogueEntry): void {
function select(entry: CatalogueEntry, release?: Release): void {
definitions.reset(); draft = scratch = false; originalSource = undefined; sourceAvailable = false;
dispose(); diagnostic(); loaded = false; selected = entry; publishedNames = [];
- selection = {hash:entry.hash,localId:entry.id}; hashInput.value = entry.hash; sourceEditor.hidden = true; el('source-notes').hidden = false;
+ selection = {hash:entry.hash,localId:entry.id}; hashInput.value = entry.hash; sourceEditor.dom.hidden = true; el('source-notes').hidden = false;
const pinned = release ?? releases.find(r=>r.hash===entry.hash&&r.demo===entry.id); chooseProgram(`demo:${entry.id}`,pinned?.version); showRelease(pinned); newWorker();
}
function invalidateProgram(): void {
definitions.reset(); draft = scratch = false; originalSource = undefined; sourceAvailable = false;
dispose(); diagnostic(); loaded = false; selection = undefined; selected = undefined; publishedNames = [];
- sourceEditor.hidden = true; el('source-notes').hidden = false; el('source').textContent = 'Load the selected program to inspect its source or package notes.';
+ sourceEditor.dom.hidden = true; el('source-notes').hidden = false; el('source').textContent = 'Load the selected program to inspect its source or package notes.';
el('package-info').textContent = 'No bundle loaded.'; showRelease(); renderPublishedNames(); controls(false); el('status').textContent = 'Load package';
}
function loadBundle(release?: Release): void {
@@ -346,22 +347,22 @@ downloadButton.onclick = () => {
current.postMessage({ type: 'load', hash });
};
-sourceEditor.addEventListener('compositionstart',()=>{composing=true;cancelIdleCompile();});
-sourceEditor.addEventListener('compositionend',()=>{composing=false;if(draft)queueCompile();});
-sourceEditor.oninput = () => {
+sourceEditor.dom.addEventListener('compositionstart',()=>{composing=true;cancelIdleCompile();});
+sourceEditor.dom.addEventListener('compositionend',()=>{composing=false;if(draft)queueCompile();});
+sourceEditor.onChange(() => {
if (busy && operation !== 'compiling') return;
editRevision++; diagnostic(); el('compile-diagnostic').hidden=true;
if (operation === 'compiling') { draft=true;controls(true);queueCompile();return; }
if (!worker || !compiled || busy) dispose();
- draft = compiled || scratch || sourceEditor.value !== originalSource;
+ draft = compiled || scratch || sourceEditor.getSource() !== originalSource;
controls(false);
if (!draft && selection) newWorker(true); else {el('status').textContent='Changes pending';queueCompile();}
-};
-restoreButton.onclick=()=>{if(originalSource===undefined||busy)return;dispose();sourceEditor.value=originalSource;sourceEditor.dispatchEvent(new Event('input'));};
+});
+restoreButton.onclick=()=>{if(originalSource===undefined||busy)return;dispose();sourceEditor.replaceSource(originalSource,true);};
compileButton.onclick=()=>compileDraft();
function compileDraft(): void {
if(!draft||busy)return;
- const snapshot={revision:editRevision,source:sourceEditor.value};dispose();operation='compiling';diagnostic();el('compile-diagnostic').hidden=true;
+ const snapshot={revision:editRevision,source:sourceEditor.getSource()};dispose();operation='compiling';diagnostic();el('compile-diagnostic').hidden=true;
try {
sourceText(snapshot.source);const current=new Worker(workerURL(),{type:'module'});worker=current;
controls(true);deadline.reset(Infinity);deadline.start();el('status').textContent='Compiling';
@@ -391,7 +392,7 @@ for(const button of document.querySelectorAll<HTMLButtonElement>('[data-compiler
const source=button.dataset['compilerExample']==='module'&&math?`!import ${math.manifest} as N\n!export answer\nanswer = N.add 40 2`:examples[button.dataset['compilerExample'] as keyof typeof examples];
if(!source)return;
definitions.reset();dispose();diagnostic();chooseProgram('');scratch=draft=true;originalSource=undefined;loaded=false;selection=undefined;selected=undefined;editRevision++;
- sourceEditor.hidden=false;el('source-notes').hidden=true;sourceEditor.value=source;controls(false);el('package-info').textContent='Scratch program · no published bundle selected.';showRelease();el('source-label').textContent='Scratch program · explicit modules or contract helpers';el('status').textContent='Changes pending';queueCompile();
+ sourceEditor.dom.hidden=false;el('source-notes').hidden=true;sourceEditor.replaceSource(source);controls(false);el('package-info').textContent='Scratch program · no published bundle selected.';showRelease();el('source-label').textContent='Scratch program · explicit modules or contract helpers';el('status').textContent='Changes pending';queueCompile();
};
function loadFragment(): boolean {
const fragment=new URLSearchParams(location.hash.slice(1)),requested=fragment.get('bundle');if(!requested)return false;
diff --git a/ext/demo-site/src/codemirror.d.ts b/ext/demo-site/src/codemirror.d.ts
@@ -0,0 +1,4 @@
+// Public types for the pinned, locally bundled editor. Resolved by javascript.nix.
+export {EditorState, StateField, StateEffect, Transaction, EditorSelection, Compartment, type Range, type Extension} from '@codemirror/state';
+export {EditorView, Decoration, WidgetType, keymap, drawSelection} from '@codemirror/view';
+export {history, historyKeymap, standardKeymap, isolateHistory, undo, redo, insertNewline} from '@codemirror/commands';
diff --git a/ext/demo-site/src/definition-inspector.ts b/ext/demo-site/src/definition-inspector.ts
@@ -1,4 +1,5 @@
-import { tokenize } from './syntax.js';
+import type { SourceEditor } from './source-editor.js';
+export { definitionSites } from './syntax.js';
import { outputType, valueText, type OutputType, type ValueView } from './codecs.js';
import { interpretationLabels, type InspectionFormat } from './auto-interpretation.js';
import type { WorkerMessage, InspectionReply } from './protocol.js';
@@ -9,19 +10,9 @@ interface IOControls {
resume(value?: string): void;
}
-// Decoration only. The runtime resolves names; this never parses executable code.
-export function definitionSites(source: string): { name: string; start: number }[] {
- const seen = new Set<string>();
- return tokenize(source).filter(token => {
- if (token.kind !== 'definition' || token.start > 0 && source[token.start - 1] !== '\n' || seen.has(token.text)) return false;
- seen.add(token.text); return true;
- }).map(token => ({ name: token.text, start: token.start }));
-}
export { valueText as inspectionText } from './codecs.js';
-export function definitionInspector(input: HTMLTextAreaElement, request: (id: number, name: string, output: InspectionFormat) => void, io: IOControls) {
- const wrapper = input.parentElement!;
- wrapper.classList.add('has-definition-inspector');
- const targets = document.createElement('div'); targets.className = 'definition-targets'; wrapper.append(targets);
+export function definitionInspector(input: SourceEditor, request: (id: number, name: string, output: InspectionFormat) => void, io: IOControls) {
+ const wrapper = input.dom;
const card = document.createElement('section'); card.className = 'definition-card'; card.hidden = true;
card.id = 'inline-definition'; card.setAttribute('aria-label', 'Compiled definition');
const title = document.createElement('strong'), format = document.createElement('select');
@@ -87,109 +78,59 @@ export function definitionInspector(input: HTMLTextAreaElement, request: (id: nu
clear();
let selected: string | undefined, source = '', ready = false, busy = false, serial = 0;
let pending: number | undefined, last = '', generation = 0, wasReady = false, scheduled = false;
- const buttons = new Map<string, HTMLButtonElement>();
- const declarationIndices = new Map<string, number>();
- const fragments = new Map<string, HTMLButtonElement[]>();
+ let published:string[]|undefined;
+ const wired = new WeakSet<HTMLElement>();
function selectName(name: string): void {
- if (busy || input.disabled || wrapper.classList.contains('composing')) return;
- const site = definitionSites(input.value).find(site => site.name === name);
- if (!site) return;
- hide(); input.focus({ preventScroll: true });
- input.setSelectionRange(site.start, site.start + site.name.length);
- input.dispatchEvent(new Event('select'));
+ if (busy || input.isDisabled || input.isReadOnly || wrapper.classList.contains('composing')) return;
+ const site = input.declarations().find(site => site.name === name);
+ if (site) { hide(); input.select(site.start, site.start + site.name.length); }
}
- function makeTarget(name: string): HTMLButtonElement {
- const button = document.createElement('button'); button.type = 'button'; button.textContent = name;
- button.dataset.definition = name;
- button.setAttribute('aria-label', `Inspect compiled definition ${name}`);
- button.setAttribute('aria-controls', card.id); button.setAttribute('aria-expanded', String(selected === name));
- // Short taps inspect. A touch hold selects the real textarea identifier;
- // buttons do not acquire native editable-word selection on their own.
- // Never cancel pointerdown or the context menu, and cancel holds on drags.
- type Gesture = { x: number; y: number; time: number; cancelled: boolean; moved: boolean; touch: boolean };
- let gesture: Gesture | undefined;
- let hold: ReturnType<typeof setTimeout> | undefined;
- const cancelHold = () => { clearTimeout(hold); hold = undefined; };
- button.onpointerdown = event => {
- cancelHold();
- const current: Gesture = { x: event.clientX, y: event.clientY, time: performance.now(), cancelled: false, moved: false, touch: event.pointerType === 'touch' || event.pointerType === 'pen' };
- gesture = current;
- if (current.touch) hold = setTimeout(() => {
- if (gesture === current && !current.cancelled) { current.cancelled = true; if (button.isConnected && !button.disabled && !button.hidden) selectName(name); }
- }, 500);
- };
- button.onpointermove = event => {
- if (gesture && Math.hypot(event.clientX - gesture.x, event.clientY - gesture.y) > 8) {
- gesture.cancelled = gesture.moved = true; cancelHold();
- }
- };
- button.onpointerup = () => {
- cancelHold();
- // Repeat selection in the release's user gesture: mobile keyboard focus
- // must not depend solely on a timer callback's transient activation.
- if (gesture?.touch && !gesture.moved && performance.now() - gesture.time >= 500 && button.isConnected && !button.disabled && !button.hidden) {
- gesture.cancelled = true; selectName(name);
- }
- };
- // Touch generates a compatibility mousedown on release. After a hold it
- // must not steal focus back from the textarea selection we just created.
- button.onmousedown = event => { if (gesture?.touch && gesture.cancelled && !gesture.moved) event.preventDefault(); };
- button.onpointercancel = () => { if (gesture) gesture.cancelled = true; cancelHold(); };
- button.oncontextmenu = () => {
- cancelHold();
- if (gesture) { if (gesture.touch && !gesture.moved && button.isConnected && !button.disabled && !button.hidden) selectName(name); gesture.cancelled = true; }
+ function wireTarget(target: HTMLElement): void {
+ if (wired.has(target)) return; wired.add(target);
+ const name = () => target.dataset.definition ?? '';
+ const enabled = () => ready && !busy && target.matches('.definition-name[aria-disabled="false"]') && !wrapper.classList.contains('composing');
+ let gesture: {x:number;y:number;time:number;cancelled:boolean;moved:boolean;touch:boolean}|undefined;
+ let hold:ReturnType<typeof setTimeout>|undefined;
+ const cancel = () => {clearTimeout(hold);hold=undefined;};
+ target.onpointerdown = event => {
+ cancel(); const current={x:event.clientX,y:event.clientY,time:performance.now(),cancelled:false,moved:false,touch:event.pointerType==='touch'||event.pointerType==='pen'}; gesture=current;
+ // Short taps inspect; holds select the identifier for editing. Pointer
+ // cancellation preserves native scrolling.
+ if(current.touch) {event.preventDefault();hold=setTimeout(()=>{if(gesture===current&&!current.cancelled&&enabled()){current.cancelled=true;selectName(name());}},500);}
+
};
- button.onclick = event => {
- cancelHold();
- const selection = document.getSelection();
- if (event.detail && (gesture && (gesture.cancelled || performance.now() - gesture.time > 500) ||
- selection && !selection.isCollapsed && (button.contains(selection.anchorNode) || button.contains(selection.focusNode)))) return;
- if (ready && !busy && !wrapper.classList.contains('composing')) {
- choose(name);
- if (!event.detail && !card.hidden) result.focus({ preventScroll: true });
- }
+ target.onpointermove = event => {if(gesture&&Math.hypot(event.clientX-gesture.x,event.clientY-gesture.y)>8){gesture.cancelled=gesture.moved=true;cancel();}};
+ target.onpointerup = () => {cancel();if(gesture?.touch&&!gesture.moved&&performance.now()-gesture.time>=500&&enabled()){gesture.cancelled=true;selectName(name());}};
+ target.onpointercancel = () => {if(gesture)gesture.cancelled=true;cancel();};
+ target.oncontextmenu = () => {cancel();if(gesture){if(gesture.touch&&!gesture.moved&&enabled())selectName(name());gesture.cancelled=true;}};
+ target.onclick = event => {
+ cancel(); if(event.detail&&gesture&&(gesture.cancelled||performance.now()-gesture.time>500))return;
+ if(!enabled())return;
+ const selection=document.getSelection();
+ if(event.detail>1)return;
+ // Touch gesture state distinguishes taps, holds and pans even when the
+ // browser retains a previous DOM selection.
+ if(event.detail&&!gesture?.touch&&selection&&!selection.isCollapsed&&(target.contains(selection.anchorNode)||target.contains(selection.focusNode)))return;
+ choose(name());if(!card.hidden)result.focus({preventScroll:true});
};
- targets.append(button); return button;
+ target.addEventListener('keydown',event=>{
+ if(['Enter',' '].includes(event.key)){event.preventDefault();event.stopPropagation();if(enabled()){choose(name());if(!card.hidden)result.focus({preventScroll:true});}}
+ if(event.key==='Escape'){event.preventDefault();event.stopPropagation();hide();}
+ },true);
}
function position(): void {
- const mirror = wrapper.querySelector('.syntax-viewport pre'); if (!mirror) return;
- const declarations = [...mirror.querySelectorAll<HTMLElement>('.syntax-definition')];
- const rect = targets.getBoundingClientRect();
- const style = getComputedStyle(input), visibleHeight = input.clientHeight;
- const height = Math.max(1, Number.parseFloat(style.lineHeight) - 2), font = style.font;
- // Read text geometry before writing overlay styles (no per-name layout flush).
- const geometry = new Map([...buttons.keys()].map(name => {
- const span = declarations[declarationIndices.get(name) ?? -1];
- return [name, span ? [...span.getClientRects()] : []] as const;
- }));
- for (const [name, primary] of buttons) {
- const boxes = geometry.get(name)!;
- const group = fragments.get(name)!;
- // A wrapped identifier has separate hit areas, never a large bounding
- // rectangle that also intercepts the expression beside its last line.
- while (group.length < boxes.length) { const button = makeTarget(name); group[group.length - 1]!.after(button); group.push(button); }
- let tabStop = false;
- for (let i = 0; i < group.length; i++) {
- const button = group[i]!, text = boxes[i];
- button.disabled = primary.disabled; button.title = primary.title;
- button.setAttribute('aria-expanded', String(selected === name && !card.hidden));
- const top = text ? text.top + text.height / 2 - rect.top - height / 2 : -100;
- button.hidden = (primary.disabled && !(ready && selected === name && !card.hidden)) || !text || top < 0 || top + height > visibleHeight;
- button.tabIndex = !button.hidden && !button.disabled && !tabStop ? 0 : -1;
- if (button.tabIndex === 0) tabStop = true;
- if (text) {
- button.style.top = `${top}px`; button.style.left = `${text.left - rect.left}px`;
- button.style.width = `${text.width}px`; button.style.height = `${height}px`;
- button.style.font = font;
- }
- }
- }
- edit.hidden = input.hidden || !selected || !buttons.has(selected); edit.disabled = busy || input.disabled || input.readOnly;
- edit.title = input.readOnly ? 'This source is read-only.' : 'Select the declaration name in the editor.';
- card.style.maxHeight = `${input.hidden ? Math.min(540, innerHeight * .75) : Math.min(input.clientHeight - 16, innerHeight * .75, ioDetected ? 540 : 260)}px`;
- if (selected && !card.hidden && !input.hidden) {
- const top = Number.parseFloat(buttons.get(selected)?.style.top ?? '0') + height + 4;
- card.style.top = `${Math.max(8, Math.min(top, input.clientHeight - card.offsetHeight - 8))}px`;
+ input.setDefinitions({ready,busy,...(selected&&!card.hidden?{selected}:{}),...(published?{published}:{})});
+ for(const target of wrapper.querySelectorAll<HTMLElement>('.definition-name'))wireTarget(target);
+ const available=selected&&input.declarations().some(site=>site.name===selected);
+ edit.hidden = input.dom.hidden || !available; edit.disabled = busy || input.isDisabled || input.isReadOnly;
+ edit.title = input.isReadOnly ? 'This source is read-only.' : 'Select the declaration name in the editor.';
+ const height=input.dom.clientHeight;
+ card.style.maxHeight = `${input.dom.hidden ? Math.min(540,innerHeight*.75) : Math.min(height-16,innerHeight*.75,ioDetected?540:260)}px`;
+ if(selected&&!card.hidden&&!input.dom.hidden){
+ const site=input.declarations().find(site=>site.name===selected);
+ const rect=site?input.view.coordsAtPos(site.start+site.name.length):null;
+ const top=rect?rect.bottom-wrapper.getBoundingClientRect().top+4:8;
+ card.style.top=`${Math.max(8,Math.min(top,height-card.offsetHeight-8))}px`;
}
}
function inspect(): void {
@@ -205,44 +146,34 @@ export function definitionInspector(input: HTMLTextAreaElement, request: (id: nu
function choose(name: string): void {
if (selected === name && !card.hidden && !suspended) { hide(); return; }
selected = name; suspended = false; ioDetected = false; lineInput.value = ''; get('input-error').textContent = ''; inputForm.hidden = true; next.disabled = true; ioPanel.hidden = true; terminal.textContent = ''; trace.replaceChildren(); clear(); format.value = 'auto'; title.textContent = name; card.hidden = false; last = ''; result.textContent = '';
- for (const [key, button] of buttons) button.setAttribute('aria-expanded', String(key === name));
position(); schedule();
}
function hide(): void {
if (ioRunning) io.stop();
const name = selected; selected = undefined; card.hidden = true;
- for (const button of targets.querySelectorAll('button')) button.setAttribute('aria-expanded', 'false');
- const target = fragments.get(name ?? '')?.find(button => !button.hidden && !button.disabled);
- (target ?? (busy ? document.getElementById('stop') : undefined))?.focus({ preventScroll: true });
+ position();
+ const target=[...wrapper.querySelectorAll<HTMLElement>('.definition-name')].find(target=>target.dataset.definition===name&&target.getAttribute('aria-disabled')==='false');
+ if(target)target.focus({preventScroll:true});else if(busy)document.getElementById('stop')?.focus({preventScroll:true});
+
}
close.onclick = hide;
card.addEventListener('keydown', event => { if (event.key === 'Escape') { event.preventDefault(); hide(); } });
- edit.onclick = () => { if (selected && !input.readOnly) selectName(selected); };
+ edit.onclick = () => { if (selected && !input.isReadOnly) selectName(selected); };
format.onchange = () => { suspended = false; last = ''; schedule(); };
function update(current: boolean, working: boolean, publishedNames?: string[]): void {
- ready = current; busy = working;
- if (!input.hidden && card.parentElement !== wrapper) { wrapper.append(card); card.classList.remove('external-definition'); }
+ ready = current; busy = working; published=publishedNames;
+ if (!input.dom.hidden && card.parentElement !== wrapper) { wrapper.append(card); card.classList.remove('external-definition'); }
if (ready && !wasReady) { generation++; last = ''; }
wasReady = ready;
- if (source !== input.value) {
+ if (source !== input.getSource()) {
ioDetected = false; ioPanel.hidden = true; clear();
- source = input.value; targets.replaceChildren(); buttons.clear(); fragments.clear(); declarationIndices.clear();
- const declarations = tokenize(source).filter(token => token.kind === 'definition');
- for (const site of definitionSites(source)) {
- declarationIndices.set(site.name, declarations.findIndex(token => token.start === site.start));
- const button = makeTarget(site.name); buttons.set(site.name, button); fragments.set(site.name, [button]);
- }
- if (selected && !buttons.has(selected)) { selected = undefined; card.hidden = true; result.textContent = ''; }
+ source = input.getSource();
+ if(selected&&!input.declarations().some(site=>site.name===selected)){selected=undefined;card.hidden=true;result.textContent='';}
}
+
if (selected && publishedNames && !publishedNames.includes(selected)) {
selected = undefined; pending = undefined; last = ''; card.hidden = true; result.textContent = '';
}
- targets.hidden = input.hidden;
- for (const [name, button] of buttons) {
- const available = !publishedNames || publishedNames.includes(name);
- button.disabled = !ready || busy || !available;
- button.title = available ? `Inspect ${name}` : `${name} is private in this published package. Edit source to compile locally.`;
- }
format.disabled = !ready || busy;
run.disabled = !ready || busy || !ioDetected; stop.disabled = !ioRunning; returnFormat.disabled = step.disabled = busy;
copy.disabled = download.disabled = busy || !saved;
@@ -252,12 +183,10 @@ export function definitionInspector(input: HTMLTextAreaElement, request: (id: nu
}
position(); schedule();
}
- input.addEventListener('scroll', position, { passive: true });
- new ResizeObserver(position).observe(input);
+ input.onLayout(position);
new ResizeObserver(position).observe(card);
- new MutationObserver(position).observe(wrapper.querySelector('.syntax-viewport')!, { childList: true, subtree: true });
return {
- open(name: string): void { card.classList.toggle('external-definition', input.hidden); if (input.hidden) { card.style.top = ''; document.getElementById('package-definition-view')!.append(card); } else wrapper.append(card); choose(name); },
+ open(name: string): void { card.classList.toggle('external-definition', input.dom.hidden); if (input.dom.hidden) { card.style.top = ''; document.getElementById('package-definition-view')!.append(card); } else wrapper.append(card); choose(name); },
event(message: WorkerMessage | CompilerMessage): void {
if (!ioRunning) return;
if (message.type === 'output') { terminal.textContent += message.text; terminal.scrollTop = terminal.scrollHeight; }
@@ -266,10 +195,9 @@ export function definitionInspector(input: HTMLTextAreaElement, request: (id: nu
if (message.type === 'done') { ioRunning = false; inputForm.hidden = true; next.disabled = true; status.textContent = 'IO finished · Returned value'; save(message.result); }
position();
},
- // Stop is an explicit suspension, not an invitation to re-observe a divergent
- // binding automatically as soon as the same source is compiled again.
+ // Stop suspends observation until the user reopens the definition.
stopped(message: string, suspend = false): void { suspended = suspend; ioRunning = false; inputForm.hidden = true; next.disabled = true; stop.disabled = true; status.textContent = message; },
- reset(): void { suspended = false; ioRunning = false; ioDetected = false; ioPanel.hidden = true; clear(); selected = undefined; pending = undefined; last = ''; card.hidden = true; result.textContent = ''; for (const button of targets.querySelectorAll('button')) button.setAttribute('aria-expanded', 'false'); },
+ reset(): void { suspended = false; ioRunning = false; ioDetected = false; ioPanel.hidden = true; clear(); selected = undefined; pending = undefined; last = ''; card.hidden = true; result.textContent = ''; position(); },
update,
reply(message: InspectionReply): boolean {
if (message.id !== pending) return false;
diff --git a/ext/demo-site/src/import-folds.ts b/ext/demo-site/src/import-folds.ts
@@ -0,0 +1,83 @@
+// Hash decorations project canonical UTF-16 document ranges. Editing a revealed
+// hash uses ordinary character-level selection and deletion.
+import {EditorState, StateField, StateEffect, Transaction, EditorSelection, EditorView, Decoration, WidgetType, type Range} from './codemirror.js';
+import {tokenize} from './syntax.js';
+export interface ImportSite {from:number;to:number;hash:string;line:number}
+const cachedSites=new WeakMap<EditorState['doc'],ImportSite[]>();
+export function importSites(state:EditorState):ImportSite[] {
+ const cached=cachedSites.get(state.doc);if(cached)return cached;
+ const source=state.doc.toString();
+ const sites=tokenize(source).filter(token=>token.kind==='directive'&&token.text==='!import').flatMap(token=>{
+ const line=state.doc.lineAt(token.start);
+ if(source.slice(line.from,token.start).trim())return [];
+ const match=/^[ \t]+([a-f0-9]{64})(?=[ \t\r\n]|$)/.exec(source.slice(token.end));
+ if(!match)return [];
+ const from=token.end+match[0].length-64;
+ return [{from,to:from+64,hash:match[1]!,line:line.number}];
+ });
+ cachedSites.set(state.doc,sites);return sites;
+}
+export const importFocus=StateEffect.define<boolean>();
+const toggle=StateEffect.define<number>();
+const short=(hash:string)=>hash.slice(0,3)+'...'+hash.slice(-3);
+class ImportHash extends WidgetType {
+ constructor(readonly site:ImportSite,readonly expanded:boolean){super();}
+ eq(other:ImportHash):boolean{return this.site.from===other.site.from&&this.site.hash===other.site.hash&&this.expanded===other.expanded;}
+ toDOM(view:EditorView):HTMLElement {
+ const button=document.createElement('button');button.type='button';button.className='import-hash';
+ button.textContent=this.expanded?this.site.hash:short(this.site.hash);button.dataset.hashFrom=String(this.site.from);
+ button.setAttribute('aria-expanded',String(this.expanded));
+ button.setAttribute('aria-label',`${this.expanded?'Collapse':'Expand'} import hash ${this.site.hash}`);
+ button.onclick=()=>{
+ view.dispatch({effects:toggle.of(this.site.from),annotations:Transaction.addToHistory.of(false)});
+ view.dom.querySelector<HTMLElement>(`[data-hash-from="${this.site.from}"]`)?.focus({preventScroll:true});
+ };
+ // Ctrl+A on a hash control selects the complete canonical program.
+ button.onkeydown=event=>{
+ if((event.ctrlKey||event.metaKey)&&event.key.toLowerCase()==='a'){
+ event.preventDefault();view.dispatch({selection:EditorSelection.single(0,view.state.doc.length),effects:importFocus.of(true)});view.focus();
+ }
+ };
+ return button;
+ }
+ ignoreEvent():boolean{return true;}
+}
+interface Folds {open:Set<number>;active:boolean;sites:ImportSite[];decorations:ReturnType<typeof Decoration.set>}
+export function selectedImportLines(state:EditorState,active:boolean):Set<number> {
+ const lines=new Set<number>();
+ for(const range of state.selection.ranges){
+ if(!active&&range.empty)continue;
+ const from=state.doc.lineAt(range.from).number,to=state.doc.lineAt(range.empty?range.to:Math.max(range.from,range.to-1)).number;
+ for(let line=from;line<=to;line++)lines.add(line);
+ }
+ return lines;
+}
+function decorate(state:EditorState,open:Set<number>,active:boolean):Folds {
+ const sites=importSites(state),selected=selectedImportLines(state,active),ranges:Range<Decoration>[]=[];
+ for(const site of sites)ranges.push((selected.has(site.line)?Decoration.mark({class:'import-hash-full'}):
+ Decoration.replace({widget:new ImportHash(site,open.has(site.from))})).range(site.from,site.to));
+ return {open,active,sites,decorations:Decoration.set(ranges,true)};
+}
+export const importFolds=StateField.define<Folds>({
+ create:state=>decorate(state,new Set(),false),
+ update:(old,tr)=>{
+ let active=old.active;
+ const open=tr.docChanged?new Set(old.sites.filter(site=>old.open.has(site.from)&&!tr.changes.touchesRange(site.from,site.to))
+ .map(site=>tr.changes.mapPos(site.from,1))):new Set(old.open);
+ if(tr.selection&&tr.isUserEvent('select'))active=true;
+ for(const effect of tr.effects){
+ if(effect.is(toggle)){if(open.has(effect.value))open.delete(effect.value);else open.add(effect.value);}
+ if(effect.is(importFocus))active=effect.value;
+ }
+ if(!tr.docChanged&&!tr.selection&&active===old.active&&open.size===old.open.size&&[...open].every(pos=>old.open.has(pos)))return old;
+ return decorate(tr.state,open,active);
+ },
+ provide:field=>EditorView.decorations.from(field,value=>value.decorations)
+});
+export function syncImportFocus(view:EditorView):void {
+ queueMicrotask(()=>{
+ const old=view.state.field(importFolds).active,element=view.dom.ownerDocument.activeElement;
+ const active=element===view.contentDOM?true:view.dom.contains(element)?old:false;
+ if(old!==active)view.dispatch({effects:importFocus.of(active),annotations:Transaction.addToHistory.of(false)});
+ });
+}
diff --git a/ext/demo-site/src/import-picker.ts b/ext/demo-site/src/import-picker.ts
@@ -1,3 +1,4 @@
+import type { SourceEditor } from './source-editor.js';
import { fetchBytes } from './bundle.js';
import { libraryIndex, latestLibraries, matchesLibrary, type Library } from './library-index.js';
import { packageReleases } from './packages.js';
@@ -5,7 +6,7 @@ import type { ImportPlan } from './import-plan.js';
import type { LocalModuleInput } from './local-modules.js';
interface Choice { title: string; description: string; manifest: string; names: string[]; alias: string; library?: Library; definition?: string; }
interface Options {
- source: HTMLTextAreaElement;
+ source: SourceEditor;
backend(): string;
available(): boolean;
editable(): boolean;
@@ -116,7 +117,7 @@ export function importPicker(options: Options): { cancel(): void } {
}
open.onclick = () => {
if (!options.available()) return;
- snapshot = options.source.value; backend = options.backend(); search.value = ''; dialog.showModal(); browse(); search.focus();
+ snapshot = options.source.getSource(); backend = options.backend(); search.value = ''; dialog.showModal(); browse(); search.focus();
if (!libraries) {
message('Loading library references…');
void fetchBytes(new URL('../reference/libraries.json', import.meta.url), 2_097_152).then(bytes => {
@@ -143,17 +144,12 @@ export function importPicker(options: Options): { cancel(): void } {
};
get('copy-import').onclick = () => { void navigator.clipboard.writeText(statement()).then(() => message('Import copied.'), () => message('Select and copy the import preview.')); };
function applyPlan(): void {
- if (!plan || !options.available() || options.source.value !== snapshot || options.backend() !== backend) { stop(); insert.disabled = true; message('The editor changed. Close and reopen the picker to use the current source.'); return; }
+ if (!plan || !options.available() || options.source.getSource() !== snapshot || options.backend() !== backend) { stop(); insert.disabled = true; message('The editor changed. Close and reopen the picker to use the current source.'); return; }
const checked = plan;
finish(); options.source.focus();
- if (checked.existing) { options.source.setSelectionRange(checked.existing.start, checked.existing.end); return; }
- // Native textarea editing supplies one undo transaction on supported browsers.
- options.source.setSelectionRange(0, 0);
- if (!document.execCommand('insertText', false, checked.statement)) {
- message('Your browser could not insert an undoable edit. Copy the import from the picker.');
- dialog.showModal(); return;
- }
- options.source.setSelectionRange(0, checked.statement.length);
+ if (checked.existing) { options.source.select(checked.existing.start, checked.existing.end); return; }
+ options.source.edit(0,0,checked.statement);
+ options.source.select(0,checked.statement.length);
}
insert.onclick = () => applyPlan();
diff --git a/ext/demo-site/src/source-editor.ts b/ext/demo-site/src/source-editor.ts
@@ -0,0 +1,142 @@
+import { importFolds, importFocus, importSites, syncImportFocus } from './import-folds.js';
+import {EditorState, StateField, StateEffect, Transaction, EditorSelection, Compartment, type Range, type Extension,
+ EditorView, Decoration, keymap, drawSelection, history, historyKeymap, standardKeymap, isolateHistory, undo, redo, insertNewline} from './codemirror.js';
+import {tokenize, bracketPair, definitionSites} from './syntax.js';
+
+// Enter inserts a plain newline, preserving explicit source indentation.
+const plainNewline=(view:EditorView):boolean=>!view.state.readOnly&&insertNewline(view);
+
+interface Definitions { ready: boolean; busy: boolean; selected?: string; published?: string[] }
+const definitions = StateEffect.define<Definitions>();
+const definitionState = StateField.define<Definitions>({
+ create: () => ({ready:false,busy:false}),
+ update: (old,tr) => {for(const effect of tr.effects)if(effect.is(definitions))return effect.value;return old;}
+});
+const presentations=new WeakMap<EditorState['doc'],{tokens:ReturnType<typeof tokenize>;sites:ReturnType<typeof definitionSites>}>();
+function presentation(state:EditorState) {
+ let cached=presentations.get(state.doc);
+ if(!cached){const source=state.doc.toString(),tokens=tokenize(source);cached={tokens,sites:definitionSites(source,tokens)};presentations.set(state.doc,cached);}
+ return cached;
+}
+function decorations(state: EditorState): ReturnType<typeof Decoration.set> {
+ const {tokens,sites}=presentation(state), selection=state.selection.main;
+ const pair=selection.empty?bracketPair(tokens,selection.head):[];
+ const marks:Range<Decoration>[]=[], imports=importSites(state);
+ for(const token of tokens) if(token.kind&&!imports.some(site=>token.start>=site.from&&token.end<=site.to)) {
+ const match=pair.includes(token.start)?pair.length===2?' bracket-match':' bracket-unmatched':'';
+ marks.push(Decoration.mark({class:`syntax-${token.kind}${match}`}).range(token.start,token.end));
+ }
+ const controls=state.field(definitionState);
+ if(controls.ready) for(const site of sites) {
+ if(controls.published&&!controls.published.includes(site.name)||controls.busy&&controls.selected!==site.name)continue;
+ marks.push(Decoration.mark({class:'definition-name',attributes:{
+ role:'button',tabindex:controls.busy?'-1':'0','data-definition':site.name,
+ 'aria-label':`Inspect compiled definition ${site.name}`,'aria-controls':'inline-definition',
+ 'aria-expanded':String(controls.selected===site.name),'aria-disabled':String(controls.busy)
+ }}).range(site.start,site.start+site.name.length));
+ }
+ return Decoration.set(marks,true);
+}
+const syntax=StateField.define({
+ create:decorations,
+ update:(old,tr)=>tr.docChanged||tr.selection||tr.effects.some(effect=>effect.is(definitions))?decorations(tr.state):old,
+ provide:field=>EditorView.decorations.from(field)
+});
+// Symbol.for shares the mounted component across independently bundled test
+// and application entrypoints.
+const editorKey=Symbol.for('tricu.source-editor');
+type MountedEditor=HTMLElement&{[editorKey]?:SourceEditor};
+// Controller and browser fixtures access the same EditorState document,
+// selection and history through the mounted component.
+export function editorFor(element:HTMLElement):SourceEditor {
+ const editor=(element as MountedEditor)[editorKey];if(!editor)throw Error('Source editor is not initialized');return editor;
+}
+export class SourceEditor {
+ readonly view:EditorView;
+ private readonly configuration:Extension[];
+ private currentDefinitions:Definitions={ready:false,busy:false};
+ private readonly availability=new Compartment();
+ private readonly changes=new Set<()=>void>();
+ private readonly layouts=new Set<()=>void>();
+ private locked=false;
+ private readonlySource=false;
+ private controls='';
+ private pendingEpoch:number|undefined;
+ private epoch=0;
+ constructor(readonly dom:HTMLElement) {
+ dom.classList.add('source-editor');
+ this.configuration=[
+ definitionState,syntax,importFolds,history(),drawSelection(),EditorState.tabSize.of(2),
+ keymap.of([{key:'Enter',run:plainNewline,shift:plainNewline},...historyKeymap,...standardKeymap]),EditorView.lineWrapping,
+ this.availability.of([EditorState.readOnly.of(false),EditorView.editable.of(true)]),
+ EditorView.domEventHandlers({focus:(_event,view)=>syncImportFocus(view),blur:(_event,view)=>syncImportFocus(view)}),
+ EditorView.contentAttributes.of({'aria-label':'tricu source (up to 16,384 characters)',spellcheck:'false',autocorrect:'off',autocapitalize:'off'}),
+ EditorView.updateListener.of(update=>{
+ if(update.docChanged)this.notify();
+ // Schedule external listeners after EditorView.update so controller
+ // effects can dispatch their own transactions.
+ queueMicrotask(()=>{for(const listener of this.layouts)listener();});
+ }),
+ EditorView.theme({'&':{height:'100%'},'.cm-scroller':{overflow:'auto',fontFamily:'inherit',lineHeight:'inherit'},
+ '.cm-content':{padding:'18px 20px',fontFamily:'inherit',fontVariantLigatures:'none',minHeight:'100%'},
+ '.cm-line':{padding:'0'},'.cm-cursor':{borderLeftColor:'var(--syntax-ink)'},
+ '.cm-selectionBackground, &.cm-focused .cm-selectionBackground':{background:'#799ea066'}})
+ ];
+ this.view=new EditorView({parent:dom,state:EditorState.create({extensions:this.configuration})});
+ this.view.scrollDOM.addEventListener('scroll',()=>{for(const listener of this.layouts)listener();},{passive:true});
+ new ResizeObserver(()=>{for(const listener of this.layouts)listener();}).observe(dom);
+ dom.addEventListener('compositionstart',()=>dom.classList.add('composing'));
+ dom.addEventListener('compositionend',()=>dom.classList.remove('composing'));
+ (dom as MountedEditor)[editorKey]=this;
+ }
+ private notify():void {
+ const epoch=this.epoch;if(this.pendingEpoch===epoch)return;this.pendingEpoch=epoch;
+ queueMicrotask(()=>{if(this.pendingEpoch===epoch)this.flushChange();});
+ }
+ // Controller edits notify after the view update returns; native-input edits
+ // notify at the microtask boundary. Both refresh revisions before the next
+ // user event. Document epochs discard notifications from previous loads.
+ private flushChange():void {
+ if(this.pendingEpoch!==this.epoch)return;this.pendingEpoch=undefined;
+ for(const listener of this.changes)listener();
+ }
+ undo():boolean{const result=undo(this.view);this.flushChange();return result;}
+ redo():boolean{const result=redo(this.view);this.flushChange();return result;}
+ getSource():string{return this.view.state.doc.toString();}
+ getSelection():{from:number;to:number}{const {from,to}=this.view.state.selection.main;return {from,to};}
+ focus():void{this.view.focus();}
+ declarations():ReturnType<typeof definitionSites>{return presentation(this.view.state).sites;}
+ revealDefinition(name:string):boolean {
+ const site=this.declarations().find(site=>site.name===name);if(!site)return false;
+ this.view.dispatch({effects:EditorView.scrollIntoView(site.start,{y:'center'})});return true;
+ }
+ select(from:number,to=from):void{this.view.dispatch({selection:EditorSelection.single(from,to),effects:importFocus.of(true),scrollIntoView:true});this.focus();}
+ // Loading/restoring documents retires old history; import insertion is a
+ // separate, isolated undoable edit. Notification is explicit for controller edits.
+ replaceSource(source:string,notify=false):void {
+ this.epoch++;this.pendingEpoch=undefined;
+ const state=EditorState.create({doc:source,extensions:this.configuration});
+ this.view.setState(state.update({effects:[definitions.of(this.currentDefinitions),
+ this.availability.reconfigure([EditorState.readOnly.of(this.locked||this.readonlySource),EditorView.editable.of(!this.locked&&!this.readonlySource)])]}).state);
+ if(notify){this.pendingEpoch=this.epoch;this.flushChange();}
+ }
+ edit(from:number,to:number,text:string):void {
+ this.view.dispatch({changes:{from,to,insert:text},selection:EditorSelection.single(from+text.length),
+ annotations:[Transaction.userEvent.of('input'),isolateHistory.of('full')]});
+ this.focus();this.flushChange();
+ }
+ get isDisabled():boolean{return this.locked;}
+ get isReadOnly():boolean{return this.readonlySource;}
+ setAvailability(disabled:boolean,readOnly:boolean):void {
+ if(this.locked===disabled&&this.readonlySource===readOnly)return;
+ this.locked=disabled;this.readonlySource=readOnly;this.dom.classList.toggle('disabled',disabled);
+ this.view.dispatch({effects:this.availability.reconfigure([EditorState.readOnly.of(disabled||readOnly),EditorView.editable.of(!disabled&&!readOnly)])});
+ }
+ setDefinitions(value:Definitions):void {
+ const key=JSON.stringify(value);if(key===this.controls)return;this.controls=key;this.currentDefinitions=value;
+ this.view.dispatch({effects:definitions.of(value)});
+ }
+ onChange(listener:()=>void):()=>void{this.changes.add(listener);return ()=>this.changes.delete(listener);}
+ onLayout(listener:()=>void):void{this.layouts.add(listener);}
+ refresh():void{this.view.requestMeasure();}
+}
diff --git a/ext/demo-site/src/syntax.ts b/ext/demo-site/src/syntax.ts
@@ -1,5 +1,5 @@
-// Presentation only: never used for parsing, compilation, or name resolution.
-// Offsets are UTF-16 textarea offsets, not compiler Unicode-scalar positions.
+// Lexical highlighting and declaration-site decoration. Editor offsets count
+// UTF-16 code units; compiler positions count Unicode scalars.
export interface Token { start: number; end: number; kind: string; text: string }
const keywords = new Set(['let', 'in', 'where', 'do', 'case', 'of', 'rec']);
export function tokenize(source: string): Token[] {
@@ -99,40 +99,11 @@ export function paintSyntax(target: HTMLElement, tokens: Token[], pair: number[]
target.replaceChildren(fragment);
}
-export function syntaxEditor(input: HTMLTextAreaElement): () => void {
- const wrapper = document.createElement('div'); wrapper.className = 'syntax-editor';
- input.before(wrapper); wrapper.append(input);
- const viewport = document.createElement('div'); viewport.className = 'syntax-viewport'; viewport.setAttribute('aria-hidden', 'true');
- const mirror = document.createElement('pre'); viewport.append(mirror); wrapper.prepend(viewport);
- let value: string | undefined, tokens: Token[] = [], lastPair = '', composing = false;
- function scroll(): void { mirror.style.transform = `translate(${-input.scrollLeft}px, ${-input.scrollTop}px)`; }
- function refresh(): void {
- wrapper.hidden = input.hidden;
- wrapper.classList.toggle('modified', input.classList.contains('modified'));
- wrapper.classList.toggle('disabled', input.disabled);
- wrapper.classList.toggle('composing', composing);
- const style = getComputedStyle(input);
- // Use the textarea's actual content box, excluding scrollbar and border.
- mirror.style.width = `${input.clientWidth}px`;
- viewport.style.inset = `${style.borderTopWidth} ${style.borderRightWidth} ${style.borderBottomWidth} ${style.borderLeftWidth}`;
- for (const property of ['font-family', 'font-size', 'line-height', 'font-weight', 'font-style', 'font-stretch', 'font-variant-ligatures', 'font-kerning', 'font-feature-settings', 'font-variation-settings', 'letter-spacing', 'padding', 'tab-size', 'text-align']) mirror.style.setProperty(property, style.getPropertyValue(property));
- const changed = value !== input.value;
- if (changed) { value = input.value; tokens = tokenize(value); }
- const pair = !composing && document.activeElement === input && input.selectionStart === input.selectionEnd ? bracketPair(tokens, input.selectionStart) : [];
- if (changed || pair.join() !== lastPair) {
- paintSyntax(mirror, tokens, pair); lastPair = pair.join();
- // Preserve a trailing empty line without introducing a new line.
- if (!value || value.endsWith('\n')) mirror.append(document.createTextNode(' '));
- }
- scroll();
- }
- input.classList.add('syntax-input');
- for (const event of ['input', 'click', 'keyup', 'select', 'focus', 'blur']) input.addEventListener(event, refresh);
- input.addEventListener('compositionstart', () => { composing = true; refresh(); });
- input.addEventListener('compositionend', () => { composing = false; refresh(); });
- input.addEventListener('scroll', scroll, { passive: true });
- document.addEventListener('selectionchange', () => { if (document.activeElement === input) refresh(); });
- new ResizeObserver(refresh).observe(input);
- new MutationObserver(refresh).observe(input, { attributes: true, attributeFilter: ['hidden', 'disabled', 'class'] });
- refresh(); return refresh;
+// Unique top-level declaration heads recognized by lexical layout.
+export function definitionSites(source: string, tokens = tokenize(source)): { name: string; start: number }[] {
+ const seen = new Set<string>();
+ return tokens.filter(token => {
+ if (token.kind !== 'definition' || token.start > 0 && source[token.start - 1] !== '\n' || seen.has(token.text)) return false;
+ seen.add(token.text); return true;
+ }).map(token => ({ name: token.text, start: token.start }));
}
diff --git a/ext/demo-site/style.css b/ext/demo-site/style.css
@@ -13,17 +13,9 @@
@media(prefers-reduced-motion:reduce){html{scroll-behavior:auto}}
-.syntax-editor{position:relative;min-width:0;background:var(--panel);--syntax-ink:var(--ink);--syn-comment:#56695e;--syn-string:#27613d;--syn-escape:#95511e;--syn-number:#27578c;--syn-keyword:#6c367c;--syn-definition:#754300;--syn-tree:#006b60;--syn-contract:#934824;--syn-invalid:#ae3026;--syn-match:#d4e5c4}
.source-panel{--syntax-ink:#e3edde;--syn-comment:#9cafa4;--syn-string:#c0d9a3;--syn-escape:#f4bc8d;--syn-number:#9ecff5;--syn-keyword:#d6b5ef;--syn-definition:#ffd08a;--syn-tree:#73dbc0;--syn-contract:#f4bc8d;--syn-invalid:#ffb2a6;--syn-match:#435b43}
-.source-panel .syntax-editor{background:var(--code);--syntax-ink:inherit;--syn-comment:inherit;--syn-string:inherit;--syn-escape:inherit;--syn-number:inherit;--syn-keyword:inherit;--syn-definition:inherit;--syn-tree:inherit;--syn-contract:inherit;--syn-invalid:inherit;--syn-match:inherit}
-.source-panel .syntax-editor.modified{background:#273c32}.syntax-editor.disabled .syntax-viewport{opacity:.75}
-.syntax-viewport{position:absolute;pointer-events:none;overflow:hidden;user-select:none}
-.syntax-viewport pre{margin:0;border:0;border-radius:0;white-space:pre-wrap;overflow-wrap:break-word;word-break:normal;min-height:100%;color:var(--syntax-ink);transform-origin:top left}
-#source-editor.syntax-input{position:relative;color:transparent;-webkit-text-fill-color:transparent;caret-color:var(--syntax-ink);background:transparent;white-space:pre-wrap;overflow-wrap:break-word;word-break:normal;display:block}
-.syntax-input::selection{background:#799ea066;color:transparent}.syntax-comment{color:var(--syn-comment)}.syntax-string{color:var(--syn-string)}.syntax-escape{color:var(--syn-escape)}.syntax-number{color:var(--syn-number)}.syntax-keyword,.syntax-directive{color:var(--syn-keyword)}.syntax-tree{color:var(--syn-tree)}.syntax-definition{color:var(--syn-definition)}.syntax-contract{color:var(--syn-contract)}.syntax-invalid{color:var(--syn-invalid);text-decoration:underline wavy}.bracket-match{background:var(--syn-match);box-shadow:inset 0 -2px var(--syn-definition)}.bracket-unmatched{text-decoration:underline wavy var(--syn-invalid);text-underline-offset:3px}
-.syntax-editor.composing .syntax-viewport{visibility:hidden}.syntax-editor.composing .syntax-input{color:var(--syntax-ink)!important;-webkit-text-fill-color:var(--syntax-ink)!important}
-@media(forced-colors:active){.syntax-viewport{display:none}#source-editor.syntax-input{color:CanvasText;-webkit-text-fill-color:CanvasText;caret-color:CanvasText}.syntax-input::selection{background:Highlight;color:HighlightText;-webkit-text-fill-color:HighlightText}}
-.syntax-editor{--syn-operator:#516263}.source-panel{--syn-operator:#aac6cc}.source-panel .syntax-editor{--syn-operator:inherit}.syntax-operator,.syntax-bracket{color:var(--syn-operator)}.syntax-input,.syntax-viewport pre{font-variant-ligatures:none}
+.syntax-comment{color:var(--syn-comment)}.syntax-string{color:var(--syn-string)}.syntax-escape{color:var(--syn-escape)}.syntax-number{color:var(--syn-number)}.syntax-keyword,.syntax-directive{color:var(--syn-keyword)}.syntax-tree{color:var(--syn-tree)}.syntax-definition{color:var(--syn-definition)}.syntax-contract{color:var(--syn-contract)}.syntax-invalid{color:var(--syn-invalid);text-decoration:underline wavy}.bracket-match{background:var(--syn-match);box-shadow:inset 0 -2px var(--syn-definition)}.bracket-unmatched{text-decoration:underline wavy var(--syn-invalid);text-underline-offset:3px}
+.source-panel{--syn-operator:#aac6cc}.syntax-operator,.syntax-bracket{color:var(--syn-operator)}
@media(max-width:740px){.editor-toolbar #status{flex:1 1 100px;order:3;align-self:center}}
#local-modules code, #local-modules p { overflow-wrap: anywhere; }
@@ -51,13 +43,13 @@ header nav{align-items:center;gap:12px}#theme-separator{color:var(--muted)}
#theme-toggle:hover{background:var(--panel)}
-.definition-targets{position:absolute;inset:0;overflow:hidden;pointer-events:none;z-index:2}
-.definition-targets button{position:absolute;min-height:0;min-width:0;margin:0;padding:0;border:0;border-bottom:1px dotted var(--syn-definition);border-radius:0;background:transparent;color:transparent;-webkit-text-fill-color:transparent;white-space:nowrap;overflow:hidden;pointer-events:auto;user-select:text;-webkit-user-select:text;touch-action:manipulation;forced-color-adjust:none}
-.definition-targets button:hover:not(:disabled),.definition-targets button[aria-expanded="true"]{background:#8bd3ad24;border-bottom:1px solid var(--syn-definition)}
-.definition-targets button:disabled{pointer-events:none;opacity:1}
-.definition-targets button:focus-visible{outline:2px solid #bfe2ba;outline-offset:2px}
-.definition-targets button::selection{background:#799ea066;color:#e3edde;-webkit-text-fill-color:#e3edde}
-.syntax-editor.composing .definition-targets{display:none}
+#source-editor.source-editor{padding:0;position:relative;color:var(--syntax-ink)}
+.source-editor .cm-editor{font:inherit;background:transparent}.source-editor.disabled{opacity:.75}
+.definition-name{text-decoration:underline dotted var(--syn-definition);text-underline-offset:3px;cursor:pointer;touch-action:manipulation}
+.definition-name:hover,.definition-name[aria-expanded="true"]{background:#8bd3ad24;text-decoration-style:solid}
+.definition-name[aria-disabled="true"]{cursor:default;pointer-events:none}.definition-name:focus-visible{outline:2px solid #bfe2ba;outline-offset:2px}
+.source-editor.composing .definition-name{text-decoration:none;pointer-events:none}
+@media(max-width:740px){.source-editor .cm-content{padding:16px}}
.definition-card{position:absolute;left:8px;right:8px;z-index:3;max-height:260px;overflow:auto;margin:0;padding:12px;border:1px solid #587362;border-radius:8px;background:#21352b;color:#e3edde;min-width:0}
.definition-card-controls{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-top:10px;padding-top:8px;border-top:1px solid #385045}
.definition-card-controls strong{flex:1;min-width:0;overflow-wrap:anywhere;font-size:12px;font-weight:500;color:#b1c1b7}
@@ -70,7 +62,7 @@ header nav{align-items:center;gap:12px}#theme-separator{color:var(--muted)}
#import-exports{display:flex;gap:6px;flex-wrap:wrap}#import-exports button{font:inherit;font-size:13px;padding:5px 8px}
#import-results h3{margin-bottom:0}#try-library,#copy-qualified{margin:8px 8px 8px 0}
-@media(forced-colors:active){.has-definition-inspector .syntax-viewport{display:block;visibility:hidden}.definition-targets{--syn-definition:ButtonText}.definition-targets button{border-color:ButtonText}.definition-targets button:hover:not(:disabled),.definition-targets button[aria-expanded="true"]{background:transparent}.definition-targets button::selection{background:Highlight;color:HighlightText;-webkit-text-fill-color:HighlightText}.definition-targets button:focus-visible{outline-color:Highlight}.definition-card{background:Canvas;color:CanvasText;border-color:CanvasText}.definition-card .hint,.definition-card button,.definition-card select{color:CanvasText;background:Canvas}}
+@media(forced-colors:active){.definition-name{color:LinkText}.definition-name:focus-visible{outline-color:Highlight}.definition-card{background:Canvas;color:CanvasText;border-color:CanvasText}.definition-card .hint,.definition-card button,.definition-card select{color:CanvasText;background:Canvas}}
/* Definition cards own both inspection and explicitly authorized IO. */
.definition-card .definition-actions,.inline-io-actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:8px}
@@ -89,3 +81,7 @@ header nav{align-items:center;gap:12px}#theme-separator{color:var(--muted)}
.definition-card{color-scheme:dark;--green:#8bd3ad}
.definition-card .edit-definition-name{display:inline-block;width:auto;height:auto;padding:4px 10px;margin-top:8px;font-size:12px;border:1px solid #587362}
+
+.source-editor .import-hash{display:inline;min-width:0;min-height:0;max-width:100%;margin:0;padding:0;border:0;border-radius:0;font:inherit;line-height:inherit;vertical-align:baseline;color:#8accc8;background:transparent;white-space:pre-wrap;overflow-wrap:anywhere;text-decoration:underline dotted;text-underline-offset:3px;cursor:pointer}
+.source-editor .import-hash:hover{background:#8bd3ad24}.source-editor .import-hash:focus-visible{outline:2px solid #bfe2ba;outline-offset:2px}.source-editor .import-hash-full{color:#8accc8}
+@media(forced-colors:active){.source-editor .import-hash{color:LinkText}.source-editor .import-hash-full{color:CanvasText}}
diff --git a/ext/demo-site/test/asset-cache-probe.mjs b/ext/demo-site/test/asset-cache-probe.mjs
@@ -4,7 +4,7 @@ const el=id=>document.getElementById(id),delay=ms=>new Promise(r=>setTimeout(r,m
const assert=(ok,message)=>{if(!ok)throw Error(message);};
async function status(wanted){for(let i=0;i<4500;i++){if(el('status').textContent===wanted)return;await delay(20);}throw Error('Waiting for '+wanted+': '+el('status').textContent+' '+el('compile-diagnostic').textContent);}
const change=(id,value)=>{el(id).value=value;el(id).dispatchEvent(new Event('change'));};
-const input=(id,value)=>{el(id).value=value;el(id).dispatchEvent(new Event('input'));};
+const input=(id,value)=>{if(id==='source-editor'){globalThis.__sourceEditor.replaceSource(value,true);return;}el(id).value=value;el(id).dispatchEvent(new Event('input'));};
export async function run(control,backend='haskell-wasm'){
await status('Ready');
if(el('runtime-backend').value!==backend){change('runtime-backend',backend);await status('Ready');}
diff --git a/ext/demo-site/test/backend-browser.mjs b/ext/demo-site/test/backend-browser.mjs
@@ -61,7 +61,8 @@ try {
console.log('Test phases:',JSON.stringify(marks.slice(-4)));
void evaluate("({status:document.getElementById('status')?.textContent,activity:document.getElementById('compile-activity')?.textContent,card:document.querySelector('.definition-card [role=status]')?.textContent})").then(state=>console.log('Page:',JSON.stringify(state))).catch(()=>{});
},30000);
- const report=await evaluate(`import(${JSON.stringify(process.env.TEST_DEFINITION_NAMES?'/definition-names-probe.mjs':process.env.TEST_INLINE_IO?'/inline-io-probe.mjs':process.env.TEST_BASIC_EXAMPLES?'/basic-examples-probe.mjs':process.env.TEST_IMPORT_PICKER?'/import-picker-probe.mjs':process.env.TEST_COLD_LOAD?'/cold-load-probe.mjs':process.env.TEST_ASSET_CACHE?'/asset-cache-probe.mjs':process.env.TEST_LOCAL_MODULES?'/local-module-probe.mjs':process.env.TEST_MODULES?'/module-probe.mjs':process.env.TEST_IDE?'/ide-probe.mjs':process.env.TEST_LIVE_UX?'/live-ux-probe.mjs':process.env.TEST_BENCHMARK?'/backend-benchmark.mjs':'/backend-probe.mjs')}).then(m=>m.run(${JSON.stringify(control)},${JSON.stringify(process.env.TEST_BACKEND||'haskell-wasm')},${!!process.env.BENCHMARK_PSS}))`);
+ const report=await evaluate(`import(${JSON.stringify(process.env.TEST_IMPORT_FOLDS?'/import-folds-probe.mjs':process.env.TEST_DEFINITION_NAMES?'/definition-names-probe.mjs':process.env.TEST_INLINE_IO?'/inline-io-probe.mjs':process.env.TEST_BASIC_EXAMPLES?'/basic-examples-probe.mjs':process.env.TEST_IMPORT_PICKER?'/import-picker-probe.mjs':process.env.TEST_COLD_LOAD?'/cold-load-probe.mjs':process.env.TEST_ASSET_CACHE?'/asset-cache-probe.mjs':process.env.TEST_LOCAL_MODULES?'/local-module-probe.mjs':process.env.TEST_MODULES?'/module-probe.mjs':process.env.TEST_IDE?'/ide-probe.mjs':process.env.TEST_LIVE_UX?'/live-ux-probe.mjs':process.env.TEST_BENCHMARK?'/backend-benchmark.mjs':'/backend-probe.mjs')}).then(m=>m.run(${JSON.stringify(control)},${JSON.stringify(process.env.TEST_BACKEND||'haskell-wasm')},${!!process.env.BENCHMARK_PSS}))`);
+ if(process.env.TEST_IMPORT_FOLDS)await (await import('./import-fold-inputs.mjs')).importFoldInputs({send,evaluate,report,prefix:process.env.TEST_SCREENSHOT_PREFIX});
if(process.env.TEST_DEFINITION_NAMES)await (await import('./definition-name-inputs.mjs')).definitionNameInputs({send,evaluate,report,prefix:process.env.TEST_SCREENSHOT_PREFIX});
if(process.env.TEST_INLINE_IO&&process.env.TEST_SCREENSHOT_PREFIX){
await evaluate("document.getElementById('run-io').click()");
@@ -94,24 +95,24 @@ try {
}
await evaluate(`(()=>{
document.querySelector('[data-compiler-example=identity]').click();
- const source=document.getElementById('source-editor');
- source.value='answer = 42\\nloop = (x : x x) (x : x x)';source.dispatchEvent(new Event('input'));
+ globalThis.__sourceEditor.replaceSource('answer = 42\\nloop = (x : x x) (x : x x)',true);
})()`);
await waitFor("document.getElementById('status').textContent==='Compiled'",'scratch compile');
assert.equal(await evaluate("document.getElementById('reload-playground').disabled"),false,'Recovery available for local drafts');
- const draftBefore=await evaluate("document.getElementById('source-editor').value");
+ const draftBefore=await evaluate("globalThis.__sourceEditor.getSource()");
const localsBefore=await evaluate("document.getElementById('local-module-list').children.length");
await evaluate("window.__reloadProof=true;window.__recoveryPrompts=0;window.confirm=()=>{window.__recoveryPrompts++;return false;};document.getElementById('reload-playground').click()");
await new Promise(r=>setTimeout(r,100));
assert.equal(await evaluate('window.__recoveryPrompts'),1,'Draft recovery asks before clearing work');
- assert.equal(await evaluate("document.getElementById('source-editor').value"),draftBefore,'Cancelled recovery preserves authored source');
+ assert.equal(await evaluate("globalThis.__sourceEditor.getSource()"),draftBefore,'Cancelled recovery preserves authored source');
assert.equal(await evaluate("document.getElementById('local-module-list').children.length"),localsBefore,'Cancelled recovery preserves local files');
await evaluate("document.querySelector('[aria-label=\"Inspect compiled definition loop\"]').click()");
await waitFor("document.getElementById('status').textContent==='Inspecting loop'",'divergent WASM observation');
assert.equal(await evaluate("document.getElementById('reload-playground').disabled"),false,'Recovery remains available while WASM is stuck');
await evaluate("window.confirm=()=>true;document.getElementById('reload-playground').click()");
await waitFor("!window.__reloadProof&&document.getElementById('status')?.textContent==='Ready'",'new page/runtime');
- assert.equal(await evaluate("document.getElementById('source-editor').readOnly||document.getElementById('source-editor').hidden"),false,'Reload restores editable demo source');
+ await evaluate("import('/source-probe-helpers.mjs').then(()=>true)");
+ assert.equal(await evaluate("globalThis.__sourceEditor.isReadOnly||document.getElementById('source-editor').hidden"),false,'Reload restores editable demo source');
assert.equal(await evaluate("document.getElementById('local-module-list').children.length"),0,'Reload clears in-memory local modules');
assert.equal(await evaluate("document.querySelector('.definition-card').hidden"),true,'Reload never automatically inspects');
assert.equal(await evaluate('document.documentElement.scrollWidth<=innerWidth'),true,'Recovery toolbar fits viewport');
@@ -133,14 +134,14 @@ try {
}
if(process.env.TEST_IDE){
await send('Emulation.setEmulatedMedia',{features:[{name:'forced-colors',value:'active'}]});
- assert.equal(await evaluate("getComputedStyle(document.querySelector('.syntax-viewport')).visibility==='hidden'&&getComputedStyle(document.getElementById('source-editor')).webkitTextFillColor!=='rgba(0, 0, 0, 0)'"),true,'High contrast retains readable native text');
+ assert.equal(await evaluate("getComputedStyle(globalThis.__sourceEditor.view.contentDOM).color!=='rgba(0, 0, 0, 0)'&&!document.querySelector('.syntax-viewport')"),true,'High contrast retains readable native text');
await send('Emulation.setEmulatedMedia',{features:[]});
- const beforeEdit=await evaluate("(()=>{const e=document.getElementById('source-editor');e.focus();e.setSelectionRange(e.value.length,e.value.length);return e.value;})()");
+ const beforeEdit=await evaluate("(()=>{const e=globalThis.__sourceEditor;e.select(e.getSource().length);return e.getSource();})()");
await send('Input.insertText',{text:' -- native undo'});
- assert.equal(await evaluate("document.getElementById('source-editor').value"),beforeEdit+' -- native undo');
+ assert.equal(await evaluate("globalThis.__sourceEditor.getSource()"),beforeEdit+' -- native undo');
await send('Input.dispatchKeyEvent',{type:'keyDown',key:'z',code:'KeyZ',modifiers:2,windowsVirtualKeyCode:90,nativeVirtualKeyCode:90});
await send('Input.dispatchKeyEvent',{type:'keyUp',key:'z',code:'KeyZ',modifiers:2,windowsVirtualKeyCode:90,nativeVirtualKeyCode:90});
- assert.equal(await evaluate("document.getElementById('source-editor').value"),beforeEdit,'Highlighting preserves native undo');
+ assert.equal(await evaluate("globalThis.__sourceEditor.getSource()"),beforeEdit,'Highlighting preserves native undo');
await send('Emulation.setDeviceMetricsOverride',{width:390,height:844,deviceScaleFactor:1,mobile:true});
await evaluate("document.getElementById('settings-toggle').click()");
assert.equal(await evaluate("document.getElementById('settings-panel').getAttribute('aria-modal')==='true'&&document.querySelector('.editor-main').inert"),true,'Mobile settings is modal');
diff --git a/ext/demo-site/test/backend-probe.mjs b/ext/demo-site/test/backend-probe.mjs
@@ -12,29 +12,29 @@ export async function run(control,backend='haskell-wasm'){
assert(/WASM fetch failed|HTTP|fetch/i.test(el('operation-diagnostic').textContent),'Runtime artifact failure is visible, no JS fallback');
change('program-picker','demo:arithmetic');await status('Stopped');
await fault({runtime:false});el('reload-package').click();await status('Ready');
- assert(!el('source-editor').hidden&&!el('source-editor').readOnly,'Retry after a fresh load failure restores editable demo source');
+ assert(!el('source-editor').hidden&&!globalThis.__sourceEditor.isReadOnly,'Retry after a fresh load failure restores editable demo source');
await select('language-reference');
assert(await inspect('leaf','tricu')==='t','Published stored binding');
assert(!(await requests()).some(path=>path.endsWith('/compiler.json')),'Published inspection does not initialize compiler');
for(const name of ['rgb','microscope','shipping','events','registration','migration'])await select(name);
await select('language-reference');
- input('source-editor',el('source-editor').value.replace('first 42 7','first 43 7'));await status('Compiled');
+ input('source-editor',globalThis.__sourceEditor.getSource().replace('first 42 7','first 43 7'));await status('Compiled');
assert(await inspect('answer','number')==='43','Edited source compiles');
assert(/MiB WASM linear memory/.test(el('compiler-stats').textContent),'Native runtime statistics');
await inspect('answer','string');assert(description().includes('Cannot interpret'),'Decoder errors are visible');
assert(await inspect('answer','number')==='43','Decoder errors preserve compiled definitions');
- input('source-editor',el('source-editor').value+'\n-- revision');await status('Compiled');assert(await inspect('answer','number')==='43','New revision');
+ input('source-editor',globalThis.__sourceEditor.getSource()+'\n-- revision');await status('Compiled');assert(await inspect('answer','number')==='43','New revision');
el('restore-source').click();await status('Ready');
await fault({compilerPin:true});document.querySelector('[data-compiler-example=contracts]').click();await status('Compilation failed');
assert(/Runtime compiler pin mismatch|HTTP|fetch/i.test(el('compile-diagnostic').textContent),'Compiler pin failure has no fallback');
await fault({compilerPin:false});
await select('names-values');
const report=await(await import('/inline-io-probe.mjs')).run(control,backend);
- await select('shipping');input('source-editor',el('source-editor').value+'\n-- native imports');await status('Compiled');
+ await select('shipping');input('source-editor',globalThis.__sourceEditor.getSource()+'\n-- native imports');await status('Compiled');
document.querySelector('[data-compiler-example=identity]').click();input('source-editor','answer = 42\nloop = (x : x x) (x : x x)');await status('Compiled');
document.querySelector('[aria-label="Inspect compiled definition loop"]').click();await wait(()=>el('status').textContent==='Inspecting loop','CPU-bound observation');await pause(100);el('stop').click();
assert(!el('compile').disabled,'Stop discards runtime and permits recompile');
- const source=el('source-editor').value;change('runtime-backend',backend==='haskell-wasm'?'zig-wasm':'haskell-wasm');await status('Compiled');assert(el('source-editor').value===source,'Backend switching preserves source');
+ const source=globalThis.__sourceEditor.getSource();change('runtime-backend',backend==='haskell-wasm'?'zig-wasm':'haskell-wasm');await status('Compiled');assert(globalThis.__sourceEditor.getSource()===source,'Backend switching preserves source');
assert(await inspect('answer','number')==='42','Backend switch rebuilds independent definitions');
await(await import('/backend-resume-probe.mjs')).probeResume(backend);
const parity=backend==='zig-wasm'?await(await import('/zig-session-probe.mjs')).run():null;
diff --git a/ext/demo-site/test/backend-server.mjs b/ext/demo-site/test/backend-server.mjs
@@ -32,6 +32,7 @@ export async function startSiteServer(directory,autoRun=false) {
res.end('ok');return;
}
if(path==='/source-probe-helpers.mjs'){res.setHeader('Content-Type','text/javascript');res.end(await readFile(new URL('./source-probe-helpers.mjs',import.meta.url)));return;}
+ if(path==='/import-folds-probe.mjs'){res.setHeader('Content-Type','text/javascript');res.end(await readFile(new URL('./import-folds-probe.mjs',import.meta.url)));return;}
if(path==='/definition-names-probe.mjs'){res.setHeader('Content-Type','text/javascript');res.end(await readFile(new URL('./definition-names-probe.mjs',import.meta.url)));return;}
if(path==='/inline-io-probe.mjs'){res.setHeader('Content-Type','text/javascript');res.end(await readFile(new URL('./inline-io-probe.mjs',import.meta.url)));return;}
if(path==='/asset-cache-probe.mjs'){res.setHeader('Content-Type','text/javascript');res.end(await readFile(new URL('./asset-cache-probe.mjs',import.meta.url)));return;}
@@ -82,7 +83,7 @@ export async function startSiteServer(directory,autoRun=false) {
if(moduleCorrupt&&path==='/_arboricx/bundle/hash/'+moduleCorrupt){bytes=Buffer.from(bytes);bytes[0]^=1;}
if(process.env.TEST_COLD_LOAD&&path==='/nested/site/index.html')bytes=Buffer.from(bytes.toString().replace('<head>',`<head><script>new MutationObserver((_,observer)=>{if(document.getElementById('status')?.textContent==='Ready'){globalThis.__readyMs=performance.now();observer.disconnect();}}).observe(document.documentElement,{childList:true,subtree:true,characterData:true});</script>`));
if(autoRun&&path==='/nested/site/index.html'&&!new URL(req.url,'http://localhost').searchParams.has('noProbe'))bytes=Buffer.from(bytes.toString()+`<script type="module">
- try{const m=await import(${JSON.stringify(process.env.TEST_DEFINITION_NAMES?'/definition-names-probe.mjs':process.env.TEST_INLINE_IO?'/inline-io-probe.mjs':process.env.TEST_BASIC_EXAMPLES?'/basic-examples-probe.mjs':process.env.TEST_IMPORT_PICKER?'/import-picker-probe.mjs':process.env.TEST_COLD_LOAD?'/cold-load-probe.mjs':process.env.TEST_ASSET_CACHE?'/asset-cache-probe.mjs':process.env.TEST_LOCAL_MODULES?'/local-module-probe.mjs':process.env.TEST_MODULES?'/module-probe.mjs':process.env.TEST_IDE?'/ide-probe.mjs':process.env.TEST_LIVE_UX?'/live-ux-probe.mjs':process.env.TEST_BENCHMARK?'/backend-benchmark.mjs':'/backend-probe.mjs')});const report=await m.run(${JSON.stringify(control)},${JSON.stringify(process.env.TEST_BACKEND||'haskell-wasm')},${!!process.env.BENCHMARK_PSS});await fetch(${JSON.stringify(control+'/report')},{method:'POST',body:JSON.stringify({ok:true,report})});}
+ try{const m=await import(${JSON.stringify(process.env.TEST_IMPORT_FOLDS?'/import-folds-probe.mjs':process.env.TEST_DEFINITION_NAMES?'/definition-names-probe.mjs':process.env.TEST_INLINE_IO?'/inline-io-probe.mjs':process.env.TEST_BASIC_EXAMPLES?'/basic-examples-probe.mjs':process.env.TEST_IMPORT_PICKER?'/import-picker-probe.mjs':process.env.TEST_COLD_LOAD?'/cold-load-probe.mjs':process.env.TEST_ASSET_CACHE?'/asset-cache-probe.mjs':process.env.TEST_LOCAL_MODULES?'/local-module-probe.mjs':process.env.TEST_MODULES?'/module-probe.mjs':process.env.TEST_IDE?'/ide-probe.mjs':process.env.TEST_LIVE_UX?'/live-ux-probe.mjs':process.env.TEST_BENCHMARK?'/backend-benchmark.mjs':'/backend-probe.mjs')});const report=await m.run(${JSON.stringify(control)},${JSON.stringify(process.env.TEST_BACKEND||'haskell-wasm')},${!!process.env.BENCHMARK_PSS});await fetch(${JSON.stringify(control+'/report')},{method:'POST',body:JSON.stringify({ok:true,report})});}
catch(e){await fetch(${JSON.stringify(control+'/report')},{method:'POST',body:JSON.stringify({ok:false,error:String(e)+'\\n'+(e.stack||'')})});}
</script>`);
if(process.env.TEST_ASSET_CACHE && ['/nested/site/index.html','/nested/site/assets.json'].includes(path))res.setHeader('Cache-Control','no-cache');
diff --git a/ext/demo-site/test/backend-webkit.mjs b/ext/demo-site/test/backend-webkit.mjs
@@ -5,16 +5,19 @@ import {tmpdir} from 'node:os';
import {join} from 'node:path';
import {startSiteServer} from './backend-server.mjs';
const {webkit}=await import(process.env.PLAYWRIGHT_MODULE);
-const {server,url,completion}=await startSiteServer(process.argv[2]||'unused',true);
+const {server,url,completion,marks}=await startSiteServer(process.argv[2]||'unused',true);
const profile=await mkdtemp(join(tmpdir(),'tricu-webkit-'));
-let browser,timer;
+const timeoutMs=Number(process.env.TEST_WEBKIT_TIMEOUT_MS??240000);
+assert(Number.isSafeInteger(timeoutMs)&&timeoutMs>=1000&&timeoutMs<=600000);
+let browser,timer,diagnostics;
try {
// Match the other browser harnesses: a fresh disk-backed profile per run.
browser=await webkit.launchPersistentContext(profile,{headless:true,viewport:{width:1280,height:900}});
const page=await browser.newPage(),errors=[];
page.on('pageerror',e=>errors.push(String(e)));
await page.goto(url);
- const report=await Promise.race([completion,new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error('WebKit probe timeout')),240000);})]);
+ if(process.env.TEST_DIAGNOSTICS)diagnostics=setInterval(()=>{void page.evaluate(()=>({status:document.getElementById('status')?.textContent,activity:document.getElementById('compile-activity')?.textContent})).then(state=>console.log('Page:',JSON.stringify(state))).catch(()=>{});},30000);
+ const report=await Promise.race([completion,new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error('WebKit probe timeout; phases: '+JSON.stringify(marks.slice(-4)))),timeoutMs);})]);
assert.deepEqual(errors,[]);
if(process.env.TEST_IMPORT_PICKER){
await page.click('#add-import');
@@ -27,7 +30,7 @@ try {
}
for(const width of [320,390,1280]){
await page.setViewportSize({width,height:844});
- // Let ResizeObserver update the textarea's decorative mirror geometry.
+ // Let CodeMirror measure its editable viewport.
await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve))));
if(process.env.TEST_IMPORT_PICKER)assert(await page.evaluate(()=>{
const content=document.querySelector('#import-content').getBoundingClientRect();
@@ -45,6 +48,6 @@ try {
console.log('PASS '+report.engine+': '+report.checks.join(' / '));
} finally {
- clearTimeout(timer);await browser?.close();server.closeAllConnections();await new Promise(r=>server.close(r));
+ clearTimeout(timer);clearInterval(diagnostics);await browser?.close();server.closeAllConnections();await new Promise(r=>server.close(r));
await rm(profile,{recursive:true,force:true});
}
diff --git a/ext/demo-site/test/basic-examples-probe.mjs b/ext/demo-site/test/basic-examples-probe.mjs
@@ -1,7 +1,7 @@
import {evaluateSource,inspect} from './source-probe-helpers.mjs';
const el=id=>document.getElementById(id),delay=ms=>new Promise(r=>setTimeout(r,ms));
const assert=(ok,message)=>{if(!ok)throw Error(message);};
-const input=(id,value)=>{el(id).value=value;el(id).dispatchEvent(new Event('input'));};
+const input=(id,value)=>{if(id==='source-editor'){globalThis.__sourceEditor.replaceSource(value,true);return;}el(id).value=value;el(id).dispatchEvent(new Event('input'));};
const change=(id,value)=>{el(id).value=value;el(id).dispatchEvent(new Event('change'));};
async function status(want){for(let i=0;i<4500;i++){if(el('status').textContent===want)return;await delay(20);}throw Error(want+': '+el('status').textContent+' / '+el('compile-diagnostic').textContent+' / '+el('operation-diagnostic').textContent);}
export async function run(control,backend='haskell-wasm'){
@@ -24,7 +24,7 @@ export async function run(control,backend='haskell-wasm'){
const evaluate=async(expression,output,expected)=>assert(await evaluateSource(expression,output)===expected,expression+' expected '+expected);
const defaults=[['greeting','string','Hello, world!'],['total','number','12'],['double 6','number','12'],['count','number','3'],['total','number','24'],['message 0','string','Your basket is empty.']];
for(let i=0;i<basics.length;i++){
- await select(basics[i]);const original=el('source-editor').value;
+ await select(basics[i]);const original=globalThis.__sourceEditor.getSource();
await evaluate(...defaults[i]);
if(!el('restore-source').hidden){el('restore-source').click();await status('Ready');}
if(i===0){input('source-editor',original.replace('answer = 42','answer = 7'));await status('Compiled');await evaluate('answer','number','7');}
@@ -33,7 +33,7 @@ export async function run(control,backend='haskell-wasm'){
if(i===3){input('source-editor',original.replace('numbers = [2 4 6]','numbers = [2 4 6 8]'));await status('Compiled');await evaluate('count','number','4');await evaluate('total','number','20');input('source-editor',original.replace('numbers = [2 4 6]','numbers = []'));await status('Compiled');await evaluate('count','number','0');await evaluate('total','number','0');}
if(i===4){input('source-editor',original.replace('Math.multiply number 2','Math.multiply number 3'));await status('Compiled');await evaluate('total','number','36');}
if(i===5){input('source-editor',original.replace('message _ =','message 2 = "You have two items."\nmessage _ ='));await status('Compiled');await evaluate('message 2','string','You have two items.');await evaluate('message 4','string','You have several items.');}
- el('restore-source').click();await status('Ready');assert(el('source-editor').value===original,'Restore '+basics[i]);
+ el('restore-source').click();await status('Ready');assert(globalThis.__sourceEditor.getSource()===original,'Restore '+basics[i]);
}
await select('language-reference');
const catalogue=await(await fetch(new URL('catalogue.json',base))).json();
diff --git a/ext/demo-site/test/definition-name-inputs.mjs b/ext/demo-site/test/definition-name-inputs.mjs
@@ -25,55 +25,54 @@ export async function definitionNameInputs({send,evaluate,report,prefix}){
await send('Emulation.setDeviceMetricsOverride',{width,height:1000,deviceScaleFactor:1,mobile:width<741});
await evaluate("new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))");
await mouse(target);await inspect();
- assert(await evaluate("document.activeElement.id!=='source-editor'"),'Inspection does not focus the textarea/open its keyboard');
- const expected=await evaluate("document.getElementById('source-editor').value");
+ assert(await evaluate("document.activeElement!==globalThis.__sourceEditor.view.contentDOM"),'Inspection keeps focus outside the editing surface');
+ const expected=await evaluate("globalThis.__sourceEditor.getSource()");
await mouse(`document.querySelector('.edit-definition-name')`);
- assert(await evaluate("document.activeElement.id==='source-editor'&&document.getElementById('source-editor').value.slice(document.getElementById('source-editor').selectionStart,document.getElementById('source-editor').selectionEnd)==='answer'"),'Trusted Edit name focuses and selects the native identifier');
+ assert(await evaluate("document.activeElement===globalThis.__sourceEditor.view.contentDOM&&globalThis.__sourceEditor.getSource().slice(globalThis.__sourceEditor.getSelection().from,globalThis.__sourceEditor.getSelection().to)==='answer'"),'Trusted Edit name focuses and selects the native identifier');
await send('Input.insertText',{text:'renamed'});
- assert.equal(await evaluate("document.getElementById('source-editor').value"),expected.replace('answer =','renamed ='),'Native typing replaces only the declaration name');
+ assert.equal(await evaluate("globalThis.__sourceEditor.getSource()"),expected.replace('answer =','renamed ='),'Native typing replaces only the declaration name');
await key('z','KeyZ',90,2);
- assert.equal(await evaluate("document.getElementById('source-editor').value"),expected,'Rename has native undo');
+ assert.equal(await evaluate("globalThis.__sourceEditor.getSource()"),expected,'Rename has native undo');
await wait("document.getElementById('status').textContent==='Compiled'",'undo compile');
- await evaluate(`document.getElementById('source-editor').focus({preventScroll:true})`);await key('Tab','Tab',9);
+ await evaluate(`globalThis.__sourceEditor.focus()`);await key('Tab','Tab',9);
assert(await evaluate(`document.activeElement===${target}`),'Tab reaches the declaration name');
await key('Enter','Enter',13);await inspect();
assert(await evaluate("document.activeElement===document.querySelector('.definition-card pre')"),'Keyboard inspection focuses the result');
await key('Escape','Escape',27);
assert(await evaluate(`${closed}&&document.activeElement===${target}`),'Escape returns keyboard focus to the definition name / '+JSON.stringify(await evaluate(`({active:document.activeElement.outerHTML.slice(0,250),hidden:${closed},target:${target}.outerHTML,scroll:document.getElementById('source-editor').scrollTop,status:document.getElementById('status').textContent})`)));
await key(' ','Space',32);await inspect();await close();
- // Clicking the RHS remains normal caret placement, not inspection.
- const rhs=await evaluate("(()=>{const s=[...document.querySelectorAll('.syntax-viewport .syntax-definition')].find(s=>s.textContent==='answer').getBoundingClientRect();return {x:s.right+parseFloat(getComputedStyle(document.getElementById('source-editor')).fontSize)*1.5,y:s.y+s.height/2};})()");
+ // Clicking the RHS places the editing caret.
+ const rhs=await evaluate("(()=>{const s=[...document.querySelectorAll('.cm-content .syntax-definition')].find(s=>s.textContent==='answer').getBoundingClientRect();return {x:s.right+parseFloat(getComputedStyle(document.getElementById('source-editor')).fontSize)*1.5,y:s.y+s.height/2};})()");
await send('Input.dispatchMouseEvent',{type:'mousePressed',...rhs,button:'left',clickCount:1});
await send('Input.dispatchMouseEvent',{type:'mouseReleased',...rhs,button:'left',clickCount:1});
- assert(await evaluate(`${closed}&&document.activeElement.id==='source-editor'`),'RHS click edits normally');
+ assert(await evaluate(`${closed}&&document.activeElement===globalThis.__sourceEditor.view.contentDOM`),'RHS click edits normally');
const p=await point(target);
await send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[{...p,radiusX:2,radiusY:2}]});
await send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});await inspect();
- assert(await evaluate("document.activeElement.id!=='source-editor'"),'Touch inspection leaves the editing keyboard closed');
+ assert(await evaluate("document.activeElement!==globalThis.__sourceEditor.view.contentDOM"),'Touch inspection leaves the editing keyboard closed');
await close();
const hold=await point(target);
await send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[{...hold,radiusX:2,radiusY:2}]});
await pause(750);await send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});await pause(100);
assert(await evaluate(closed),'Real touch hold does not inspect');
- assert(await evaluate("document.activeElement.id==='source-editor'&&document.getElementById('source-editor').value.slice(document.getElementById('source-editor').selectionStart,document.getElementById('source-editor').selectionEnd)==='answer'"),'Touch hold selects the identifier in the native editor / '+JSON.stringify(await evaluate(`({active:document.activeElement.outerHTML.slice(0,200),start:document.getElementById('source-editor').selectionStart,end:document.getElementById('source-editor').selectionEnd,target:${target}.outerHTML})`)));
+ assert(await evaluate("document.activeElement===globalThis.__sourceEditor.view.contentDOM&&globalThis.__sourceEditor.getSource().slice(globalThis.__sourceEditor.getSelection().from,globalThis.__sourceEditor.getSelection().to)==='answer'"),'Touch hold selects the identifier in the native editor / '+JSON.stringify(await evaluate(`({active:document.activeElement.outerHTML.slice(0,200),start:globalThis.__sourceEditor.getSelection().from,end:globalThis.__sourceEditor.getSelection().to,target:${target}.outerHTML})`)));
await evaluate('document.getSelection().removeAllRanges()');
- await evaluate(`document.getElementById('source-editor').setSelectionRange(0,0);${target}.focus({preventScroll:true})`);
+ await evaluate(`globalThis.__sourceEditor.select(0);${target}.focus({preventScroll:true})`);
const pan=await point(target);
await send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[pan]});
await send('Input.dispatchTouchEvent',{type:'touchMove',touchPoints:[{x:pan.x,y:pan.y+40}]});
await pause(550);await send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});
- assert(await evaluate(`${closed}&&document.getElementById('source-editor').selectionStart===0&&document.getElementById('source-editor').selectionEnd===0`),'Touch panning cancels the hold without selecting or inspecting');
- // Start in ordinary text and drag across a clickable name. The textarea,
- // not the overlay, must own the native selection throughout the gesture.
- const drag=await evaluate("(()=>{const w=document.getElementById('source-editor').closest('.syntax-editor'),a=w.querySelector('.syntax-directive').getBoundingClientRect(),b=w.querySelector('[data-definition=identity]').getBoundingClientRect();return {from:{x:a.left+2,y:a.top+a.height/2},to:{x:b.left+b.width/2,y:b.top+b.height/2}};})()");
+ assert(await evaluate(`${closed}&&globalThis.__sourceEditor.getSelection().from===0&&globalThis.__sourceEditor.getSelection().to===0`),'Touch panning cancels the hold without selecting or inspecting');
+ // Drag from ordinary text across a clickable name using editor selection.
+ const drag=await evaluate("(()=>{const w=document.getElementById('source-editor'),a=w.querySelector('.syntax-directive').getBoundingClientRect(),b=w.querySelector('[data-definition=identity]').getBoundingClientRect();return {from:{x:a.left+2,y:a.top+a.height/2},to:{x:b.left+b.width/2,y:b.top+b.height/2}};})()");
await send('Input.dispatchMouseEvent',{type:'mousePressed',...drag.from,button:'left',clickCount:1});
await send('Input.dispatchMouseEvent',{type:'mouseMoved',...drag.to,button:'left',buttons:1});
await send('Input.dispatchMouseEvent',{type:'mouseReleased',...drag.to,button:'left',clickCount:1});
- assert(await evaluate(`${closed}&&document.getElementById('source-editor').value.slice(document.getElementById('source-editor').selectionStart,document.getElementById('source-editor').selectionEnd).includes('answer = 42')`),'Native drag selection crosses name decorations without inspecting');
- // A native range selection remains possible in the underlying textarea.
- await evaluate("(()=>{const e=document.getElementById('source-editor');e.focus();e.setSelectionRange(e.value.indexOf('identity x'),e.value.indexOf('identity x')+14);e.dispatchEvent(new Event('select'));})()");
- assert(await evaluate("document.getElementById('source-editor').selectionEnd>document.getElementById('source-editor').selectionStart"),'Native source selections survive name decoration');
+ assert(await evaluate(`${closed}&&globalThis.__sourceEditor.getSource().slice(globalThis.__sourceEditor.getSelection().from,globalThis.__sourceEditor.getSelection().to).includes('answer = 42')`),'Native drag selection crosses name decorations without inspecting');
+ // Select an identifier range in the canonical document.
+ await evaluate("(()=>{const e=globalThis.__sourceEditor,start=e.getSource().indexOf('identity x');e.select(start,start+14);})()");
+ assert(await evaluate("globalThis.__sourceEditor.getSelection().to>globalThis.__sourceEditor.getSelection().from"),'Native source selections survive name decoration');
if(prefix){
await evaluate("document.activeElement.blur();window.scrollTo({top:0,behavior:'instant'})");
const capture=async suffix=>{
diff --git a/ext/demo-site/test/definition-names-probe.mjs b/ext/demo-site/test/definition-names-probe.mjs
@@ -1,5 +1,5 @@
-// Actual compiled definitions and shipped editor controls; no evaluator substitute.
-import {el,input,change,status,wait,inspect,card,result,pause} from './source-probe-helpers.mjs';
+// Compiled-definition inspection through the shipped editor controls.
+import {el,input,change,status,wait,inspect,card,result,pause,sourceEditor} from './source-probe-helpers.mjs';
const assert=(ok,message)=>{if(!ok)throw Error(message);};
export async function run(control,backend='haskell-wasm'){
await status('Ready');
@@ -18,24 +18,23 @@ outer x = let
select [] = 0
select xs = 1
-- comment = 1`;
- const editor=el('source-editor'),wrapper=editor.closest('.syntax-editor');
- input('source-editor',source);await status('Compiled');editor.scrollTop=0;editor.dispatchEvent(new Event('scroll'));
+ const editor=sourceEditor,wrapper=editor.dom;
+ input('source-editor',source);await status('Compiled');editor.view.scrollDOM.scrollTop=0;
await pause(0);
const target=name=>wrapper.querySelector(`[data-definition="${name}"]`);
assert(!wrapper.querySelector('.definition-gutter'),'No gutter');
- assert(parseFloat(getComputedStyle(editor).paddingLeft)<=20,'No reserved horizontal inspection column');
+ assert(parseFloat(getComputedStyle(wrapper).paddingLeft)<=20,'No reserved horizontal inspection column');
const names=[...new Set([...wrapper.querySelectorAll('[data-definition]')].map(button=>button.dataset.definition))];
assert(JSON.stringify(names)===JSON.stringify(['answer','identity',long,'text','outer','select']),'Only unique top-level declaration heads are interactive');
assert(!target('local')&&!target('x')&&!target('fake')&&!target('comment'),'No local variables, references, comments or string lookalikes');
- assert(!target('answer').hidden&&!target('answer').disabled&&target('answer').tabIndex===0,'Compiled names are keyboard accessible');
+ assert(!target('answer').hidden&&target('answer').getAttribute('aria-disabled')==='false'&&target('answer').tabIndex===0,'Compiled names are keyboard accessible');
assert(await inspect('answer')==='42','Name opens the actual retained definition');
assert(target('answer').getAttribute('aria-expanded')==='true','Open name highlighted');
card().querySelector('.edit-definition-name').click();
const offset=source.indexOf('answer =');
- assert(card().hidden&&document.activeElement===editor&&editor.selectionStart===offset&&editor.selectionEnd===offset+6,'Edit name selects exactly the declaration, not its export or references');
- assert(editor.value===source,'Opening/closing and Edit name do not mutate source');
- // Selection/hold/drag must not accidentally inspect. These DOM cases complement
- // the harness's trusted mouse, touch and keyboard input.
+ assert(card().hidden&&document.activeElement===editor.view.contentDOM&&editor.getSelection().from===offset&&editor.getSelection().to===offset+6,'Edit name selects exactly the declaration, not its export or references');
+ assert(editor.getSource()===source,'Opening/closing and Edit name do not mutate source');
+ // Selection, hold and drag checks complement trusted mouse/touch/keyboard input.
const button=target('answer');
const down=()=>button.dispatchEvent(new PointerEvent('pointerdown',{clientX:10,clientY:10,pointerId:1,bubbles:true}));
const click=()=>button.dispatchEvent(new MouseEvent('click',{detail:1,bubbles:true}));
@@ -43,41 +42,26 @@ select xs = 1
down();button.dispatchEvent(new PointerEvent('pointermove',{clientX:30,clientY:10,pointerId:1,bubbles:true}));click();assert(card().hidden,'Dragging is not a tap');
down();const menu=new MouseEvent('contextmenu',{bubbles:true,cancelable:true});button.dispatchEvent(menu);click();assert(!menu.defaultPrevented&&card().hidden,'Native context menu is not intercepted');
down();document.getSelection().selectAllChildren(button);click();assert(card().hidden,'Selecting the identifier does not inspect');document.getSelection().removeAllRanges();
- editor.dispatchEvent(new CompositionEvent('compositionstart'));
- assert(getComputedStyle(wrapper.querySelector('.definition-targets')).display==='none','IME has no overlapping inspection targets');
- editor.dispatchEvent(new CompositionEvent('compositionend'));
- input('source-editor',source.replaceAll('answer','renamed'));
- assert([...wrapper.querySelectorAll('[data-definition]')].every(button=>button.disabled||button.hidden),'Dirty names lose clickability immediately');
+ wrapper.dispatchEvent(new CompositionEvent('compositionstart'));
+ assert(getComputedStyle(target('answer')).pointerEvents==='none','IME disables name pointer activation');
+ wrapper.dispatchEvent(new CompositionEvent('compositionend'));
+ input('source-editor',source.replaceAll('answer','renamed'));await pause(0);
+ assert([...wrapper.querySelectorAll('[data-definition]')].every(button=>button.getAttribute('aria-disabled')==='true'||button.hidden),'Dirty names lose clickability immediately');
await status('Compiled');assert(await inspect('renamed')==='42','Renamed definition resolves from the new compiled revision');
input('source-editor','!export renamed\nrenamed = missing');await status('Compilation failed');
- assert([...wrapper.querySelectorAll('[data-definition]')].every(button=>button.disabled&&button.hidden),'Failed compilation leaves no clickable underline');
- input('source-editor',source);await status('Compiled');editor.scrollTop=0;editor.dispatchEvent(new Event('scroll'));await pause(0);
- // Long declaration names wrap without stealing the expression's hit area.
- const mirror=wrapper.querySelector('.syntax-viewport pre');
- const span=[...mirror.querySelectorAll('.syntax-definition')].find(span=>span.textContent===long);
- const boxes=[...span.getClientRects()];
- const targets=[...wrapper.querySelectorAll(`[data-definition="${long}"]`)];
- assert(targets.length===boxes.length,'Every wrapped fragment has its own target');
- for(let i=0;i<boxes.length;i++){
- const rect=targets[i].getBoundingClientRect();
- assert(Math.abs(rect.left-boxes[i].left)<1&&Math.abs(rect.width-boxes[i].width)<1,'No hit area extends over adjacent expression text');
- }
- assert(targets.filter(button=>button.tabIndex===0).length===1,'Wrapped definition has one tab stop');
- if(boxes.length>1){
- editor.style.height='240px';await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));
- editor.scrollTop=span.getClientRects()[0].top-editor.getBoundingClientRect().top+parseFloat(getComputedStyle(editor).lineHeight);
- editor.dispatchEvent(new Event('scroll'));
- const visible=[...wrapper.querySelectorAll(`[data-definition="${long}"]`)].filter(button=>!button.hidden);
- assert(visible.length>0&&visible[0].tabIndex===0,'A partially scrolled wrapped name retains a visible keyboard stop');
- visible[0].click();await pause(0);await wait(()=>!card().querySelector('select').disabled&&result()==='9','wrapped observation');
- card().querySelector('[aria-label="Close definition inspection"]').click();
- assert(document.activeElement===visible[0],'Close returns focus to a visible fragment, not its offscreen first line');
- editor.style.height='';editor.scrollTop=0;editor.dispatchEvent(new Event('scroll'));
- await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));
+ assert([...wrapper.querySelectorAll('[data-definition]')].every(button=>button.getAttribute('aria-disabled')==='true'&&button.hidden),'Failed compilation leaves no clickable underline');
+ input('source-editor',source);await status('Compiled');editor.view.scrollDOM.scrollTop=0;await pause(0);
+ // Wrapped declaration fragments retain their inline text hit areas.
+ const span=target(long);span.scrollIntoView({block:'center',behavior:'instant'});await new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)));const boxes=[...span.getClientRects()];
+ assert(boxes.length>0&&span.tabIndex===0,'Wrapped inline name has one keyboard stop');
+ for(const box of boxes){
+ const hit=document.elementFromPoint(box.left+Math.min(3,box.width/2),box.top+box.height/2);
+ assert(hit&&span.contains(hit),'Every visible name fragment has its own native inline hit area: '+JSON.stringify({box,hit:hit?.outerHTML.slice(0,180),window:innerHeight}));
}
+ assert(!wrapper.querySelector('.definition-targets'),'No manual overlay rectangles');
assert(await inspect(long)==='9','Wrapped private definition is inspectable');
card().querySelector('[aria-label="Close definition inspection"]').click();
assert(document.activeElement===target(long),'Closing returns focus to the name');
- editor.scrollTop=0;editor.dispatchEvent(new Event('scroll'));
+ editor.view.scrollDOM.scrollTop=0;
return {userAgent:navigator.userAgent,checks:['underlined definition names without a gutter; exact wrapped hit areas; unique heads only; retained/private inspection; Edit name and focus; dirty/error invalidation; native context menus; hold/drag/selection suppression; IME; one keyboard stop per name']};
}
diff --git a/ext/demo-site/test/firefox-idle.mjs b/ext/demo-site/test/firefox-idle.mjs
@@ -37,8 +37,8 @@ const snapshot=context=>evaluate(context,`(()=>{
const get=id=>document.getElementById(id);
return {at:new Date().toISOString(),visibility:document.visibilityState,status:get('status')?.textContent,
backend:get('runtime-backend')?.value,program:get('program-picker')?.value,
- sourceHidden:get('source-editor')?.hidden,sourceReadOnly:get('source-editor')?.readOnly,
- sourceDisabled:get('source-editor')?.disabled,source:get('source-editor')?.value,
+ sourceHidden:get('source-editor')?.hidden,sourceReadOnly:globalThis.__sourceEditor?.isReadOnly,
+ sourceDisabled:globalThis.__sourceEditor?.isDisabled,source:globalThis.__sourceEditor?.getSource(),
result:document.querySelector('.definition-card pre')?.textContent,
diagnostic:get('compile-diagnostic')?.textContent,inspectionDisabled:document.querySelector('.definition-card select')?.disabled,
errors:window.__idleErrors,visibilityChanges:window.__idleVisibility};
@@ -49,7 +49,7 @@ async function wait(context,condition,label){
throw Error('Timeout '+label+': '+JSON.stringify(await snapshot(context)));
}
const status=(context,text)=>wait(context,`document.getElementById('status')?.textContent===${JSON.stringify(text)}`,text);
-const input=(context,id,value)=>evaluate(context,`(()=>{const e=document.getElementById(${JSON.stringify(id)});e.value=${JSON.stringify(value)};e.dispatchEvent(new Event('input'));})()`);
+const input=(context,id,value)=>evaluate(context,`(()=>{const e=document.getElementById(${JSON.stringify(id)});if(${JSON.stringify(id)}==='source-editor'){globalThis.__sourceEditor.replaceSource(${JSON.stringify(value)},true);}else{e.value=${JSON.stringify(value)};e.dispatchEvent(new Event('input'));}})()`);
const change=(context,id,value)=>evaluate(context,`(()=>{const e=document.getElementById(${JSON.stringify(id)});e.value=${JSON.stringify(value)};e.dispatchEvent(new Event('change'));})()`);
const click=(context,id)=>evaluate(context,`document.getElementById(${JSON.stringify(id)}).click()`);
async function editable(context){
@@ -83,7 +83,7 @@ async function exercise(job){
await run(context,'answer',mode==='compiled'?'43':'42');
for(let cycle=0;cycle<2;cycle++){
await select(context,'arithmetic');await run(context,'total','12');
- const source=await evaluate(context,"document.getElementById('source-editor').value");
+ const source=await evaluate(context,"globalThis.__sourceEditor.getSource()");
assert(source.includes('Math.add 5 7'),'Known independently checked arithmetic specimen');
await input(context,'source-editor',source.replace('Math.add 5 7','Math.add 8 9'));
await status(context,'Compiled');await run(context,'total','17');
@@ -136,9 +136,9 @@ try{
window.addEventListener('unhandledrejection',event=>window.__idleErrors.push({type:'rejection',message:String(event.reason)}));
document.addEventListener('visibilitychange',()=>window.__idleVisibility.push({visibility:document.visibilityState,at:Date.now()}));
})()`);
- await status(context,'Ready');
+ await status(context,'Ready');await evaluate(context,"import('/source-probe-helpers.mjs').then(()=>true)");
if(mode==='compiled'){
- const source=await evaluate(context,"document.getElementById('source-editor').value");
+ const source=await evaluate(context,"globalThis.__sourceEditor.getSource()");
assert(source.includes('answer = 42'));await input(context,'source-editor',source.replace('answer = 42','answer = 43'));
await status(context,'Compiled');
}
diff --git a/ext/demo-site/test/import-fold-inputs.mjs b/ext/demo-site/test/import-fold-inputs.mjs
@@ -0,0 +1,44 @@
+// Trusted input on the packaged Playground's canonical editor document.
+import assert from 'node:assert/strict';
+import {writeFile} from 'node:fs/promises';
+const pause=ms=>new Promise(r=>setTimeout(r,ms));
+export async function importFoldInputs({send,evaluate,report,prefix}){
+ const e='globalThis.__sourceEditor',initial=report.source;
+ const wait=async condition=>{for(let i=0;!await evaluate(condition);i++){assert(i<1600,condition);await pause(25);}};
+ const key=async(key,code,vk,modifiers=0)=>{await send('Input.dispatchKeyEvent',{type:'keyDown',key,code,windowsVirtualKeyCode:vk,modifiers,...(key==='Enter'?{text:'\r'}:{})});await send('Input.dispatchKeyEvent',{type:'keyUp',key,code,windowsVirtualKeyCode:vk,modifiers});await pause(30);};
+ const point=async expression=>evaluate(`(()=>{const element=${expression};element.scrollIntoView({block:'center',behavior:'instant'});const r=element.getBoundingClientRect();return {x:r.left+r.width*.25,y:r.top+r.height/2};})()`);
+ const click=async expression=>{const p=await point(expression);await send('Input.dispatchMouseEvent',{type:'mousePressed',...p,button:'left',clickCount:1});await send('Input.dispatchMouseEvent',{type:'mouseReleased',...p,button:'left',clickCount:1});await pause(50);};
+ const widget=`${e}.dom.querySelector('.import-hash')`,alias=`[...${e}.dom.querySelectorAll('.syntax-name')].find(span=>span.textContent==='N')`;
+ const counts=`({folded:${e}.dom.querySelectorAll('.import-hash').length,full:${e}.dom.querySelectorAll('.import-hash-full').length})`;
+ await send('Browser.grantPermissions',{origin:await evaluate('location.origin'),permissions:['clipboardReadWrite','clipboardSanitizedWrite']});
+ for(const width of [390,1440]){
+ await send('Emulation.setDeviceMetricsOverride',{width,height:1000,deviceScaleFactor:1,mobile:width<741});
+ await evaluate(`${e}.replaceSource(${JSON.stringify(initial)},true)`);await wait("document.getElementById('status').textContent==='Compiled'");
+ assert.deepEqual(await evaluate(counts),{folded:3,full:0});
+ await click(widget);await key('Enter','Enter',13);assert((await evaluate(`${widget}.textContent`)).includes('...'),'Keyboard toggles are presentation only');
+ await click(alias);assert.deepEqual(await evaluate(counts),{folded:2,full:1});
+ assert.equal(await evaluate(`${e}.getSelection().from`),initial.indexOf(' as N')+4,'Caret maps past hidden 64-character hash');
+ await send('Input.insertText',{text:'M'});await key('z','KeyZ',90,2);assert.equal(await evaluate(`${e}.getSource()`),initial,'Typing undo');
+ await evaluate(`${e}.select(${initial.indexOf('!import')},${initial.indexOf('!import '+report.math+' as P')})`);
+ assert.deepEqual(await evaluate(counts),{folded:1,full:2});
+ await key('c','KeyC',67,2);const selected=await evaluate('navigator.clipboard.readText()');assert(selected.includes(report.math)&&!selected.includes('...'),'Partial selection copies complete hashes');
+ await key('a','KeyA',65,2);await key('c','KeyC',67,2);assert.equal(await evaluate('navigator.clipboard.readText()'),initial,'Native full-source clipboard');
+ await evaluate(`${e}.select(0)`);const inserted=`!import ${report.math} as Q\n`;
+ await send('Input.insertText',{text:inserted});await pause(30);assert.equal((await evaluate(counts)).folded,4,'Pasted import gains fold');
+ await key('z','KeyZ',90,2);assert.equal(await evaluate(`${e}.getSource()`),initial,'Undo restores source after dynamic decoration');
+ await key('Z','KeyZ',90,10);assert.equal(await evaluate(`${e}.getSource()`),inserted+initial,'Redo restores source after dynamic decoration');await key('z','KeyZ',90,2);
+ await evaluate(`${e}.select(${initial.length})`);const p=await point(alias);
+ await send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[p]});await send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});await pause(80);
+ assert.deepEqual(await evaluate(counts),{folded:2,full:1},'Touch reveals only the touched import line');
+ await evaluate(`${e}.select(${initial.indexOf(report.math)+64})`);await key('Backspace','Backspace',8);assert.equal((await evaluate(`${e}.getSource()`)).length,initial.length-1,'Hash editing deletes one character');await key('z','KeyZ',90,2);assert.equal(await evaluate(`${e}.getSource()`),initial);
+ await wait("document.getElementById('status').textContent==='Compiled'");await evaluate(`${e}.setAvailability(true,false)`);
+ await send('Input.insertText',{text:'MUST NOT EDIT'});assert.equal(await evaluate(`${e}.getSource()`),initial,'Busy/read-only blocks native edits');await evaluate(`${e}.setAvailability(false,false)`);
+ if(prefix){const {cssContentSize:r}=await send('Page.getLayoutMetrics');const shot=await send('Page.captureScreenshot',{format:'png',captureBeyondViewport:true,clip:{x:0,y:0,width:r.width,height:r.height,scale:1}});await writeFile(prefix+'-folds-'+width+'.png',Buffer.from(shot.data,'base64'));}
+ }
+ // Enter inserts a plain newline; read-only state also applies to command keys.
+ await evaluate(`${e}.replaceSource(' answer = 42',true);${e}.select(${(' answer = 42').length})`);await key('Enter','Enter',13);
+ assert.equal(await evaluate(`${e}.getSource()`),' answer = 42\n','Enter inserts exactly one newline');
+ await evaluate(`${e}.setAvailability(true,false)`);await key('Enter','Enter',13);assert.equal(await evaluate(`${e}.getSource()`),' answer = 42\n','Read-only also rejects Enter');
+ await evaluate(`${e}.setAvailability(false,false);${e}.replaceSource(${JSON.stringify(initial)},true)`);await wait("document.getElementById('status').textContent==='Compiled'");
+ report.checks.push('trusted per-line mouse/touch; canonical alias caret; full and selected-source clipboard; pasted-import native undo/redo; read-only at 390/1440px');
+}
diff --git a/ext/demo-site/test/import-folds-probe.mjs b/ext/demo-site/test/import-folds-probe.mjs
@@ -0,0 +1,28 @@
+// Packaged page, real canonical editor and actual selected compiler/runtime.
+import {sourceEditor as editor,input,change,status,el,inspect,pause} from './source-probe-helpers.mjs';
+const assert=(ok,message)=>{if(!ok)throw Error(message);};
+export async function run(_control,backend='haskell-wasm'){
+ await status('Ready');if(el('runtime-backend').value!==backend){change('runtime-backend',backend);await status('Ready');}
+ const catalog=await(await fetch(new URL('../reference/libraries.json',document.querySelector('script[type=module][src]').src))).json();
+ const releases=catalog.releases;
+ const hash=name=>releases.find(row=>row.name==='tricu-lib-'+name&&row.version==='0.3.0').manifest;
+ const math=hash('native-math'),base=hash('base');
+ const source=`-- λ🙂 canonical offsets\n!import ${math} as N\n!import ${base} as B\n!import ${math} as P\n!export answer\nanswer = N.add 40 2`;
+ document.querySelector('[data-compiler-example=identity]').click();input('source-editor',source);await status('Compiled');
+ const widgets=()=>[...editor.dom.querySelectorAll('.import-hash')],full=()=>editor.dom.querySelectorAll('.import-hash-full').length;
+ assert(widgets().length===3&&widgets()[0].textContent===math.slice(0,3)+'...'+math.slice(-3),'Exact per-hash abbreviation');
+ assert(editor.getSource()===source,'Compilation sees canonical source');
+ let edits=0;const unsubscribe=editor.onChange(()=>edits++);
+ widgets()[0].click();assert(widgets()[0].textContent===math&&widgets()[1].textContent.includes('...'),'Independent expansion');
+ widgets()[0].click();assert(widgets()[0].textContent.includes('...'),'Independent collapse');
+ editor.select(source.indexOf(' as N')+4);assert(full()===1&&widgets().length===2,'Only edited line reveals');
+ editor.select(source.indexOf('!import'),source.indexOf('!import '+math+' as P'));assert(full()===2&&widgets().length===1,'Only selected lines reveal');
+ editor.select(source.length);await pause(0);assert(widgets().length===3&&edits===0,'Presentation/selection preserves source and revision');
+ editor.edit(0,0,`!import ${math} as Q\n`);editor.select(editor.getSource().length);
+ assert(widgets().length===4,'New import receives decoration');assert(editor.undo(),'Insertion undo');assert(editor.getSource()===source,'One undo restores entire canonical document');
+ assert(editor.redo()&&widgets().length===4,'Redo preserves dynamic folding');assert(editor.undo()&&editor.getSource()===source,'Undo remains complete');
+ await status('Compiled');assert(await inspect('answer','number')==='42','Actual compiler/runtime accepts full-hash imports');
+ document.querySelector('[aria-label="Close definition inspection"]').click();
+ editor.select(source.length);editor.view.contentDOM.blur();await pause(0);unsubscribe();
+ return {checks:['per-line import hash folding; independent controls; selected ranges; immutable canonical source/revisions; dynamic import undo/redo; actual compiler/runtime'],source,math};
+}
diff --git a/ext/demo-site/test/import-folds.test.mjs b/ext/demo-site/test/import-folds.test.mjs
@@ -0,0 +1,28 @@
+import test from 'node:test';import assert from 'node:assert/strict';
+import {EditorState,EditorSelection,EditorView} from '../dist/codemirror.js';
+import {importSites,selectedImportLines,importFolds,importFocus} from '../dist/import-folds.js';
+const hash='0123456789abcdef'.repeat(4),other='abcdef0123456789'.repeat(4);
+test('import projection recognizes only real, complete, line-head import hashes',()=>{
+ const source=`-- !import ${hash}\ntext = "!import ${hash}"\n|- !import ${hash} -|\nx = !import ${hash}\n!import ${hash.slice(1)} as short\n!import ${hash.toUpperCase()} as upper\n!import ${hash}x as extra\n!import ${hash} as A\n !import\t${other} as B`;
+ const sites=importSites(EditorState.create({doc:source}));
+ assert.equal(sites.length,2);assert.deepEqual(sites.map(site=>site.hash),[hash,other]);
+ for(const site of sites)assert.equal(source.slice(site.from,site.to),site.hash);
+});
+test('selection exposes only affected import lines, including exclusive end boundaries',()=>{
+ const doc=`-- λ🙂\n!import ${hash} as A\n!import ${other} as B\nanswer = 42`;
+ let state=EditorState.create({doc});
+ assert.deepEqual([...selectedImportLines(state,false)],[]);
+ state=state.update({selection:EditorSelection.single(doc.indexOf(' as A')+4)}).state;
+ assert.deepEqual([...selectedImportLines(state,true)],[2]);
+ state=state.update({selection:EditorSelection.single(state.doc.line(2).from,state.doc.line(4).from)}).state;
+ assert.deepEqual([...selectedImportLines(state,false)],[2,3]);
+});
+test('projection transactions preserve canonical source and character-level ranges',()=>{
+ const doc=`!import ${hash} as A\n!import ${other} as B\nanswer = 42`;
+ let state=EditorState.create({doc,extensions:[importFolds]});
+ assert.equal(state.field(importFolds).decorations.size,2);
+ state=state.update({selection:EditorSelection.single(state.doc.line(3).from),effects:importFocus.of(true)}).state;
+ assert.equal(state.doc.toString(),doc);assert.deepEqual(state.facet(EditorView.atomicRanges),[]);
+ state=state.update({changes:{from:0,insert:`!import ${hash} as C\n`}}).state;
+ assert.equal(state.field(importFolds).sites.length,3);assert.equal(state.doc.toString(),`!import ${hash} as C\n`+doc);
+});
diff --git a/ext/demo-site/test/import-picker-probe.mjs b/ext/demo-site/test/import-picker-probe.mjs
@@ -1,7 +1,7 @@
import {evaluateSource,inspect} from './source-probe-helpers.mjs';
const assert=(ok,message)=>{if(!ok)throw Error(message);};
const el=id=>document.getElementById(id),delay=ms=>new Promise(r=>setTimeout(r,ms));
-const input=(id,value)=>{el(id).value=value;el(id).dispatchEvent(new Event('input'));};
+const input=(id,value)=>{if(id==='source-editor'){globalThis.__sourceEditor.replaceSource(value,true);return;}el(id).value=value;el(id).dispatchEvent(new Event('input'));};
const change=(id,value)=>{el(id).value=value;el(id).dispatchEvent(new Event('change'));};
async function wait(fn,label){for(let i=0;i<4500;i++){if(fn())return;await delay(20);}throw Error('Timeout '+label+' / '+el('status').textContent+' / '+el('import-status').textContent);}
const status=value=>wait(()=>el('status').textContent===value,value);
@@ -132,7 +132,7 @@ outside = zeros 4097`;
const select=async()=>{input('import-search','remainder');await wait(()=>el('import-results').querySelector(`[data-manifest="${math.manifest}"]`),'search export');el('import-results').querySelector(`[data-manifest="${math.manifest}"]`).click();input('import-alias','N');};
await open();await select();
assert(el('import-title').textContent==='native-math','Search reaches native math');
- assert(el('source-editor').value===original,'Browsing preserves draft');
+ assert(globalThis.__sourceEditor.getSource()===original,'Browsing preserves draft');
assert(el('import-preview').textContent===`!import ${math.manifest} as N`,'Exact full manifest preview: '+el('import-preview').textContent);
assert(el('import-version').value==='0.3.0','Newest version initially selected');
assert(el('import-version').options.length>=2,'History available in details: '+[...el('import-version').options].map(o=>o.value));
@@ -143,26 +143,26 @@ outside = zeros 4097`;
await wait(()=>!el('insert-import').disabled,'candidate compiled');
el('insert-import').click();
assert(!el('import-dialog').open,'Insertion closes dialog');
- assert(el('source-editor').value===`!import ${math.manifest} as N\n`+original,'Insertion preserves all original source');
- assert(el('source-editor').selectionStart===0&&el('source-editor').selectionEnd===(`!import ${math.manifest} as N\n`).length,'Inserted line selected');
+ assert(globalThis.__sourceEditor.getSource()===`!import ${math.manifest} as N\n`+original,'Insertion preserves all original source');
+ assert(globalThis.__sourceEditor.getSelection().from===0&&globalThis.__sourceEditor.getSelection().to===(`!import ${math.manifest} as N\n`).length,'Inserted line selected');
await status('Compiled');
- // Undo is one native textarea edit; compilation does not replace the editor.
- el('source-editor').focus();assert(document.execCommand('undo'),'Undo available');
- assert(el('source-editor').value===original,'One undo restores exact original source');await status('Compiled');
+ // Import insertion retains one undo transaction across compilation.
+ globalThis.__sourceEditor.focus();assert(globalThis.__sourceEditor.undo(),'Undo available');
+ assert(globalThis.__sourceEditor.getSource()===original,'One undo restores exact original source');await status('Compiled');
await open();await select();await wait(()=>!el('insert-import').disabled,'reinsert checked');el('insert-import').click();await status('Compiled');
assert(await evaluateSource('N.add answer 8')==='50','Inserted namespace usable from source');
- const inserted=el('source-editor').value;
+ const inserted=globalThis.__sourceEditor.getSource();
await open();await select();await wait(()=>!el('insert-import').disabled,'existing import');
assert(el('import-status').textContent.includes('Already imported as N'),'Existing namespace shown');el('insert-import').click();
- assert(el('source-editor').value===inserted,'Jump does not edit');
+ assert(globalThis.__sourceEditor.getSource()===inserted,'Jump does not edit');
// Alias conflict is based on the native header; a failed check leaves the editor intact.
await open();input('import-search','conversions');el('import-results').querySelector('button').click();input('import-alias','N');
await wait(()=>el('import-status').textContent.includes('already used'),'namespace conflict');assert(el('insert-import').disabled,'Conflict blocks insert');el('import-cancel').click();
- assert(el('source-editor').value===inserted,'Cancellation preserves source');
+ assert(globalThis.__sourceEditor.getSource()===inserted,'Cancellation preserves source');
input('source-editor','!export answer\nanswer = (');await status('Compilation failed');
await open();await select();await wait(()=>el('import-status').textContent.includes('copy the import'),'malformed source fallback');assert(el('insert-import').disabled,'Malformed source blocks insertion');el('import-cancel').click();
input('source-editor',original);await status('Compiled');
- await open();await select();el('import-cancel').click();await delay(400);assert(!el('import-dialog').open,'Check cancelled');assert(el('source-editor').value===original,'Cancellation is an edit-free operation');
+ await open();await select();el('import-cancel').click();await delay(400);assert(!el('import-dialog').open,'Check cancelled');assert(globalThis.__sourceEditor.getSource()===original,'Cancellation is an edit-free operation');
// Local filenames are text and their validated interfaces are searchable.
const bytes=await(await fetch('/_arboricx/bundle/hash/'+math.hash)).arrayBuffer();
const files=new DataTransfer();files.items.add(new File([bytes],'<svg onload=bad>.arboricx'));el('local-module-file').files=files.files;el('local-module-file').dispatchEvent(new Event('change'));
@@ -175,8 +175,8 @@ outside = zeros 4097`;
assert(definition,'Definition matches have their own results');definition.click();
assert(el('import-definition').textContent.includes('Definition: remainder'),'Direct definition detail');
assert(el('try-library').hidden,'Editable source has no expression-only Try action');
- const beforeBrowse=el('source-editor').value;el('import-cancel').click();
- assert(el('source-editor').value===beforeBrowse,'Definition browsing preserves authored source without generating experiments');
+ const beforeBrowse=globalThis.__sourceEditor.getSource();el('import-cancel').click();
+ assert(globalThis.__sourceEditor.getSource()===beforeBrowse,'Definition browsing preserves authored source without generating experiments');
// Source-free library exploration is available and never inserts into a hidden editor.
change('program-picker','hash');input('bundle-hash',math.hash);el('program-hash').dispatchEvent(new Event('submit',{cancelable:true}));await status('Ready');
assert(el('source-editor').hidden&&!el('add-import').hidden,'Explorer available without source');
diff --git a/ext/demo-site/test/inline-io-probe.mjs b/ext/demo-site/test/inline-io-probe.mjs
@@ -1,6 +1,7 @@
+import './source-probe-helpers.mjs';
const assert=(condition,message)=>{if(!condition)throw Error(message);};
const el=id=>document.getElementById(id),pause=ms=>new Promise(r=>setTimeout(r,ms));
-const input=(id,value)=>{el(id).value=value;el(id).dispatchEvent(new Event('input'));};
+const input=(id,value)=>{if(id==='source-editor'){globalThis.__sourceEditor.replaceSource(value,true);return;}el(id).value=value;el(id).dispatchEvent(new Event('input'));};
const change=(id,value)=>{el(id).value=value;el(id).dispatchEvent(new Event('change'));};
async function wait(check,label){for(let i=0;i<3600;i++){if(check())return;await pause(25);}throw Error('Timeout '+label+' / '+el('status').textContent+' / '+el('operation-diagnostic').textContent);}
const status=text=>wait(()=>el('status').textContent===text,text);
@@ -51,7 +52,7 @@ export async function run(control,backend='haskell-wasm'){
el('run-io').click();await status('Finished');assert(el('terminal').textContent==='Explicit output','Rerun clears old terminal');button('write').click();
await open('io');el('io-return-format').value='string';el('step-mode').checked=true;el('run-io').click();await status('Paused before action');
el('next').click();await status('Waiting for input');
- assert(!button('io').hidden&&button('io').disabled&&button('io').getAttribute('aria-expanded')==='true'&&getComputedStyle(button('io')).pointerEvents==='none','Active IO name stays highlighted but cannot start another observation');
+ assert(!button('io').hidden&&button('io').getAttribute('aria-disabled')==='true'&&button('io').getAttribute('aria-expanded')==='true'&&getComputedStyle(button('io')).pointerEvents==='none','Active IO name stays highlighted but cannot start another observation');
input('line-input','a'.repeat(257));el('input-form').requestSubmit();assert(!el('input-form').hidden,'Invalid input remains retryable');
input('line-input','λ雪🙂');el('input-form').requestSubmit();await status('Finished');assert(view().textContent==='λ雪🙂','Returned IO value uses selected interpretation');
el('step-mode').checked=false;el('run-io').click();await status('Waiting for input');el('stop-io').click();
diff --git a/ext/demo-site/test/live-ux-probe.mjs b/ext/demo-site/test/live-ux-probe.mjs
@@ -10,10 +10,10 @@ export async function run(control,backend='haskell-wasm'){
set onmessage(handler){super.onmessage=event=>{if(hold&&['compiled','error'].includes(event.data.type))held.push(()=>handler(event));else handler(event);};}
};
try{
- const original=el('source-editor').value;
+ const original=globalThis.__sourceEditor.getSource();
input('source-editor',original.replace('first 42 7','first 43 7'));
assert(card().querySelector('select').disabled&&result()==='','Edits invalidate old inline output immediately');
- await status('Compiling');assert(!el('source-editor').disabled,'Editing continues during compilation');
+ await status('Compiling');assert(!globalThis.__sourceEditor.isDisabled,'Editing continues during compilation');
input('source-editor',original.replace('first 42 7','first 44 7'));input('source-editor',original.replace('first 42 7','first 45 7'));
await wait(()=>held.length>0,'held compilation');assert(submitted.length===1,'Keystrokes do not restart current compile');
hold=false;held.shift()();await status('Compiled');assert(submitted.length===2&&submitted[1].includes('first 45 7'),'Only newest queued revision compiles');
@@ -31,7 +31,7 @@ export async function run(control,backend='haskell-wasm'){
input('source-editor','answer = 50');change('program-picker','demo:language-reference');await status('Ready');await pause(900);assert(el('status').textContent==='Ready','Package change cancels queued compilation');
document.querySelector('[data-compiler-example=input]').click();await status('Compiled');assert(el('input-form').hidden&&el('terminal').textContent==='','Compilation never runs IO');
await inspect('io');assert(el('input-form').hidden,'Recognition never runs IO');el('io-return-format').value='string';el('run-io').click();await status('Waiting for input');
- assert(el('source-editor').disabled&&el('reset').disabled,'Active IO cannot be replaced by background edits or Clear');input('line-input','hello λ🙂');el('input-form').requestSubmit();await status('Finished');assert(result()==='hello λ🙂','Inline IO return');
+ assert(globalThis.__sourceEditor.isDisabled&&el('reset').disabled,'Active IO cannot be replaced by background edits or Clear');input('line-input','hello λ🙂');el('input-form').requestSubmit();await status('Finished');assert(result()==='hello λ🙂','Inline IO return');
input('source-editor','id x = x\nanswer = id 51\nbomb = (x : x x) (x : x x)');await status('Compiled');assert(await inspect('answer','number')==='51','Unused divergent binding is not forced');
document.querySelector('[aria-label="Inspect compiled definition bomb"]').click();await wait(()=>el('status').textContent==='Inspecting bomb','divergent observation');await pause(150);el('stop').click();await status('Stopped');
}finally{globalThis.Worker=NativeWorker;}
diff --git a/ext/demo-site/test/local-module-probe.mjs b/ext/demo-site/test/local-module-probe.mjs
@@ -5,7 +5,7 @@ async function rejects(fn,pattern){try{await fn();}catch(e){assert(pattern.test(
const el=id=>document.getElementById(id),delay=ms=>new Promise(r=>setTimeout(r,ms));
async function wait(fn){for(let i=0;i<4500;i++){if(fn())return;await delay(20);}throw Error('Timed out: '+el('status').textContent+' / '+el('compiled-module-status').textContent);}
const status=s=>wait(()=>el('status').textContent===s);
-const input=(id,value)=>{el(id).value=value;el(id).dispatchEvent(new Event('input'));};
+const input=(id,value)=>{if(id==='source-editor'){globalThis.__sourceEditor.replaceSource(value,true);return;}el(id).value=value;el(id).dispatchEvent(new Event('input'));};
const change=(id,value)=>{el(id).value=value;el(id).dispatchEvent(new Event('change'));};
export async function run(control,backend){
const base=new URL('../',document.querySelector('script[type=module][src]').src);
diff --git a/ext/demo-site/test/module-probe.mjs b/ext/demo-site/test/module-probe.mjs
@@ -6,7 +6,7 @@ const equal=(actual,expected,label)=>assert(JSON.stringify(actual)===JSON.string
async function rejects(fn,pattern){try{await fn();}catch(e){assert(pattern.test(e.message),'Wrong rejection: '+e.message);return;}throw Error('Expected '+pattern);}
const el=id=>document.getElementById(id),delay=ms=>new Promise(r=>setTimeout(r,ms));
async function status(value){for(let i=0;i<4500;i++){if(el('status').textContent===value)return;await delay(20);}throw Error('Timed out '+value+': '+el('status').textContent+' '+el('compile-diagnostic').textContent);}
-const input=(id,value)=>{el(id).value=value;el(id).dispatchEvent(new Event('input'));};
+const input=(id,value)=>{if(id==='source-editor'){globalThis.__sourceEditor.replaceSource(value,true);return;}el(id).value=value;el(id).dispatchEvent(new Event('input'));};
const change=(id,value)=>{el(id).value=value;el(id).dispatchEvent(new Event('change'));};
export async function run(control,backend='haskell-wasm'){
const base=new URL('../',document.querySelector('script[type=module][src]').src);
@@ -116,14 +116,14 @@ export async function run(control,backend='haskell-wasm'){
// Exercise the actual editable page, including Worker termination and rebuilding.
await status('Ready');change('runtime-backend',backend);await status('Ready');
document.querySelector('[data-compiler-example=module]').click();await status('Compiled');
- assert(el('source-editor').value.includes(math.manifest),'Module example uses an indexed manifest, not a bundle digest');
+ assert(globalThis.__sourceEditor.getSource().includes(math.manifest),'Module example uses an indexed manifest, not a bundle digest');
equal(await inspect('answer','number'),'42','Module scratch example');
input('source-editor',source);el('compile').click();await status('Compiled');
assert(document.querySelector('[aria-label="Inspect compiled definition private"]'),'Private scope remains inspectable');
equal(await evaluateSource('N.add answer private'),'141','Actual page imported application in source');
input('source-editor',`!import ${math.manifest} as N\n!export answer\nloop x = loop x\nanswer = N.add 40 2`);
el('compile').click();await status('Compiled');
- input('source-editor',el('source-editor').value+'\nbomb = loop t');await status('Compiled');document.querySelector('[aria-label="Inspect compiled definition bomb"]').click();await delay(100);el('stop').click();await status('Stopped');
+ input('source-editor',globalThis.__sourceEditor.getSource()+'\nbomb = loop t');await status('Compiled');document.querySelector('[aria-label="Inspect compiled definition bomb"]').click();await delay(100);el('stop').click();await status('Stopped');
assert(!el('compile').disabled,'Stop discards imported heap');
el('compile').click();await status('Compiled');equal(await evaluateSource('N.add answer 1'),'43','Stop/recompile reconstructs verified imports');
// Edit the actual parser/lexer examples, not a scratch copy; verify changed
@@ -134,14 +134,14 @@ export async function run(control,backend='haskell-wasm'){
['lexer','N.inRange character 97 122','N.inRange character 65 90','scanWord "HELLO,world"','HELLO',''],
]){
change('program-picker','demo:'+id);await status('Ready');
- assert(!el('source-editor').hidden&&!el('source-editor').readOnly,'Editable '+id);
- const source=el('source-editor').value;assert(source.includes(before),'Known predicate');
+ assert(!el('source-editor').hidden&&!globalThis.__sourceEditor.isReadOnly,'Editable '+id);
+ const source=globalThis.__sourceEditor.getSource();assert(source.includes(before),'Known predicate');
input('source-editor',source.replace(before,after));el('compile').click();await status('Compiled');
const expressionSource=`let
firstValue [[_ _ value] | _] = value
firstValue _ = ""
in firstValue (${expression})`;equal(await evaluateSource(expressionSource,'string'),want,'Edited '+id+' result');
- el('restore-source').click();await status('Ready');equal(el('source-editor').value,source,'Restore '+id);
+ el('restore-source').click();await status('Ready');equal(globalThis.__sourceEditor.getSource(),source,'Restore '+id);
equal(await evaluateSource(expressionSource,'string'),original,'Restored '+id+' behavior');
}
return {userAgent:navigator.userAgent,checks:['all sixteen editable demos match native goldens; parser/lexer edit and restore; native headers; qualified/open imports; full reexports; retained private/import scope; collision/diagnostic controls; transport and manifest faults; no capabilities; repeated replacement/GC; actual page Stop/recompile']};
diff --git a/ext/demo-site/test/probe-api.mjs b/ext/demo-site/test/probe-api.mjs
@@ -7,3 +7,5 @@ export * as bundle from './bundle.js';
export * as graph from './graph.js';
export * as codecs from './codecs.js';
export * as literalInput from './literal-input.js';
+
+export { editorFor } from './source-editor.js';
diff --git a/ext/demo-site/test/site.test.mjs b/ext/demo-site/test/site.test.mjs
@@ -20,8 +20,8 @@ test('editor preserves authoring, IO, package and immutable download controls',a
for(const id of ['source-editor','compile','stop','restore-source','download-bundle','package-version','program-hash','share','package-definition-search'])assert.ok(html.includes(`id="${id}"`),id);
assert.match(html,/Edits compile after a pause/);assert.match(html,/Stored definitions can be inspected without source/);
assert.doesNotMatch(html,/id="edit-source"|compile-consent|slow-compilation|uncapped|execution-limits/);
- const app=await read('src/app.ts');assert.match(app,/sourceEditor.classList.toggle\('modified', modified\)/);
- assert.match(app,/sourceEditor.value !== compiledSource/);
+ const app=await read('src/app.ts');assert.match(app,/sourceEditor.dom.classList.toggle\('modified', modified\)/);
+ assert.match(app,/sourceEditor.getSource\(\) !== compiledSource/);
assert.match(app,/data.hash !== hash/);
assert.match(app,/r\.name === name && r\.version === versionPicker\.value/);
});
diff --git a/ext/demo-site/test/source-probe-helpers.mjs b/ext/demo-site/test/source-probe-helpers.mjs
@@ -1,6 +1,9 @@
-// Real source edits and definition inspection; never emulate retired DOM controls.
+// Source edits and definition inspection through the mounted editor.
export const el=id=>document.getElementById(id);
-export const input=(id,value)=>{el(id).value=value;el(id).dispatchEvent(new Event('input'));};
+const {editorFor}=await import(new URL('./probe-api.js',document.querySelector('script[type=module][src]').src));
+export const sourceEditor=editorFor(el('source-editor'));
+globalThis.__sourceEditor=sourceEditor;
+export const input=(id,value)=>{if(id==='source-editor'){sourceEditor.replaceSource(value,true);return;}el(id).value=value;el(id).dispatchEvent(new Event('input'));};
export const change=(id,value)=>{el(id).value=value;el(id).dispatchEvent(new Event('change'));};
export const pause=ms=>new Promise(r=>setTimeout(r,ms));
export async function wait(check,label='page state'){
@@ -14,8 +17,9 @@ export const description=()=>card().querySelector('[role=status]').textContent;
export async function inspect(name,format='auto'){
const title=card().querySelector('.definition-card-controls strong');
if(card().hidden||title.textContent!==name||description().startsWith('Runtime stopped.')){
- const button=document.querySelector(`[aria-label="Inspect compiled definition ${name}"]`)
+ let button=document.querySelector(`[aria-label="Inspect compiled definition ${name}"]`)
??[...el('package-definition-list').querySelectorAll('button')].find(button=>button.textContent===name);
+ if(!button&&!sourceEditor.dom.hidden&&sourceEditor.revealDefinition(name)){await wait(()=>document.querySelector(`[aria-label="Inspect compiled definition ${name}"]`),'visible definition '+name);button=document.querySelector(`[aria-label="Inspect compiled definition ${name}"]`);}
if(!button)throw Error('Missing real definition '+name);button.click();await pause(0);
}
await wait(()=>!card().hidden&&!card().querySelector('select').disabled,'inspect '+name);
@@ -28,7 +32,7 @@ export async function evaluateSource(expression,format='number'){
??[...el('package-definition-list').querySelectorAll('button')].find(button=>button.textContent===expression));
if(/^[A-Za-z_][\w?]*$/.test(expression)&&direct)return inspect(expression,format);
if(el('source-editor').hidden)throw Error('Test must import source-free functions explicitly, not synthesize an evaluator');
- const source=el('source-editor').value.replace(/\n-- browser probe binding\nprobeResult =[\s\S]*$/,'');
+ const source=sourceEditor.getSource().replace(/\n-- browser probe binding\nprobeResult =[\s\S]*$/,'');
input('source-editor',source+'\n-- browser probe binding\nprobeResult = (\n'+expression.split('\n').map(line=>' '+line).join('\n')+'\n)');
await status('Compiled');return inspect('probeResult',format);
}
diff --git a/ext/demo-site/test/syntax-probe.mjs b/ext/demo-site/test/syntax-probe.mjs
@@ -1,64 +1,31 @@
-// Browser-only presentation checks: no evaluator/compiler substitution.
+// CodeMirror document, selection, highlighting and viewport checks.
+import {sourceEditor as editor,el,wait,status,pause} from './source-probe-helpers.mjs';
const assert=(ok,message)=>{if(!ok)throw Error(message);};
export async function syntaxProbe(){
- const source=document.getElementById('source-editor'), input=source;
- for(let i=0;input.disabled;i++){if(i>3600)throw Error('Source not editable for syntax checks');await new Promise(r=>setTimeout(r,25));}
- const wrapper=input.closest('.syntax-editor'), mirror=wrapper.querySelector('pre');
- assert(source.closest('.syntax-editor').querySelector('.syntax-definition'),'Loaded source declarations are highlighted');
- const sourceMirror=source.closest('.syntax-editor').querySelector('pre');
- await new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)));
- assert(Math.abs(sourceMirror.scrollHeight-source.scrollHeight)<=2,'Source mirror wrapping matches native editor: '+JSON.stringify({viewport:innerWidth,input:source.scrollHeight,mirror:sourceMirror.scrollHeight,width:source.clientWidth,mirrorWidth:sourceMirror.style.width,lineHeight:getComputedStyle(source).lineHeight}));
- // Real geometry catches inherited global button sizing and glyph/line-box
- // differences. The IDE harness runs this at 320, 390 and 1440 pixels.
- const checkTargets=()=>{
- const definitions=[...sourceMirror.querySelectorAll('.syntax-definition')];
- let visible=0;const controls=[];
- for(const button of source.closest('.syntax-editor').querySelectorAll('.definition-targets button')){
- if(button.hidden||button.disabled)continue;
- const name=button.getAttribute('aria-label').replace('Inspect compiled definition ','');
- const texts=[...definitions.find(span=>span.textContent===name)?.getClientRects()??[]];
- const control=button.getBoundingClientRect();
- const text=texts.find(text=>Math.abs(text.left-control.left)<1&&Math.abs(text.width-control.width)<1);
- assert(text,'Name target has declaration text: '+name);
- controls.push(control);
- assert(Math.abs(control.width-text.width)<=1,'Name target has precisely the identifier width');
- assert(control.height<=parseFloat(getComputedStyle(source).lineHeight)-2,'Definition control leaves space between adjacent lines');
- assert(Math.abs(control.top+control.height/2-text.top-text.height/2)<=1,'Definition control centered on '+name+' at '+innerWidth+'px: '+JSON.stringify({controlTop:control.top,controlHeight:control.height,textTop:text.top,textHeight:text.height}));
- visible++;
- }
- controls.sort((a,b)=>a.top-b.top);
- for(let i=1;i<controls.length;i++)assert(controls[i].top>=controls[i-1].bottom+1,'Sequential name targets do not overlap');
- assert(visible>0,'Visible definition controls tested');
- };
- const oldScroll=source.scrollTop;
- const firstDefinition=sourceMirror.querySelector('.syntax-definition').getClientRects()[0];
- source.scrollTop=Math.max(0,oldScroll+firstDefinition.top-source.getBoundingClientRect().top-48);source.dispatchEvent(new Event('scroll'));
- checkTargets();
- source.scrollTop=Math.min(source.scrollTop+96,source.scrollHeight-source.clientHeight);source.dispatchEvent(new Event('scroll'));
- checkTargets();
- source.scrollTop=oldScroll;source.dispatchEvent(new Event('scroll'));
- assert(document.querySelector('#source .syntax-definition'),'Read-only source gets the same tokens');
- assert(wrapper.querySelector('[aria-hidden=true]')&&input.tagName==='TEXTAREA','Decorative mirror leaves native accessible textarea intact');
- const saved=input.value;
- const set=value=>{input.value=value;input.dispatchEvent(new Event('input'));};
- const caret=position=>{input.focus();input.setSelectionRange(position,position);input.dispatchEvent(new Event('select'));};
+ for(let i=0;editor.isDisabled;i++){assert(i<3600,'Source editable');await pause(25);}
+ const initiallyPublished=el('status').textContent==='Ready';
+ const dom=editor.dom,saved=editor.getSource(),frame=()=>new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)));
+ assert(dom.querySelector('.syntax-definition'),'Loaded declarations highlighted');
+ assert(dom.querySelector('[contenteditable=true][aria-label]')&&!dom.querySelector('textarea,.syntax-viewport'),'Single accessible editing surface');
+ assert(document.querySelector('#source .syntax-definition'),'Read-only source shares tokens');
+ const set=value=>editor.replaceSource(value,true),caret=position=>editor.select(position);
set('let named x = [x (t)] in named "λ🙂["');
- assert(mirror.querySelector('.syntax-definition').textContent==='named','Local declaration color');
- assert(mirror.textContent===input.value,'Mirror preserves all source bytes');
- assert(getComputedStyle(mirror.querySelector('.syntax-definition')).color!==getComputedStyle(mirror.querySelector('.syntax-name')).color,'Definition names have a dedicated color');
- caret(input.value.indexOf('['));assert(mirror.querySelectorAll('.bracket-match').length===2,'Caret highlights bracket pair');
- caret(input.value.lastIndexOf('['));assert(!mirror.querySelector('.bracket-match'),'String brackets are ignored');
- input.setSelectionRange(0,4);input.dispatchEvent(new Event('select'));assert(!mirror.querySelector('.bracket-match'),'Range selections have no caret match');
- set('(t');caret(0);assert(mirror.querySelector('.bracket-unmatched'),'Unclosed delimiter marked without compiler interaction');
- set('<img src=x onerror="throw 1">');assert(!mirror.querySelector('img')&&mirror.textContent===input.value,'Source cannot become HTML');
- input.dispatchEvent(new CompositionEvent('compositionstart'));
- assert(wrapper.classList.contains('composing')&&getComputedStyle(wrapper.querySelector('.syntax-viewport')).visibility==='hidden','IME uses visible native text, not a duplicate mirror');
- set('"λ🙂"');input.dispatchEvent(new CompositionEvent('compositionend'));assert(!wrapper.classList.contains('composing'),'IME restores highlighting');
- set(Array(80).fill('"λ🙂" t (t t) '+ 'longIdentifier '.repeat(12)).join('\n')+'\n');
- await new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)));
- assert(Math.abs(mirror.scrollHeight-input.scrollHeight)<=2,'Wrapping and trailing-line heights match native textarea');
- input.scrollTop=300;input.dispatchEvent(new Event('scroll'));
- assert(mirror.style.transform.includes('-300px'),'Scrolling keeps decoration aligned');
- input.blur();set(saved);input.scrollTop=0;input.dispatchEvent(new Event('scroll'));
- for(let i=0;input.disabled;i++){if(i>3600)throw Error('Source restore did not finish');await new Promise(r=>setTimeout(r,25));}
+ assert(dom.querySelector('.syntax-definition').textContent==='named','Local declaration color');
+ assert(getComputedStyle(dom.querySelector('.syntax-definition')).color!==getComputedStyle(dom.querySelector('.syntax-name')).color,'Definition color');
+ caret(editor.getSource().indexOf('['));assert(dom.querySelectorAll('.bracket-match').length===2,'Bracket pair');
+ caret(editor.getSource().lastIndexOf('['));assert(!dom.querySelector('.bracket-match'),'String brackets ignored');
+ editor.select(0,4);assert(!dom.querySelector('.bracket-match'),'Range has no caret match');
+ set('(t');caret(0);assert(dom.querySelector('.bracket-unmatched'),'Unclosed delimiter');
+ set('<img src=x onerror="throw 1">');assert(!dom.querySelector('img')&&editor.getSource()==='<img src=x onerror="throw 1">','Source markup remains literal text');
+ dom.dispatchEvent(new CompositionEvent('compositionstart'));
+ assert(dom.classList.contains('composing'),'Composition lifecycle observed');
+ set('"λ🙂"');dom.dispatchEvent(new CompositionEvent('compositionend'));assert(!dom.classList.contains('composing'),'Composition lifecycle ends');
+ const large=Array.from({length:1000},(_,i)=>`x${i} = ${i}`).join('\n')+'\n';set(large);await frame();
+ assert(editor.getSource()===large&&dom.querySelectorAll('.cm-line').length<1000,'Virtualization preserves complete document and trailing newline');
+ editor.select(large.length);await frame();assert(editor.getSelection().to===large.length,'Selection uses canonical UTF-16 offsets beyond viewport');
+ set(saved);editor.view.contentDOM.blur();editor.view.scrollDOM.scrollTop=0;
+ await pause(0);await wait(()=>['Compiled','Ready'].includes(el('status').textContent)&&!editor.isDisabled,'source restoration');
+ // A slow engine can finish a compilation during the rendering stress check.
+ // Restore the original published session after that compilation completes.
+ if(initiallyPublished&&el('status').textContent==='Compiled'){el('restore-source').click();await status('Ready');}
}
diff --git a/flake.nix b/flake.nix
@@ -168,13 +168,15 @@
'';
};
+ siteJavaScript = import ./ext/demo-site/javascript.nix { inherit pkgs; };
+
tricuWasmTests = pkgs.runCommand "tricu-wasm-tests" {
nativeBuildInputs = [ pkgs.nodejs pkgs.typescript ];
} ''
cp -r ${tricuSource} source
chmod -R u+w source
cd source
- tsc -p ext/demo-site/tsconfig.json
+ cp -r ${siteJavaScript}/. ext/demo-site/dist/
timeout 120 node ext/wasm/check.mjs ${tricuWasm}/lib/arboricx.wasm
timeout 120 node ext/wasm/backend-check.mjs ${tricuWasm}/lib/arboricx.wasm
mkdir -p $out
@@ -188,7 +190,7 @@
cp -r ${tricuSource} source
chmod -R u+w source
cd source
- tsc -p ext/demo-site/tsconfig.json
+ cp -r ${siteJavaScript}/. ext/demo-site/dist/
timeout 240 node ext/wasm/browser.mjs ${tricuWasm}/lib/arboricx.wasm chromium $out/report.json
'';
@@ -198,7 +200,7 @@
cp -r ${tricuSource} source
chmod -R u+w source
cd source
- tsc -p ext/demo-site/tsconfig.json
+ cp -r ${siteJavaScript}/. ext/demo-site/dist/
mkdir -p $out
node ext/wasm/compare.mjs ${tricuWasm}/lib/arboricx.wasm $out/report.json
node ext/wasm/preview-compare.mjs ${tricuWasm}/lib/arboricx.wasm $out/preview-report.json
@@ -458,6 +460,7 @@
-i${./src} -outputdir "$TMPDIR/objects" ${./test/InspectorOracle.hs} \
-o $out/bin/inspector-oracle
'';
+ packages.arboricxSiteJavaScript = siteJavaScript;
packages.arboricxArtwork = import ./ext/demo-site/artwork.nix { inherit pkgs; };
packages.arboricxWebkitCheck = import ./ext/demo-site/webkit.nix { inherit pkgs; };
packages.arboricxSite = siteRelease.arboricxSite;