From e092cb029c3885c8ffc9b1036de4c742dca79c21 Mon Sep 17 00:00:00 2001 From: Alex Maldonado Date: Thu, 12 Nov 2026 22:24:02 -0500 Subject: [PATCH] Initial commit --- .editorconfig | 100 + .gitattributes | 2 + .gitea/workflows/deploy.yml | 108 + .gitignore | 17 + .gitmodules | 4 + AGENTS.md | 57 + CHANGELOG.md | 52 + CITATION.cff | 21 + CODE_OF_CONDUCT.md | 84 + CONTRIBUTING.md | 34 + LICENSE.md | 167 + NOTICE.md | 16 + README.md | 97 + SECURITY.md | 29 + THIRD_PARTY.md | 82 + core | 1 + docs/Caddyfile | 76 + docs/app.md | 234 + docs/deploy.md | 67 + fonts/IBMPlexMono-Italic.woff2 | Bin 0 -> 50224 bytes fonts/IBMPlexMono-Regular.woff2 | Bin 0 -> 45640 bytes fonts/IBMPlexMono-SemiBold.woff2 | Bin 0 -> 47016 bytes fonts/IBMPlexSans-Bold.woff2 | Bin 0 -> 63012 bytes fonts/IBMPlexSans-Medium.woff2 | Bin 0 -> 66740 bytes fonts/IBMPlexSans-Regular.woff2 | Bin 0 -> 63020 bytes fonts/IBMPlexSans-SemiBold.woff2 | Bin 0 -> 67060 bytes fonts/LICENSE.txt | 93 + fonts/README.md | 28 + fonts/plex.css | 8 + index.html | 37 + package-lock.json | 33 + package.json | 24 + pixi.lock | 1413 ++++++ pixi.toml | 53 + quarto/.gitignore | 3 + quarto/README.md | 243 + quarto/_extensions/pplus/_extension.yml | 7 + quarto/_extensions/pplus/course/asm86.css | 2773 +++++++++++ quarto/_extensions/pplus/course/kit.css | 302 ++ quarto/_extensions/pplus/course/tokens.css | 99 + quarto/_extensions/pplus/pplus-hw.css | 119 + quarto/_extensions/pplus/pplus-views.css | 810 +++ quarto/_extensions/pplus/pplus.css | 234 + quarto/_extensions/pplus/pplus.js | 312 ++ quarto/_extensions/pplus/pplus.lua | 781 +++ quarto/_extensions/pplus/render.mjs | 91 + quarto/_extensions/pplus/syntax/lingo.xml | 155 + quarto/_extensions/pplus/syntax/mojo.xml | 310 ++ quarto/_extensions/pplus/syntax/pseudo.xml | 238 + quarto/_quarto.yml | 35 + quarto/example/index.qmd | 143 + quarto/example/live.qmd | 68 + quarto/example/machine.qmd | 77 + quarto/example/programs/binary-search.pseudo | 24 + quarto/example/programs/cell.asm | 9 + quarto/example/programs/cell.setup | 5 + quarto/example/programs/count-base.lingo | 7 + quarto/example/programs/count-base.mojo | 14 + quarto/example/programs/count-base.pseudo | 26 + quarto/example/programs/count-base.speco | 4 + quarto/example/programs/five-bugs.pseudo | 15 + quarto/example/programs/lifecycle.mojo | 38 + .../example/programs/match-off-by-one.pseudo | 33 + quarto/example/programs/mean.tex | 3 + quarto/example/programs/two-pointers.asm | 27 + quarto/example/programs/two-pointers.setup | 6 + scratch/.gitignore | 2 + scripts/assemble-page.mjs | 69 + scripts/assemble.sh | 27 + scripts/build-info.mjs | 46 + scripts/caddy-check.mjs | 75 + scripts/check-pages.mjs | 181 + scripts/deploy.sh | 57 + scripts/package.py | 51 + scripts/quarto-css.mjs | 163 + scripts/quarto-engine.mjs | 55 + scripts/quarto-export.mjs | 48 + scripts/release.mjs | 388 ++ scripts/vendor/build.mjs | 17 + scripts/vendor/codemirror.sh | 47 + scripts/vendor/entry.ts | 8 + scripts/vendor/relink.mjs | 26 + scripts/vendor/tsconfig.cm.json | 64 + src/core/areas.ts | 132 + src/core/catalog.ts | 33 + src/core/compiles.ts | 120 + src/core/csv.ts | 33 + src/core/guard.ts | 77 + src/core/hardware.ts | 279 ++ src/core/inputnote.ts | 76 + src/core/library.ts | 56 + src/core/prefs.ts | 65 + src/core/provenance.ts | 16 + src/core/session.ts | 458 ++ src/core/site.ts | 47 + src/core/state.ts | 433 ++ src/core/versions.ts | 222 + src/main.ts | 170 + src/quarto/dom.ts | 353 ++ src/quarto/machine.ts | 196 + src/quarto/program.ts | 73 + src/quarto/render.ts | 512 ++ src/quarto/shortcodes.ts | 150 + src/ui/consent.ts | 38 + src/ui/dom.ts | 62 + src/ui/editor.ts | 422 ++ src/ui/embed.ts | 230 + src/ui/footer.ts | 40 + src/ui/home.ts | 325 ++ src/ui/hw/board.ts | 331 ++ src/ui/hw/lines.ts | 51 + src/ui/library.ts | 121 + src/ui/minirun.ts | 117 + src/ui/nav.ts | 22 + src/ui/notice.ts | 22 + src/ui/provenance.ts | 45 + src/ui/quarto.ts | 391 ++ src/ui/reference.ts | 50 + src/ui/shell.ts | 1059 ++++ src/ui/splitter.ts | 40 + src/ui/stepkinds.ts | 38 + src/ui/theme.ts | 71 + src/ui/tooltip.ts | 28 + src/ui/views/compiler.ts | 265 + src/ui/views/lifetimes.ts | 77 + src/ui/views/panels.ts | 179 + src/ui/views/practices.ts | 45 + src/ui/views/run.ts | 208 + src/ui/views/tests.ts | 151 + src/ui/views/trace.ts | 538 ++ src/ui/views/viz.ts | 861 ++++ src/vendor/CODEMIRROR-LICENSE | 21 + .../cm-types/commands/src/commands.d.ts | 98 + src/vendor/cm-types/commands/src/comment.d.ts | 16 + src/vendor/cm-types/commands/src/history.d.ts | 19 + src/vendor/cm-types/commands/src/index.d.ts | 3 + src/vendor/cm-types/common/src/index.d.ts | 3 + src/vendor/cm-types/common/src/mix.d.ts | 14 + src/vendor/cm-types/common/src/parse.d.ts | 48 + src/vendor/cm-types/common/src/tree.d.ts | 282 ++ src/vendor/cm-types/crelt/index.d.ts | 4 + .../find-cluster-break/src/index.d.ts | 15 + .../cm-types/highlight/src/highlight.d.ts | 116 + src/vendor/cm-types/language/src/fold.d.ts | 57 + .../cm-types/language/src/highlight.d.ts | 27 + src/vendor/cm-types/language/src/indent.d.ts | 48 + src/vendor/cm-types/language/src/index.d.ts | 8 + src/vendor/cm-types/language/src/isolate.d.ts | 4 + .../cm-types/language/src/language.d.ts | 116 + .../cm-types/language/src/matchbrackets.d.ts | 23 + .../cm-types/language/src/stream-parser.d.ts | 25 + .../cm-types/language/src/stringstream.d.ts | 25 + src/vendor/cm-types/lr/src/constants.d.ts | 45 + src/vendor/cm-types/lr/src/decode.d.ts | 5 + src/vendor/cm-types/lr/src/index.d.ts | 3 + src/vendor/cm-types/lr/src/parse.d.ts | 110 + src/vendor/cm-types/lr/src/stack.d.ts | 38 + src/vendor/cm-types/lr/src/token.d.ts | 46 + src/vendor/cm-types/search/src/cursor.d.ts | 28 + src/vendor/cm-types/search/src/goto-line.d.ts | 2 + src/vendor/cm-types/search/src/index.d.ts | 5 + src/vendor/cm-types/search/src/regexp.d.ts | 35 + src/vendor/cm-types/search/src/search.d.ts | 54 + .../cm-types/search/src/selection-match.d.ts | 10 + src/vendor/cm-types/state/src/change.d.ts | 42 + src/vendor/cm-types/state/src/char.d.ts | 4 + .../cm-types/state/src/charcategory.d.ts | 6 + src/vendor/cm-types/state/src/column.d.ts | 2 + src/vendor/cm-types/state/src/config.d.ts | 4 + src/vendor/cm-types/state/src/extension.d.ts | 18 + src/vendor/cm-types/state/src/facet.d.ts | 115 + src/vendor/cm-types/state/src/index.d.ts | 12 + src/vendor/cm-types/state/src/rangeset.d.ts | 73 + src/vendor/cm-types/state/src/selection.d.ts | 36 + src/vendor/cm-types/state/src/state.d.ts | 67 + src/vendor/cm-types/state/src/text.d.ts | 33 + .../cm-types/state/src/transaction.d.ts | 65 + .../cm-types/style-mod/src/style-mod.d.ts | 16 + src/vendor/cm-types/view/src/active-line.d.ts | 2 + src/vendor/cm-types/view/src/attributes.d.ts | 9 + src/vendor/cm-types/view/src/bidi.d.ts | 23 + src/vendor/cm-types/view/src/browser.d.ts | 19 + src/vendor/cm-types/view/src/buildtile.d.ts | 95 + src/vendor/cm-types/view/src/cursor.d.ts | 26 + src/vendor/cm-types/view/src/decoration.d.ts | 104 + src/vendor/cm-types/view/src/dialog.d.ts | 20 + src/vendor/cm-types/view/src/docview.d.ts | 67 + src/vendor/cm-types/view/src/dom.d.ts | 68 + src/vendor/cm-types/view/src/domchange.d.ts | 27 + src/vendor/cm-types/view/src/domobserver.d.ts | 109 + src/vendor/cm-types/view/src/domreader.d.ts | 22 + .../cm-types/view/src/draw-selection.d.ts | 9 + src/vendor/cm-types/view/src/dropcursor.d.ts | 2 + src/vendor/cm-types/view/src/editorview.d.ts | 185 + src/vendor/cm-types/view/src/extension.d.ts | 137 + src/vendor/cm-types/view/src/gutter.d.ts | 41 + src/vendor/cm-types/view/src/heightmap.d.ts | 71 + .../cm-types/view/src/highlight-space.d.ts | 3 + src/vendor/cm-types/view/src/index.d.ts | 22 + src/vendor/cm-types/view/src/input.d.ts | 94 + src/vendor/cm-types/view/src/keymap.d.ts | 17 + src/vendor/cm-types/view/src/layer.d.ts | 32 + .../cm-types/view/src/matchdecorator.d.ts | 19 + src/vendor/cm-types/view/src/panel.d.ts | 19 + src/vendor/cm-types/view/src/placeholder.d.ts | 3 + .../view/src/rectangular-selection.d.ts | 7 + .../cm-types/view/src/scrollpastend.d.ts | 2 + .../cm-types/view/src/special-chars.d.ts | 8 + src/vendor/cm-types/view/src/theme.d.ts | 15 + src/vendor/cm-types/view/src/tile.d.ts | 161 + src/vendor/cm-types/view/src/tooltip.d.ts | 45 + src/vendor/cm-types/view/src/viewstate.d.ts | 95 + src/vendor/cm-types/w3c-keyname/index.d.ts | 5 + src/vendor/codemirror.d.ts | 5 + src/vendor/codemirror.js | 68 + styles.css | 4348 +++++++++++++++++ styles/course/README.md | 26 + styles/course/asm86.css | 2773 +++++++++++ styles/course/bridge.css | 142 + styles/course/kit.css | 302 ++ styles/course/tokens.css | 99 + tests/a11y.test.mjs | 58 + tests/areas.test.mjs | 153 + tests/badges.test.mjs | 167 + tests/bridge.test.mjs | 134 + tests/chain.test.mjs | 84 + tests/copy.test.mjs | 125 + tests/course-css.test.mjs | 29 + tests/csp.test.mjs | 60 + tests/editor.test.mjs | 33 + tests/hardening.test.mjs | 234 + tests/hardware.test.mjs | 235 + tests/inputnote.test.mjs | 71 + tests/library.test.mjs | 59 + tests/load.test.mjs | 62 + tests/mojo.test.mjs | 118 + tests/narrow.test.mjs | 37 + tests/practices-switch.test.mjs | 85 + tests/quarto-gallery.test.mjs | 48 + tests/quarto-render.test.mjs | 222 + tests/quarto.test.mjs | 302 ++ tests/quarto/harness.lua | 36 + tests/services.test.mjs | 26 + tests/site-data.test.mjs | 124 + tests/spdx.test.mjs | 38 + tests/state.test.mjs | 95 + tests/sync-hub.test.mjs | 96 + tests/tasks.test.mjs | 108 + tests/third-party.test.mjs | 72 + tests/trust.test.mjs | 73 + tests/versions.test.mjs | 231 + tsconfig.json | 30 + 252 files changed, 35037 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitattributes create mode 100644 .gitea/workflows/deploy.yml create mode 100644 .gitignore create mode 100644 .gitmodules create mode 100644 AGENTS.md create mode 100644 CHANGELOG.md create mode 100644 CITATION.cff create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE.md create mode 100644 NOTICE.md create mode 100644 README.md create mode 100644 SECURITY.md create mode 100644 THIRD_PARTY.md create mode 160000 core create mode 100644 docs/Caddyfile create mode 100644 docs/app.md create mode 100644 docs/deploy.md create mode 100644 fonts/IBMPlexMono-Italic.woff2 create mode 100644 fonts/IBMPlexMono-Regular.woff2 create mode 100644 fonts/IBMPlexMono-SemiBold.woff2 create mode 100644 fonts/IBMPlexSans-Bold.woff2 create mode 100644 fonts/IBMPlexSans-Medium.woff2 create mode 100644 fonts/IBMPlexSans-Regular.woff2 create mode 100644 fonts/IBMPlexSans-SemiBold.woff2 create mode 100755 fonts/LICENSE.txt create mode 100644 fonts/README.md create mode 100644 fonts/plex.css create mode 100644 index.html create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 pixi.lock create mode 100644 pixi.toml create mode 100644 quarto/.gitignore create mode 100644 quarto/README.md create mode 100644 quarto/_extensions/pplus/_extension.yml create mode 100644 quarto/_extensions/pplus/course/asm86.css create mode 100644 quarto/_extensions/pplus/course/kit.css create mode 100644 quarto/_extensions/pplus/course/tokens.css create mode 100644 quarto/_extensions/pplus/pplus-hw.css create mode 100644 quarto/_extensions/pplus/pplus-views.css create mode 100644 quarto/_extensions/pplus/pplus.css create mode 100644 quarto/_extensions/pplus/pplus.js create mode 100644 quarto/_extensions/pplus/pplus.lua create mode 100644 quarto/_extensions/pplus/render.mjs create mode 100644 quarto/_extensions/pplus/syntax/lingo.xml create mode 100644 quarto/_extensions/pplus/syntax/mojo.xml create mode 100644 quarto/_extensions/pplus/syntax/pseudo.xml create mode 100644 quarto/_quarto.yml create mode 100644 quarto/example/index.qmd create mode 100644 quarto/example/live.qmd create mode 100644 quarto/example/machine.qmd create mode 100644 quarto/example/programs/binary-search.pseudo create mode 100644 quarto/example/programs/cell.asm create mode 100644 quarto/example/programs/cell.setup create mode 100644 quarto/example/programs/count-base.lingo create mode 100644 quarto/example/programs/count-base.mojo create mode 100644 quarto/example/programs/count-base.pseudo create mode 100644 quarto/example/programs/count-base.speco create mode 100644 quarto/example/programs/five-bugs.pseudo create mode 100644 quarto/example/programs/lifecycle.mojo create mode 100644 quarto/example/programs/match-off-by-one.pseudo create mode 100644 quarto/example/programs/mean.tex create mode 100644 quarto/example/programs/two-pointers.asm create mode 100644 quarto/example/programs/two-pointers.setup create mode 100644 scratch/.gitignore create mode 100644 scripts/assemble-page.mjs create mode 100755 scripts/assemble.sh create mode 100644 scripts/build-info.mjs create mode 100644 scripts/caddy-check.mjs create mode 100644 scripts/check-pages.mjs create mode 100755 scripts/deploy.sh create mode 100644 scripts/package.py create mode 100644 scripts/quarto-css.mjs create mode 100644 scripts/quarto-engine.mjs create mode 100644 scripts/quarto-export.mjs create mode 100644 scripts/release.mjs create mode 100644 scripts/vendor/build.mjs create mode 100755 scripts/vendor/codemirror.sh create mode 100644 scripts/vendor/entry.ts create mode 100644 scripts/vendor/relink.mjs create mode 100644 scripts/vendor/tsconfig.cm.json create mode 100644 src/core/areas.ts create mode 100644 src/core/catalog.ts create mode 100644 src/core/compiles.ts create mode 100644 src/core/csv.ts create mode 100644 src/core/guard.ts create mode 100644 src/core/hardware.ts create mode 100644 src/core/inputnote.ts create mode 100644 src/core/library.ts create mode 100644 src/core/prefs.ts create mode 100644 src/core/provenance.ts create mode 100644 src/core/session.ts create mode 100644 src/core/site.ts create mode 100644 src/core/state.ts create mode 100644 src/core/versions.ts create mode 100644 src/main.ts create mode 100644 src/quarto/dom.ts create mode 100644 src/quarto/machine.ts create mode 100644 src/quarto/program.ts create mode 100644 src/quarto/render.ts create mode 100644 src/quarto/shortcodes.ts create mode 100644 src/ui/consent.ts create mode 100644 src/ui/dom.ts create mode 100644 src/ui/editor.ts create mode 100644 src/ui/embed.ts create mode 100644 src/ui/footer.ts create mode 100644 src/ui/home.ts create mode 100644 src/ui/hw/board.ts create mode 100644 src/ui/hw/lines.ts create mode 100644 src/ui/library.ts create mode 100644 src/ui/minirun.ts create mode 100644 src/ui/nav.ts create mode 100644 src/ui/notice.ts create mode 100644 src/ui/provenance.ts create mode 100644 src/ui/quarto.ts create mode 100644 src/ui/reference.ts create mode 100644 src/ui/shell.ts create mode 100644 src/ui/splitter.ts create mode 100644 src/ui/stepkinds.ts create mode 100644 src/ui/theme.ts create mode 100644 src/ui/tooltip.ts create mode 100644 src/ui/views/compiler.ts create mode 100644 src/ui/views/lifetimes.ts create mode 100644 src/ui/views/panels.ts create mode 100644 src/ui/views/practices.ts create mode 100644 src/ui/views/run.ts create mode 100644 src/ui/views/tests.ts create mode 100644 src/ui/views/trace.ts create mode 100644 src/ui/views/viz.ts create mode 100644 src/vendor/CODEMIRROR-LICENSE create mode 100644 src/vendor/cm-types/commands/src/commands.d.ts create mode 100644 src/vendor/cm-types/commands/src/comment.d.ts create mode 100644 src/vendor/cm-types/commands/src/history.d.ts create mode 100644 src/vendor/cm-types/commands/src/index.d.ts create mode 100644 src/vendor/cm-types/common/src/index.d.ts create mode 100644 src/vendor/cm-types/common/src/mix.d.ts create mode 100644 src/vendor/cm-types/common/src/parse.d.ts create mode 100644 src/vendor/cm-types/common/src/tree.d.ts create mode 100644 src/vendor/cm-types/crelt/index.d.ts create mode 100644 src/vendor/cm-types/find-cluster-break/src/index.d.ts create mode 100644 src/vendor/cm-types/highlight/src/highlight.d.ts create mode 100644 src/vendor/cm-types/language/src/fold.d.ts create mode 100644 src/vendor/cm-types/language/src/highlight.d.ts create mode 100644 src/vendor/cm-types/language/src/indent.d.ts create mode 100644 src/vendor/cm-types/language/src/index.d.ts create mode 100644 src/vendor/cm-types/language/src/isolate.d.ts create mode 100644 src/vendor/cm-types/language/src/language.d.ts create mode 100644 src/vendor/cm-types/language/src/matchbrackets.d.ts create mode 100644 src/vendor/cm-types/language/src/stream-parser.d.ts create mode 100644 src/vendor/cm-types/language/src/stringstream.d.ts create mode 100644 src/vendor/cm-types/lr/src/constants.d.ts create mode 100644 src/vendor/cm-types/lr/src/decode.d.ts create mode 100644 src/vendor/cm-types/lr/src/index.d.ts create mode 100644 src/vendor/cm-types/lr/src/parse.d.ts create mode 100644 src/vendor/cm-types/lr/src/stack.d.ts create mode 100644 src/vendor/cm-types/lr/src/token.d.ts create mode 100644 src/vendor/cm-types/search/src/cursor.d.ts create mode 100644 src/vendor/cm-types/search/src/goto-line.d.ts create mode 100644 src/vendor/cm-types/search/src/index.d.ts create mode 100644 src/vendor/cm-types/search/src/regexp.d.ts create mode 100644 src/vendor/cm-types/search/src/search.d.ts create mode 100644 src/vendor/cm-types/search/src/selection-match.d.ts create mode 100644 src/vendor/cm-types/state/src/change.d.ts create mode 100644 src/vendor/cm-types/state/src/char.d.ts create mode 100644 src/vendor/cm-types/state/src/charcategory.d.ts create mode 100644 src/vendor/cm-types/state/src/column.d.ts create mode 100644 src/vendor/cm-types/state/src/config.d.ts create mode 100644 src/vendor/cm-types/state/src/extension.d.ts create mode 100644 src/vendor/cm-types/state/src/facet.d.ts create mode 100644 src/vendor/cm-types/state/src/index.d.ts create mode 100644 src/vendor/cm-types/state/src/rangeset.d.ts create mode 100644 src/vendor/cm-types/state/src/selection.d.ts create mode 100644 src/vendor/cm-types/state/src/state.d.ts create mode 100644 src/vendor/cm-types/state/src/text.d.ts create mode 100644 src/vendor/cm-types/state/src/transaction.d.ts create mode 100644 src/vendor/cm-types/style-mod/src/style-mod.d.ts create mode 100644 src/vendor/cm-types/view/src/active-line.d.ts create mode 100644 src/vendor/cm-types/view/src/attributes.d.ts create mode 100644 src/vendor/cm-types/view/src/bidi.d.ts create mode 100644 src/vendor/cm-types/view/src/browser.d.ts create mode 100644 src/vendor/cm-types/view/src/buildtile.d.ts create mode 100644 src/vendor/cm-types/view/src/cursor.d.ts create mode 100644 src/vendor/cm-types/view/src/decoration.d.ts create mode 100644 src/vendor/cm-types/view/src/dialog.d.ts create mode 100644 src/vendor/cm-types/view/src/docview.d.ts create mode 100644 src/vendor/cm-types/view/src/dom.d.ts create mode 100644 src/vendor/cm-types/view/src/domchange.d.ts create mode 100644 src/vendor/cm-types/view/src/domobserver.d.ts create mode 100644 src/vendor/cm-types/view/src/domreader.d.ts create mode 100644 src/vendor/cm-types/view/src/draw-selection.d.ts create mode 100644 src/vendor/cm-types/view/src/dropcursor.d.ts create mode 100644 src/vendor/cm-types/view/src/editorview.d.ts create mode 100644 src/vendor/cm-types/view/src/extension.d.ts create mode 100644 src/vendor/cm-types/view/src/gutter.d.ts create mode 100644 src/vendor/cm-types/view/src/heightmap.d.ts create mode 100644 src/vendor/cm-types/view/src/highlight-space.d.ts create mode 100644 src/vendor/cm-types/view/src/index.d.ts create mode 100644 src/vendor/cm-types/view/src/input.d.ts create mode 100644 src/vendor/cm-types/view/src/keymap.d.ts create mode 100644 src/vendor/cm-types/view/src/layer.d.ts create mode 100644 src/vendor/cm-types/view/src/matchdecorator.d.ts create mode 100644 src/vendor/cm-types/view/src/panel.d.ts create mode 100644 src/vendor/cm-types/view/src/placeholder.d.ts create mode 100644 src/vendor/cm-types/view/src/rectangular-selection.d.ts create mode 100644 src/vendor/cm-types/view/src/scrollpastend.d.ts create mode 100644 src/vendor/cm-types/view/src/special-chars.d.ts create mode 100644 src/vendor/cm-types/view/src/theme.d.ts create mode 100644 src/vendor/cm-types/view/src/tile.d.ts create mode 100644 src/vendor/cm-types/view/src/tooltip.d.ts create mode 100644 src/vendor/cm-types/view/src/viewstate.d.ts create mode 100644 src/vendor/cm-types/w3c-keyname/index.d.ts create mode 100644 src/vendor/codemirror.d.ts create mode 100644 src/vendor/codemirror.js create mode 100644 styles.css create mode 100644 styles/course/README.md create mode 100644 styles/course/asm86.css create mode 100644 styles/course/bridge.css create mode 100644 styles/course/kit.css create mode 100644 styles/course/tokens.css create mode 100644 tests/a11y.test.mjs create mode 100644 tests/areas.test.mjs create mode 100644 tests/badges.test.mjs create mode 100644 tests/bridge.test.mjs create mode 100644 tests/chain.test.mjs create mode 100644 tests/copy.test.mjs create mode 100644 tests/course-css.test.mjs create mode 100644 tests/csp.test.mjs create mode 100644 tests/editor.test.mjs create mode 100644 tests/hardening.test.mjs create mode 100644 tests/hardware.test.mjs create mode 100644 tests/inputnote.test.mjs create mode 100644 tests/library.test.mjs create mode 100644 tests/load.test.mjs create mode 100644 tests/mojo.test.mjs create mode 100644 tests/narrow.test.mjs create mode 100644 tests/practices-switch.test.mjs create mode 100644 tests/quarto-gallery.test.mjs create mode 100644 tests/quarto-render.test.mjs create mode 100644 tests/quarto.test.mjs create mode 100644 tests/quarto/harness.lua create mode 100644 tests/services.test.mjs create mode 100644 tests/site-data.test.mjs create mode 100644 tests/spdx.test.mjs create mode 100644 tests/state.test.mjs create mode 100644 tests/sync-hub.test.mjs create mode 100644 tests/tasks.test.mjs create mode 100644 tests/third-party.test.mjs create mode 100644 tests/trust.test.mjs create mode 100644 tests/versions.test.mjs create mode 100644 tsconfig.json diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..0a4cb20 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,100 @@ +# EditorConfig: https://editorconfig.org +# In VS Code, install the "EditorConfig for VS Code" extension (EditorConfig.EditorConfig). + +root = true + +# Defaults for every file +[*] +charset = utf-8 +end_of_line = lf +indent_style = space +indent_size = 4 +insert_final_newline = true +trim_trailing_whitespace = true + +# Python +[*.{py,pyi}] +indent_size = 4 +max_line_length = 88 + +# Mojo (`mojo format` is Black-style, 88 columns; the fire emoji extension is also valid) +[*.{mojo,🔥}] +indent_size = 4 +max_line_length = 88 + +# Rust (rustfmt defaults: 4 spaces, 100 columns) +[*.rs] +indent_size = 4 +max_line_length = 100 + +# Cargo manifests and rustfmt config +[{Cargo.toml,Cargo.lock,rustfmt.toml,.rustfmt.toml,clippy.toml}] +indent_size = 4 + +# Mojo project manifest +[{mojoproject.toml,pixi.toml,pixi.lock}] +indent_size = 4 + +# YAML +[*.{yml,yaml}] +indent_size = 2 + +# JSON and friends +[*.{json,jsonc,json5}] +indent_size = 2 + +# Web +[*.{js,jsx,mjs,cjs,ts,tsx,css,scss,less,html,vue,svelte}] +indent_size = 2 + +# Config formats +[*.{toml,ini,cfg}] +indent_size = 4 + +[*.xml] +indent_size = 2 + +# Markdown: trailing spaces are significant (hard line breaks) +[*.{md,markdown}] +indent_size = 2 +trim_trailing_whitespace = false + +# typst +[*.{typ}] +indent_size = 4 +trim_trailing_whitespace = false + +# Shell scripts +[*.{sh,bash,zsh}] +indent_size = 2 + +# Makefiles require tabs +[{Makefile,makefile,*.mk}] +indent_style = tab + +# Go uses tabs +[*.go] +indent_style = tab + +# Windows-only scripts need CRLF +[*.{bat,cmd,ps1}] +end_of_line = crlf + +# Dockerfiles +[{Dockerfile,Dockerfile.*,*.dockerfile}] +indent_size = 4 + +# Terraform +[*.{tf,tfvars,hcl}] +indent_size = 2 + +# Don't touch these +[LICENSE*] +insert_final_newline = false + +[*.{diff,patch}] +trim_trailing_whitespace = false + +[*.min.{js,css}] +insert_final_newline = unset +trim_trailing_whitespace = unset diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..997504b --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# SCM syntax highlighting & preventing 3-way merges +pixi.lock merge=binary linguist-language=YAML linguist-generated=true -diff diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml new file mode 100644 index 0000000..42999b2 --- /dev/null +++ b/.gitea/workflows/deploy.yml @@ -0,0 +1,108 @@ +# Programming+ on Gitea Actions, with a runner that has no container image: the act_runner runs jobs directly on +# the droplet's shell ("host mode"). docs/deploy.md has the runner's setup, once. +# +# Every push and pull request runs `pixi run ci`, the same task a developer runs, in the environment pixi.lock pins +# (Node, Python, pandoc, Mojo): every test of the site (the Quarto ones fail, not skip, without pandoc), and core's +# tests and mojo-status-strict at the pinned commit. A push to main also checks the chain of pointers +# (`pixi run release-check`) and publishes the site to /srv/www/ as an atomic release (scripts/deploy.sh). +# +# On GitHub Actions the build and test steps run with one change, `runs-on: ubuntu-latest`; the publish step needs +# a host that serves /srv/www, so it is the droplet's. +# +# Repository -> Settings -> Actions -> Variables (all optional): +# SITE_SLUG the directory under /srv/www (defaults to the repository name) +# SITE_URL e.g. https://pplus.scient.ing, turns on the smoke test +name: Build, test, deploy +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +concurrency: + group: deploy-${{ github.ref }} + cancel-in-progress: true + +env: + # set by Gitea and GitHub Actions already; written here so the tests' "fail, not skip, under CI" never depends on it + CI: "true" + # the pixi that reads pixi.lock; when the host has another version, this one is fetched into the cache below + PIXI_VERSION: "0.83.0" + +jobs: + site: + # a pull request runs only from a branch of this repository: on a host runner a fork's workflow would run its + # own code on the droplet (docs/deploy.md in pplus-web). Drop this line for a runner that is a throwaway VM. + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository + # The host-mode label from the runner registration. Jobs run as the runner's user, in a fresh working directory. + runs-on: quarto-deploy + timeout-minutes: 60 + steps: + # core/ is pplus-core, a submodule pinned to one commit, and core/library/ is pplus-library, pinned by core; + # the job's token must be able to read both repositories while they are private + - uses: actions/checkout@v4 + with: + submodules: recursive + + # pixi: the host's when it is the pinned version, else the pinned release, fetched once into a cache directory + # the runner's user owns (no sudo), checked by SHA-256 + - name: pixi, pinned + shell: bash + run: | + set -euo pipefail + if command -v pixi >/dev/null && [ "$(pixi --version | cut -d' ' -f2)" = "$PIXI_VERSION" ]; then + echo "pixi $PIXI_VERSION is on the host: $(command -v pixi)"; exit 0 + fi + dir="${PPLUS_CI_CACHE:-$HOME/.cache/pplus-ci}/pixi-$PIXI_VERSION" + if [ ! -x "$dir/pixi" ]; then + case "$(uname -s)-$(uname -m)" in + Linux-x86_64) asset=pixi-x86_64-unknown-linux-musl.tar.gz; sum=064f371e692aaa3400ac581c89da2843c91437f20c2d9155395a5d0037f33551 ;; + Linux-aarch64) asset=pixi-aarch64-unknown-linux-musl.tar.gz; sum=d08403d8f048626ec93ba7b7c56e3b747a5f3a95c4e6e0c815ceb264f5f0b9ce ;; + *) echo "no pinned pixi for $(uname -sm)" >&2; exit 1 ;; + esac + tmp="$(mktemp -d)" + curl -fsSL --retry 3 -o "$tmp/$asset" "https://github.com/prefix-dev/pixi/releases/download/v$PIXI_VERSION/$asset" + echo "$sum $tmp/$asset" | sha256sum -c - + mkdir -p "$dir" && tar -xzf "$tmp/$asset" -C "$dir" pixi && rm -rf "$tmp" + fi + echo "$dir" >> "$GITHUB_PATH" + "$dir/pixi" --version + + - name: The pinned environment, exactly as pixi.lock has it + run: pixi install --locked + + # every test of the site; core's tests and mojo-status-strict at the pinned commit (pixi.toml) + - name: pixi run ci + run: pixi run ci + + # each pointer on its pushed branch, the generated files current, Mojo pinned alike (scripts/release.mjs); + # a pointer it cannot check (a private remote the job cannot ask) is reported, not failed + - name: The chain of pointers + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + run: pixi run release-check + + - name: Assemble the site + run: scripts/assemble.sh + env: + GITHUB_SHA: ${{ github.sha }} + + - name: Publish to /srv/www + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + env: + SLUG: ${{ vars.SITE_SLUG || github.event.repository.name }} + GITHUB_SHA: ${{ github.sha }} + run: scripts/deploy.sh "$SLUG" + + - name: Smoke test + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && vars.SITE_URL != '' + shell: bash + env: + SITE_URL: ${{ vars.SITE_URL }} + GITHUB_SHA: ${{ github.sha }} + run: | + sleep 2 + live=$(curl -fsS "$SITE_URL/VERSION") + case "$live" in + "${GITHUB_SHA:0:12}"*) echo "live site is at $live" ;; + *) echo "live site reports '$live', expected ${GITHUB_SHA:0:12}" >&2; exit 1 ;; + esac diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..50a7c3d --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +site/ +node_modules/ +.DS_Store +dist/ +patches/ +package/ +# pixi environments +.pixi/* +!.pixi/config.toml + +# Python +__pycache__/ +*.pyc +# the Quarto example site's output and Quarto's own state +quarto/_site/ +quarto/.quarto/ +quarto/_extensions/pplus/engine/ diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..e506060 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,4 @@ +[submodule "core"] + path = core + url = https://git.scient.ing/pplus/pplus-core.git + branch = main diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..2741e3a --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,57 @@ +# AGENTS.md + +Instructions for coding agents (and people) changing Programming+. Read this first, then the [README](README.md) for what the app is and where things are. When this file and a task's instructions disagree, the task wins; say so in your summary. + +## Build, test, and the gate + +The engine core (the languages, translators, Mojo checker and interpreter, prover, fuzzer, machine model and the Mojo corpus) is **pplus-core**, the git submodule `core/`, with its own rules in [core/AGENTS.md](core/AGENTS.md). This file is for the site. + +```bash +pixi run test # build core, then the site, then every test of the site +pixi run core-test # core's own tests, at the pinned commit +``` + +Without pixi (a sandbox with only Node and Python): + +```bash +npm install && npm test +(cd core && node --test tests/*.test.mjs && python3 scripts/mojo/corpus.py status --strict) +``` + +**Finish every change with the gate green**, both commands. The baseline passes completely; there is no known failure to work around. If a test fails, fix the cause or stop and report it. Do not skip, loosen, or delete a test to get green. + +The site's suite takes under a minute. While iterating, build and run one file: `npm run build && node --test tests/state.test.mjs`. + +## Hard rules + +1. **A change to what programs mean belongs in core.** A translator, the checker, the interpreter, the prover, the fuzzer, the machine model, the catalog's problems, the Mojo corpus: change them in pplus-core under its rules (its own commit, its own gate), then move the `core` pointer here in a commit that says what it brings. Never edit `core/` from a site change without that. The site imports core only as `#core/.js` (the import map in `index.html`, `imports` in `package.json`), from its built `core/dist/`. +2. **Do not edit generated files by hand.** `quarto/_extensions/pplus/pplus-views.css` comes from `styles.css`, `pplus-hw.css` and `course/*.css` beside it from `styles/course/`, and `syntax/mojo.xml` from core's `core/library/syntax/mojo.xml` (`pixi run quarto-css`; a test fails while they are out of date, so run it after changing a rule the views use). Core's generated files are listed in its AGENTS.md. +3. **Never claim Mojo compiles, runs, or prints something without the real compiler's answer.** Mojo is pinned to 1.2.0 by core. What the app shows about Mojo comes from core's checker and interpreter and from godbolt's answers (stored in `core/library/mojo/golden/`, or asked live by Compile & run); the site never invents a verdict, and every Mojo construct written into the app must pass `checkMojo`. +4. **Never show "proved" for something that is not a proof.** The badges and verdicts are in [core/docs/trust.md](core/docs/trust.md); the site shows what core decided and does not soften or upgrade it. +5. **No new dependencies.** TypeScript is the only npm package. There is no bundler, no framework, and no npm runtime dependency: CodeMirror, the one library the page runs, is vendored as one built module (`src/vendor/`), rebuilt only by `scripts/vendor/codemirror.sh`. `tests/tasks.test.mjs` holds `package.json` to that. +6. **You have no network** in most sandboxes. Godbolt (Compile & run) needs one, and so do core's network tasks. Never fake their results; leave those steps to the owner and list them. +7. **Keep the workspace working while you change it.** Code panes are always the CodeMirror editor (`Editor` in `src/ui/editor.ts`, over the vendored `src/vendor/codemirror.js`), never a ``; + if (this.namespaceURI === SVG_NS && !this.childNodes.length) return open + '/>'; + return `${open}>${super.serialize()}`; + } +} +const BOOL_ATTR: Record = { hidden: true, open: true, disabled: true, readonly: true, checked: true, selected: true, multiple: true, required: true }; + +/* ---------- selectors ---------- */ + +type Matcher = (e: SElement) => boolean; +const compiled = new Map(); + +function compile(sel: string): Matcher { + const hit = compiled.get(sel); + if (hit) return hit; + const alts = sel.split(',').map((s) => s.trim()).filter(Boolean).map(descendant); + const m: Matcher = (e) => alts.some((a) => a(e)); + compiled.set(sel, m); + return m; +} + +/** `a b c`: c, inside a b, inside an a. */ +function descendant(s: string): Matcher { + if (/[>+~]/.test(s.replace(/\[[^\]]*\]/g, ''))) throw new Error(`the render document does not handle the selector "${s}" (only the descendant combinator)`); + const parts = s.split(/\s+(?![^\[]*\])/).filter(Boolean).map(compound); + const last = parts.pop()!; + return (e) => { + if (!last(e)) return false; + let k = parts.length - 1; + for (let a = e.parentElement; a && k >= 0; a = a.parentElement) if (parts[k](a)) k--; + return k < 0; + }; +} + +function compound(s: string): Matcher { + const tests: Matcher[] = []; + const re = /^([a-zA-Z][\w-]*|\*)|\.([\w-]+)|#([\w-]+)|\[([\w-]+)(?:([\^$*]?=)"?([^"\]]*)"?)?\]/g; + let m: RegExpExecArray | null; + let pos = 0; + while ((m = re.exec(s))) { + if (m.index !== pos) break; + pos = re.lastIndex; + const [, tag, cls, id, attr, op, val] = m; + if (tag && tag !== '*') tests.push((e) => e.localName.toLowerCase() === tag.toLowerCase()); + else if (cls) tests.push((e) => e.classList.contains(cls)); + else if (id) tests.push((e) => e.getAttribute('id') === id); + else if (attr) tests.push((e) => { + const v = e.getAttribute(attr); + if (v === null) return false; + if (!op) return true; + return op === '=' ? v === val : op === '^=' ? v.startsWith(val) : op === '$=' ? v.endsWith(val) : v.includes(val); + }); + } + if (pos !== s.length) throw new Error(`the render document does not handle the selector "${s}"`); + return (e) => tests.every((t) => t(e)); +} + +/* ---------- the document, and the globals ---------- */ + +export class SDocument extends SFragment { + readonly documentElement = new SElement('html'); + readonly head = new SElement('head'); + readonly body = new SElement('body'); + constructor() { super(); this.nodeType = 9; this.appendChild(this.documentElement); this.documentElement.append(this.head, this.body); } + createElement(tag: string): SElement { return new SElement(tag); } + createElementNS(ns: string | null, tag: string): SElement { return new SElement(tag, ns); } + createTextNode(s: string): SText { return new SText(String(s)); } + createComment(s: string): SComment { return new SComment(String(s)); } + createDocumentFragment(): SFragment { return new SFragment(); } + getElementById(id: string): SElement | null { return this.querySelector('#' + id); } + execCommand(): boolean { return false; } + get activeElement(): null { return null; } +} + +const queued: Array<() => void> = []; + +/** Run what the views put off to the next frame or a timer (a view that measures before drawing), until none is left. */ +export function flushQueued(rounds = 8): void { + for (let i = 0; i < rounds && queued.length; i++) for (const fn of queued.splice(0)) { try { fn(); } catch { /* a view's late refinement, not its output */ } } +} + +let installed: SDocument | null = null; + +/** + * Give this process a `document` (and the few other browser globals the views reach for). Does nothing where a + * real document exists, so the same render code runs in the app's gallery and under `quarto render`. + */ +export function installDocument(): boolean { + const g = globalThis as any; + if (g.document && !installed) return false; + if (installed) return true; + installed = new SDocument(); + const store = new Map(); + g.document = installed; + g.Node = SNode; g.Element = SElement; g.HTMLElement = SElement; g.SVGElement = SElement; g.Text = SText; g.DocumentFragment = SFragment; + g.localStorage ??= { getItem: (k: string) => store.get(k) ?? null, setItem: (k: string, v: string) => void store.set(k, String(v)), removeItem: (k: string) => void store.delete(k), clear: () => store.clear(), key: (i: number) => [...store.keys()][i] ?? null, get length() { return store.size; } }; + g.requestAnimationFrame ??= (fn: (t: number) => void) => { queued.push(() => fn(0)); return queued.length; }; + g.cancelAnimationFrame ??= () => { /* queued work runs at most once */ }; + g.ResizeObserver ??= class { observe() { /* no layout */ } unobserve() { /* no layout */ } disconnect() { /* no layout */ } }; + g.IntersectionObserver ??= class { observe() { /* no layout */ } unobserve() { /* no layout */ } disconnect() { /* no layout */ } }; + g.MutationObserver ??= class { observe() { /* nothing changes */ } disconnect() { /* nothing changes */ } takeRecords() { return []; } }; + g.getComputedStyle ??= () => ({ getPropertyValue: () => '' }); + g.matchMedia ??= () => ({ matches: false, addEventListener() { /* static */ }, removeEventListener() { /* static */ }, addListener() { /* static */ }, removeListener() { /* static */ } }); + // a window whose timers are queued with the animation frames: the render reads the views once, after flushQueued() + g.window ??= g; + if (g.window === g) { + g.innerWidth ??= 1200; g.innerHeight ??= 800; g.devicePixelRatio ??= 1; + g.addEventListener ??= () => { /* nothing fires */ }; g.removeEventListener ??= () => { /* nothing fires */ }; + g.location ??= { href: 'https://pplus.invalid/', hash: '', search: '', origin: 'https://pplus.invalid' }; + } + return true; +} + +/** The HTML of what a view built: an element's children, as markup. */ +export function htmlOf(node: unknown): string { + if (node instanceof SNode) return node.serialize(); + return (node as any).innerHTML as string; +} diff --git a/src/quarto/machine.ts b/src/quarto/machine.ts new file mode 100644 index 0000000..059e462 --- /dev/null +++ b/src/quarto/machine.ts @@ -0,0 +1,196 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +/** + * The machine, rendered with the page: the Hardware area's board views (registers, memory, the stack, the caches, + * virtual memory, the pipeline, the out-of-order core, the encoding...) over an x86-64 run, for the Quarto + * extension's `pplus-hw` shortcodes. + * + * The views are the course's own (src/engines/asm86/views.js and hwviews.js), mounted exactly as the board mounts + * them (`mountView`, `courseViews` in core/hardware.ts) and drawn at every step of the run. A page cannot run them, + * so each card keeps what it drew at each step: the distinct drawings once, and which one each step shows. pplus.js + * steps through them; render.mjs compresses them (they repeat from step to step, so deflate makes a run of a + * hundred steps a few kilobytes per card). The step the page opens on is in the markup itself, so the page reads, + * prints and works without script. + */ +import { el, add } from '../ui/dom.js'; +import type { Session } from '../core/session.js'; +import { BOARD_VIEWS, BOARD_PRESETS, boardFrame, boardView, courseViews, parseMachine, machineLabel, machineName, type BoardViewId } from '../core/hardware.js'; +import { mountView } from '../ui/hw/board.js'; +import { machineView } from '../ui/views/panels.js'; +import { highlighted, freeze } from './render.js'; + +/** + * The machine's views as the shortcodes name them: `pplus-hw-`. The name is the board's id, except where a + * shortcode of that name already means something else (the ALU is `bits` on the board, the whole core `machine`). + */ +export const HW_NAMES: Record = { + code: 'code', explain: 'explain', registers: 'registers', flags: 'flags', address: 'address', memory: 'memory', stack: 'stack', + dataflow: 'dataflow', alu: 'bits', branches: 'branches', vectors: 'vectors', + lines: 'lines', cache: 'cache', hierarchy: 'hierarchy', paging: 'paging', + pipeline: 'pipeline', uops: 'uops', timeline: 'timeline', bottleneck: 'bottleneck', counters: 'counters', + chip: 'machine', core: 'core', encoding: 'encoding', +}; + +/** The board's arrangements a page can ask for (`preset=`), without the Mojo one (the machine cards only). */ +export const HW_PRESETS = BOARD_PRESETS.filter((p) => p.id !== 'mojo').map((p) => ({ id: p.id, label: p.label, blurb: p.blurb, views: p.items.map((x) => x.id).filter((id) => boardView(id)!.needs === 'asm') })); + +/** A view by its shortcode name or its board id. */ +export function hwView(name: string): BoardViewId | null { + const n = name.trim().toLowerCase(); + if (HW_NAMES[n]) return HW_NAMES[n]; + const v = boardView(n); + return v && v.needs === 'asm' ? v.id : null; +} + +/** What pplus.js reads: for each card, its distinct drawings, and which one each step shows. */ +export interface HwData { + count: number; + t: number; + /** Per step: the line of the instruction about to run (`n`) and of the one that just ran (`l`), and that instruction's text. */ + steps: Array<{ n: number | null; l: number | null; x: string }>; + cards: Array<{ id: string; frames: string[]; at: number[] }>; + /** Steps drawn: every one, or every `stride`-th when the run is longer than `max`. */ + shown: number[]; +} + +export interface HwRequest { views?: string[]; preset?: string; t?: number; max?: number; listing?: boolean; stepper?: boolean } + +export function machineBoard(session: Session, req: HwRequest): { node: HTMLElement; markdown: string; warnings: string[]; data: HwData | null } { + const warnings: string[] = []; + session.state.lang = 'asm'; + // the views asked for, in order; unknown ones are reported, and paging turns virtual memory on + let ids: BoardViewId[] = []; + if (req.views?.length) { + for (const v of req.views) { const id = hwView(v); if (id) { if (!ids.includes(id)) ids.push(id); } else warnings.push(`hw: no machine view "${v}"; the views are ${Object.keys(HW_NAMES).join(', ')}`); } + } + if (!ids.length) ids = (HW_PRESETS.find((p) => p.id === req.preset) ?? HW_PRESETS[0]).views; + if (req.preset && !req.views?.length && !HW_PRESETS.some((p) => p.id === req.preset)) warnings.push(`hw: no preset "${req.preset}"; the presets are ${HW_PRESETS.map((p) => p.id).join(', ')}`); + if (ids.includes('paging') && !parseMachine(session.state.machine).paging) session.state.machine = machineName({ preset: parseMachine(session.state.machine).preset, paging: true }); + + const tr = session.trace(); + const trace = tr && tr.lang === 'asm' ? (tr.raw as any)?.trace : null; + if (!session.source('asm').trim()) { + const why = 'The machine views run an x86-64 file (asm=, with its setup=). For a Mojo program, `pixi run quarto-export` writes the compiler\'s x86-64 and setup beside the page.'; + return { node: el('div', {}, el('p', { class: 'pplus-err' }, why)), markdown: `*${why}*`, warnings: [...warnings, 'hw: no x86-64 file (asm=)'], data: null }; + } + if (!trace) { + const why = session.runError ?? session.diagnostics('asm').find((d) => d.severity === 'error')?.message ?? 'The x86-64 file does not assemble.'; + return { node: el('div', {}, el('p', { class: 'pplus-err' }, `It does not run: ${why}`)), markdown: `*It does not run: ${why}*`, warnings: [...warnings, `hw: ${why}`], data: null }; + } + + const machine = parseMachine(session.state.machine); + const count: number = trace.count; + const max = Math.max(10, Math.min(req.max ?? 400, 5000)); + const stride = Math.max(1, Math.ceil(count / max)); + const shown: number[] = []; + for (let t = 0; t <= count; t += stride) shown.push(t); + if (shown[shown.length - 1] !== count) shown.push(count); + const t0 = Math.max(0, Math.min(req.t ?? 0, count)); + // the step the page opens on is one of those drawn + const open = shown.reduce((best, t) => (Math.abs(t - t0) < Math.abs(best - t0) ? t : best), shown[0]); + const stepper = req.stepper !== false && count > 0; + + const lineOf = (instr: any) => (instr && typeof instr.lineNo === 'number' ? instr.lineNo + 1 : null); + const steps = shown.map((t) => { const f = boardFrame(trace, t); return { n: lineOf(f.next), l: lineOf(f.last?.instr), x: String(f.last?.instr?.text ?? '').trim().replace(/\s+/g, ' ') }; }); + + const cards: HwData['cards'] = []; + const grid = el('div', { class: 'pplus-hw-grid' }); + // the listing stands beside the cards (sticky while they scroll), unless the machine-code card is one of them + let listing: HTMLElement | null = null; + if (req.listing !== false && !ids.includes('code')) { + const code = highlighted(session.source('asm'), 'asm', { numbers: true }); + const at = steps[shown.indexOf(open)]; + for (const ln of [...code.querySelectorAll('.pplus-ln')]) { + const n = Number(ln.getAttribute('data-line')); + if (n === at.n) ln.classList.add('is-next'); + if (n === at.l) ln.classList.add('is-last'); + } + listing = el('section', { class: 'pplus-hw-card pplus-hw-listing', 'data-hw': 'listing' }, el('div', { class: 'pplus-hw-title' }, 'x86-64'), code); + } + for (const id of ids) { + const def = boardView(id)!; + const card = el('section', { class: `pplus-hw-card pplus-hw-${id}${def.wide ? ' is-wide' : ''}`, 'data-hw': id, title: def.blurb }); + add(grid, card); + if (id === 'counters') { + // the run's totals: the same at every step + const box = el('div', { class: 'view view-asm' }); + machineView(session, box); + freeze(box); + add(card, el('div', { class: 'pplus-hw-title' }, def.label), box); + continue; + } + const spec = id === 'lines' ? { name: 'lines', options: {} } : courseViews([{ id }], trace, machine)[0]; + if (!spec) continue; + const view = mountView(spec.name, trace, spec.options); + const frames: string[] = []; + const index = new Map(); + const at: number[] = []; + let first = ''; + for (const t of stepper ? shown : [open]) { + view.update(boardFrame(trace, t)); + const html = inert(view.node.outerHTML); + if (!index.has(html)) { index.set(html, frames.length); frames.push(html); } + at.push(index.get(html)!); + if (t === open) first = html; + } + if (view.node.classList.contains('has-failed')) warnings.push(`hw: the ${def.label} view failed on this run`); + const holder = el('div', { class: 'a86 board-a86', 'data-hw-frame': '' }); + // the drawing for the step the page opens on: the course view's own markup. In a browser (the gallery) it goes + // in directly; the small document has no parser, so there it is spliced into the serialized page (spliceFrames) + if (typeof DOMParser !== 'undefined') holder.innerHTML = first; + else (holder as any).__html = first; + add(card, holder); + cards.push({ id, frames, at }); + } + + const data: HwData = { count, t: open, steps, cards, shown }; + const btn = (go: string, label: string, title: string) => el('button', { type: 'button', class: 'pplus-btn', 'data-go': go, title, 'aria-label': title }, label); + const node = el('div', { 'data-count': String(count), 'data-t': String(open) }, + stepper ? el('div', { class: 'pplus-steps-bar' }, + el('span', { class: 'pplus-chip pplus-chip-asm' }, 'x86-64'), + btn('first', '⏮', 'First step'), btn('back', '◀', 'Back one step'), btn('next', '▶', 'One step'), btn('last', '⏭', 'Last step'), btn('play', 'Play', 'Play the run'), + el('input', { type: 'range', class: 'pplus-steps-slider', min: '0', max: String(shown.length - 1), value: String(shown.indexOf(open)), 'aria-label': 'step' }), + el('span', { class: 'pplus-steps-count' }, `${open} / ${count}`)) : null, + el('div', { class: 'pplus-hw-now' }, nowText(steps[shown.indexOf(open)], open), el('span', { class: 'pplus-muted pplus-hw-machine' }, ` · ${machineLabel(session.state.machine)} machine`)), + el('div', { class: `pplus-hw-body${listing ? ' has-listing' : ''}` }, listing, grid), + stride > 1 ? el('p', { class: 'pplus-note' }, `The run takes ${count} steps; every ${stride}${stride === 2 ? 'nd' : stride === 3 ? 'rd' : 'th'} is drawn (max="${max}").`) : null, + stepper ? el('script', { type: 'application/json', class: 'pplus-hw-data' }, JSON.stringify(data).replace(/]*>[\s\S]*?<\/button>/g, '').replace(/]*>[\s\S]*?<\/select>/g, '').replace(/]*>/g, ''); +} + +export const nowText = (s: { x: string } | undefined, t: number): string => (t === 0 ? 'Before the first instruction.' : `Step ${t}: ${s?.x ?? ''}`); + +/** Put each card's drawing for the opening step into the serialized markup (see machineBoard). */ +export function spliceFrames(html: string, node: HTMLElement): string { + const holders = [...node.querySelectorAll('[data-hw-frame]')]; + let i = 0; + return html.replace(/
<\/div>/g, (m) => { + const h = holders[i++] as any; + return h?.__html ? m.replace('>
', `>${h.__html}`) : m; + }); +} + +/** In a format other than HTML: the registers the run wrote, at the step shown, and what each view is. */ +function machineMarkdown(ids: BoardViewId[], trace: any, t: number): string { + const f = boardFrame(trace, t); + const regs = new Set(); + for (const s of trace.steps.slice(0, t)) for (const r of s.diff?.regs ?? []) regs.add(r.name); + const hex = (v: unknown) => { try { return '0x' + BigInt.asUintN(64, BigInt(v as any)).toString(16); } catch { return String(v); } }; + const rows = [...regs].map((r) => `| ${r} | ${hex(f.state.regs[r])} |`); + return [`*The machine at step ${t} of ${trace.count}${f.last ? `, after \`${String(f.last.instr.text).trim().replace(/\s+/g, ' ')}\`` : ''}.*`, '', + rows.length ? ['| register | value |', '|---|---|', ...rows].join('\n') : '', + '', `*Drawn in the HTML version of this page: ${ids.map((id) => boardView(id)!.label).join(', ')}.*`].join('\n'); +} + +export const HW_VIEW_LIST = BOARD_VIEWS.filter((v) => v.needs === 'asm'); diff --git a/src/quarto/program.ts b/src/quarto/program.ts new file mode 100644 index 0000000..52d9649 --- /dev/null +++ b/src/quarto/program.ts @@ -0,0 +1,73 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +/** + * A program file as a Quarto page keeps it beside the .qmd: which pane it fills, the header lines the page's + * checker reads (`// CALL:`, `// INPUT:`, `// EXPECT:` ...), and the text a reader is shown, without them. + * + * The rules are the shortcode's (quarto/_extensions/pplus/pplus.lua) and scripts/check-pages.mjs's: + * lingo, pseudo, speco `// KEY: value` anywhere in the file + * matho (.tex) `% KEY: value` + * Mojo the leading block of `# key: value` comments (mojo/local/'s corpus header, or + * `# EXPECT:` lines); a `# note:` further down belongs to the program + * DOM-free; tests/quarto-render.test.mjs checks it. + */ +import type { LangId } from '#core/common/types.js'; + +export interface ProgramHeader { + call?: string; + input: string[]; + expect: string[]; + errors?: number; + stops?: string; + questions: string[]; +} + +/** The pane a file fills, from its extension. */ +export function langOfFile(name: string): LangId | null { + const ext = /\.([a-z0-9]+)$/i.exec(name)?.[1]?.toLowerCase(); + switch (ext) { + case 'lingo': return 'lingo'; + case 'tex': case 'matho': return 'matho'; + case 'pseudo': return 'pseudo'; + case 'speco': return 'speco'; + case 'mojo': case '🔥': return 'mojo'; + case 'asm': case 's': return 'asm'; + default: return null; + } +} + +// `# expect-stdout:` is the corpus header's spelling of EXPECT (mojo/local/, mojo/stress/), so an exported program keeps its check +const HEADER = /^\s*(?:\/\/|%|#)\s*(CALL|INPUT|EXPECT|ERRORS|QUESTION|STOPS|expect-stdout):\s?(.*)$/; + +/** The header lines of a program file (the same lines scripts/check-pages.mjs reads). */ +export function programHeader(text: string): ProgramHeader { + const h: ProgramHeader = { input: [], expect: [], questions: [] }; + for (const line of text.split('\n')) { + const m = HEADER.exec(line); + if (!m) continue; + const v = m[2]; + if (m[1] === 'CALL') h.call = v.trim(); + else if (m[1] === 'INPUT') h.input.push(v); + else if (m[1] === 'EXPECT' || m[1] === 'expect-stdout') h.expect.push(v); + else if (m[1] === 'ERRORS') h.errors = Number(v); + else if (m[1] === 'QUESTION') h.questions.push(v.trim()); + else if (m[1] === 'STOPS') h.stops = v.trim(); + } + return h; +} + +/** The file as a page shows it and a pane holds it: the header lines removed, blank lines trimmed at both ends. */ +export function listingText(text: string, lang: LangId): string { + const out: string[] = []; + let head = lang === 'mojo'; + for (const line of text.replace(/\r\n?/g, '\n').split('\n')) { + if (head) { + if (/^#\s*[\w-]+:/.test(line)) continue; + if (!line.trim() && !out.length) continue; + head = false; + } + if (lang !== 'mojo' && /^\s*(?:\/\/|%)\s*[A-Z]+:/.test(line)) continue; + out.push(line); + } + return out.join('\n').replace(/^\n+/, '').replace(/\n+$/, ''); +} diff --git a/src/quarto/render.ts b/src/quarto/render.ts new file mode 100644 index 0000000..331022e --- /dev/null +++ b/src/quarto/render.ts @@ -0,0 +1,512 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +/** + * The static views of the Quarto extension: a program from the files beside a page, run by the app's own engines + * when the page is rendered, and drawn by the app's own views (src/ui/views/) as HTML that needs no iframe and no + * network. `quarto render` reaches this through quarto/_extensions/pplus/render.mjs, under the small document of + * ./dom.ts; the app's "With Quarto" gallery (src/ui/quarto.ts) calls it in the browser, with the real one, so the + * gallery shows exactly what a page gets. + * + * run what the program prints (and returns), checked against its EXPECT lines + * steps the listing with a stepper: every step, the line it ran, the values after it (pplus.js steps it) + * table the table of values: a column per step that changed something, a row per name + * flow the flowchart of the routine, shaded by how often each line ran + * data the data-flow graph of the routine + * life each Mojo value's lifetime: made, copied, moved, destroyed + * proof the claims of the speco (or the pseudo's ENSUREs), proved, broken or open + * tests the fuzzer's report for every routine + * check the checker's findings for each file, on its own lines + * translate the procedure in every notation the hub can write it in, Mojo generated from the pseudo + * machine the x86-64 run on the model machine: instructions, cycles, cache misses + * hw the Hardware area's board over an x86-64 run: registers, memory, caches, pipeline, the core..., + * steppable (./machine.ts) + * + * Every view returns HTML for an HTML page and Markdown for any other format (a PDF, a Word file), so a page + * renders everywhere; the Markdown says plainly what only the HTML can show. + */ +import { el, add } from '../ui/dom.js'; +import { Session } from '../core/session.js'; +import { emptyState, type PlayState } from '../core/state.js'; +import { LANG_NAMES, type LangId } from '#core/common/types.js'; +import { SERVICES } from '#core/services/index.js'; +import { SyncHub, mojoFromPseudo, LINKED } from '#core/sync/hub.js'; +import { runColumns, defaultFollow, runRows, valuesAt, type RunRow } from '#core/common/runview.js'; +import { familyOf } from '../ui/stepkinds.js'; +import { flowView, dataFlowView, traceTableView } from '../ui/views/viz.js'; +import { problemsView, proofView, machineView } from '../ui/views/panels.js'; +import { testsView } from '../ui/views/tests.js'; +import { lifetimesView } from '../ui/views/lifetimes.js'; +import { MOJO_VERSION } from '#core/mojo/generated/pin.js'; +import { listingText, programHeader, type ProgramHeader } from './program.js'; +import { machineBoard, spliceFrames } from './machine.js'; + +export const STATIC_VIEWS = ['run', 'steps', 'table', 'flow', 'data', 'life', 'proof', 'tests', 'check', 'translate', 'machine', 'hw'] as const; +export type StaticView = typeof STATIC_VIEWS[number]; +export const isStaticView = (v: unknown): v is StaticView => (STATIC_VIEWS as readonly string[]).includes(v as string); + +const PANES: LangId[] = ['lingo', 'matho', 'pseudo', 'speco', 'mojo', 'asm']; + +/** What a page asks for: one view of the program in `files` (each file's text as it is on disk, header and all). */ +export interface RenderRequest { + view: StaticView; + files: Partial>; + /** The pane the run reads (default: the first of lingo, matho, pseudo, mojo, asm given; speco runs as its pseudo). */ + lang?: LangId; + /** The call, and the lines INPUT reads; by default the files' own `// CALL:` and `// INPUT:` lines. */ + call?: string | null; + input?: string[]; + setup?: string; + machine?: string; + /** The step a stepper starts on, and where the flowchart and the table of values stop (default: the end). */ + t?: number; + title?: string; + /** translate: the notations to show (default: every one the procedure has, and Mojo). */ + to?: LangId[]; + /** steps: the most steps kept for the stepper (default 400). */ + max?: number; + /** steps, table: the variables to show, as written in the program (default: the routine that does the most work). */ + follow?: string[]; + /** hw: the machine views to show (their shortcode names or board ids), or a preset of the board (regs, caches, pipeline, chip). */ + hw?: string[]; + preset?: string; + /** hw: false leaves out the x86-64 listing; stepper false draws only the step `t`. */ + listing?: boolean; + stepper?: boolean; + /** A run of the Mojo file by a real compiler (render.mjs does it when `mojo` is on the PATH). */ + compiled?: { stdout: string; stderr: string; status: number | null; version: string } | null; +} + +export interface TranslatedPane { lang: LangId; label: string; text: string; authored: boolean; generated: boolean; note?: string; /** For a generated pane: the notation it was written from. */ from?: LangId } + +export interface RenderResult { + view: StaticView; + /** The language that ran or was drawn. */ + lang: LangId | null; + /** The view as an element of whichever document is installed, and as markup. */ + node: HTMLElement; + html: string; + markdown: string; + /** Things the author should know (stderr in `quarto render`): a run that does not print its EXPECT lines, a missing piece. */ + warnings: string[]; + /** run: what the program printed against what its EXPECT lines say. */ + expect?: { want: string[]; got: string[]; ok: boolean }; + /** translate: each notation's text. */ + panes?: TranslatedPane[]; +} + +/* ------------------------------------------------------------------ */ +/* The session */ +/* ------------------------------------------------------------------ */ + +interface Prepared { session: Session; header: ProgramHeader; given: LangId[]; sources: Partial> } + +function prepare(req: RenderRequest): Prepared { + const sources: Partial> = {}; + const given: LangId[] = []; + for (const l of PANES) { + const text = req.files[l]; + if (typeof text !== 'string') continue; + sources[l] = listingText(text, l); + given.push(l); + } + const runnable = (['lingo', 'matho', 'pseudo', 'mojo', 'asm'] as LangId[]).find((l) => given.includes(l)) ?? given[0] ?? 'pseudo'; + const lang = req.lang && given.includes(req.lang) ? req.lang : runnable; + // the header of the file that runs comes first; another file's fills in what it leaves out + const order = [lang, ...given.filter((l) => l !== lang)]; + const header: ProgramHeader = { input: [], expect: [], questions: [] }; + for (const l of order) { + const h = programHeader(req.files[l] ?? ''); + header.call ??= h.call; header.errors ??= h.errors; header.stops ??= h.stops; + if (!header.input.length) header.input = h.input; + if (!header.expect.length) header.expect = h.expect; + header.questions.push(...h.questions); + } + const state: PlayState = { ...emptyState(), sources, lang, view: 'trace' }; + const call = req.call !== undefined ? req.call : header.call; + if (call) state.call = call; + const input = req.input ?? header.input; + if (input.length) state.input = input.join('\n'); + if (req.setup) state.setup = listingText(req.setup, 'asm'); + if (req.machine) state.machine = req.machine; + if (typeof req.t === 'number' && req.t >= 0) state.t = Math.floor(req.t); + if (req.title) state.title = req.title; + return { session: new Session(state), header, given, sources }; +} + +/* ------------------------------------------------------------------ */ +/* Small pieces */ +/* ------------------------------------------------------------------ */ + +/** Code, highlighted by the pane's own highlighter, one `.pplus-ln` per line (`data-line` is 1-based). */ +export function highlighted(text: string, lang: LangId, opts: { numbers?: boolean } = {}): HTMLElement { + const svc = SERVICES[lang]; + const rows = text.split('\n'); + const doc = svc.tokenizeLines ? svc.tokenizeLines(text) : null; + // focusable, so a reader with only a keyboard can scroll a listing wider or taller than its box + const pre = el('pre', { class: `pplus-code lang-${lang}`, tabindex: '0' }); + rows.forEach((line, i) => { + const ln = el('span', { class: 'pplus-ln', 'data-line': String(i + 1) }); + if (opts.numbers) add(ln, el('span', { class: 'pplus-lno', 'aria-hidden': 'true' }, String(i + 1))); + const toks = doc ? doc[i] ?? [] : svc.tokenize ? svc.tokenize(line) : [{ text: line, cls: '' }]; + for (const t of toks) add(ln, t.cls ? el('span', { class: t.cls }, t.text) : t.text); + if (!line) add(ln, ' '); + add(pre, ln); + if (i < rows.length - 1) add(pre, '\n'); + }); + return pre; +} + +const chip = (lang: LangId) => el('span', { class: `pplus-chip pplus-chip-${lang}` }, LANG_NAMES[lang]); + +function head(...parts: Array): HTMLElement { + return el('div', { class: 'pplus-head' }, ...parts); +} + +/** A view built for a screen, made for a page: controls that need the app (buttons, inputs, menus) are taken out, and a link-styled line reference becomes plain text. */ +export function freeze(root: Element): void { + for (const s of [...root.querySelectorAll('select')]) { + const opt = (s as HTMLSelectElement).options[(s as HTMLSelectElement).selectedIndex] ?? (s as HTMLSelectElement).options[0]; + s.replaceWith(el('span', { class: 'pplus-picked' }, opt?.textContent ?? '')); + } + for (const b of [...root.querySelectorAll('button')]) { + if (b.classList.contains('linkish')) b.replaceWith(el('span', { class: b.className.replace('linkish', 'pplus-ref') }, b.textContent ?? '')); + else if (b.classList.contains('btn-option')) b.replaceWith(el('span', { class: 'pplus-option' }, b.textContent ?? '')); + else if (b.classList.contains('life-mark')) b.replaceWith(el('span', { class: b.className, title: b.getAttribute('title') ?? '', style: b.getAttribute('style') ?? '' })); + else b.remove(); + } + for (const i of [...root.querySelectorAll('input')]) i.remove(); + for (const l of [...root.querySelectorAll('.tool-label')]) l.remove(); + // what the app says about stepping, which a page does not do + for (const x of [...root.querySelectorAll('.fuzz-bar, .viz-step-note')]) x.remove(); + for (const x of [...root.querySelectorAll('[title=""]')]) x.removeAttribute('title'); +} + +const mdEscape = (s: string) => s.replace(/\|/g, '\\|').replace(/\n/g, ' '); +const fence = (text: string, cls = '') => { const ticks = /```/.test(text) ? '````' : '```'; return `${ticks}${cls}\n${text}\n${ticks}`; }; +function mdTable(headRow: string[], rows: string[][]): string { + return [`| ${headRow.map(mdEscape).join(' | ')} |`, `|${headRow.map(() => '---').join('|')}|`, ...rows.map((r) => `| ${r.map((c) => mdEscape(c || ' ')).join(' | ')} |`)].join('\n'); +} + +function result(view: StaticView, lang: LangId | null, node: HTMLElement, markdown: string, warnings: string[] = [], extra: Partial = {}): RenderResult { + node.classList.add('pplus-static', `pplus-v-${view}`); + node.setAttribute('data-pplus-view', view); + return { view, lang, node, html: node.outerHTML, markdown, warnings, ...extra }; +} + +/** A view of the app's, drawn into a fresh element and frozen for the page. */ +function appView(draw: (host: HTMLElement) => unknown, cls: string): HTMLElement { + const host = el('div', { class: `view ${cls}` }); + draw(host); + freeze(host); + return host; +} + +const noHooks = { reveal: () => { /* a page has no editor to move */ }, fix: () => { /* nor one to fix */ } }; + +/* ------------------------------------------------------------------ */ +/* The views */ +/* ------------------------------------------------------------------ */ + +export function renderStatic(req: RenderRequest): RenderResult { + if (!isStaticView(req.view)) throw new Error(`unknown view "${req.view}": the static views are ${STATIC_VIEWS.join(', ')}`); + const p = prepare(req); + if (!p.given.length) return result(req.view, null, el('div', {}, el('p', { class: 'pplus-note' }, 'No program: give a file (pseudo=, lingo=, matho=, speco=, mojo= or asm=).')), '*No program was given.*', ['no program file was given']); + switch (req.view) { + case 'run': return runOf(p, req); + case 'steps': return stepsOf(p, req); + case 'table': return tableOf(p); + case 'flow': case 'data': return graphOf(p, req.view); + case 'life': return lifeOf(p); + case 'proof': return proofOf(p); + case 'tests': return testsOf(p); + case 'check': return checkOf(p); + case 'translate': return translateOf(p, req); + case 'machine': return machineOf(p); + case 'hw': return hwOf(p, req); + } +} + +/* ---------- run ---------- */ + +function runOf(p: Prepared, req: RenderRequest): RenderResult { + const { session, header } = p; + const warnings: string[] = []; + const lang = session.traceLang(); + const trace = session.trace(); + const call = lang !== 'mojo' && lang !== 'asm' ? session.callText() : null; + const node = el('div', {}); + const compiled = lang === 'mojo' ? req.compiled ?? null : null; + let got: string[]; + let who: string; + if (compiled) { + got = compiled.stdout.replace(/\n$/, '').split('\n').filter((l, i, a) => !(a.length === 1 && l === '')); + who = `${compiled.version}, on the machine that rendered this page`; + } else { + got = trace ? [...trace.output] : []; + who = lang === 'mojo' ? `Programming+'s Mojo interpreter (modeled on Mojo ${MOJO_VERSION}; not the compiler)` : lang === 'asm' ? 'the model x86-64 machine' : `Programming+'s ${LANG_NAMES[lang]} interpreter`; + } + add(node, head(chip(lang), call ? el('code', { class: 'pplus-call' }, call) : null, el('span', { class: 'pplus-muted' }, trace ? `${trace.count} step${trace.count === 1 ? '' : 's'}` : ''), el('span', { class: 'pplus-spacer' }), el('span', { class: 'pplus-muted pplus-who' }, who))); + if (!trace && !compiled) { + const why = session.runError ?? (session.allDiagnostics().find((d) => d.severity === 'error')?.message ? `It does not run yet: ${session.allDiagnostics().find((d) => d.severity === 'error')!.message}` : 'There is nothing to run.'); + add(node, el('p', { class: 'pplus-err' }, why)); + warnings.push(`run: ${why}`); + // a program with EXPECT lines that does not run does not print them: pplus-strict stops the render on it + return result('run', lang, node, `*${why}*`, warnings, header.expect.length ? { expect: { want: header.expect, got: [], ok: false } } : undefined); + } + add(node, el('pre', { class: 'pplus-out' }, got.length ? got.join('\n') : el('span', { class: 'pplus-muted' }, '(printed nothing)'))); + let errText: string | null = null; + if (compiled && compiled.status !== 0) errText = `exited with status ${compiled.status}${compiled.stderr.trim() ? `: ${compiled.stderr.trim().split('\n').slice(0, 6).join('\n')}` : ''}`; + else if (!compiled && trace?.error) errText = `stopped${trace.error.line ? ` at line ${trace.error.line}` : ''}: ${trace.error.message}`; + if (errText) add(node, el('p', { class: header.stops ? 'pplus-note' : 'pplus-err' }, `The run ${errText}`)); + if (trace?.truncated) add(node, el('p', { class: 'pplus-note' }, 'The run was cut short after the step limit.')); + let expect: RenderResult['expect']; + if (header.expect.length) { + const ok = JSON.stringify(got) === JSON.stringify(header.expect); + expect = { want: header.expect, got, ok }; + add(node, el('div', { class: `pplus-expect ${ok ? 'is-ok' : 'is-bad'}` }, ok + ? `✓ prints the ${header.expect.length} line${header.expect.length === 1 ? '' : 's'} its EXPECT header says` + : el('span', {}, '✗ does not print what its EXPECT header says. Expected:', el('pre', { class: 'pplus-out' }, header.expect.join('\n'))))); + if (!ok) warnings.push(`run: printed ${JSON.stringify(got)}, its EXPECT lines say ${JSON.stringify(header.expect)}`); + } + if (compiled && trace && JSON.stringify(trace.output) !== JSON.stringify(got)) warnings.push('run: Programming+\'s Mojo interpreter printed something else than the compiler; the page shows the compiler\'s output'); + const md = [`${LANG_NAMES[lang]}${call ? ` \`${call}\`` : ''}, run by ${who}:`, '', fence(got.join('\n') || '(printed nothing)'), errText ? `\n*The run ${errText}*` : ''].join('\n'); + return result('run', lang, node, md, warnings, { expect }); +} + +/* ---------- steps ---------- */ + +/** The stepper's data, read by pplus.js: one row per step, and a value per followed variable after it. */ +export interface StepsData { + lang: LangId; + count: number; + t: number; + cols: Array<{ label: string; type: string }>; + /** l: the line the step ran; x: what it did; f: its kind (write, decision, loop, call, return, io, life, error); w: what it wrote; c: each column's value after it (null: not in scope); cw: the columns it wrote; o: what it printed. */ + rows: Array<{ l: number | null; x: string; f: string; w: string[]; c: Array; cw: number[]; o: string[] }>; + /** The values before the first step. */ + c0: Array; + error: string | null; + truncated: boolean; +} + +const hex = (v: unknown): string => { try { return '0x' + BigInt.asUintN(64, BigInt(v as any)).toString(16); } catch { return String(v); } }; + +function stepsData(session: Session, req: RenderRequest): StepsData | null { + const trace = session.trace(); + if (!trace) return null; + const max = Math.max(10, Math.min(req.max ?? 400, 5000)); + const n = Math.min(trace.count, max); + if (trace.lang === 'asm') { + const steps = trace.steps as any[]; + const states = trace.states as any[]; + const regs: string[] = []; + for (const s of steps.slice(0, n)) for (const r of s.diff?.regs ?? []) if (!regs.includes(r.name)) regs.push(r.name); + const at = (i: number) => regs.map((r) => (states[i]?.regs?.[r] !== undefined ? hex(states[i].regs[r]) : null)); + return { + lang: 'asm', count: n, t: Math.min(req.t ?? 0, n), cols: regs.map((r) => ({ label: r, type: 'register' })), c0: at(0), + rows: steps.slice(0, n).map((s, i) => { + const wrote = (s.diff?.regs ?? []).map((r: any) => r.name); + return { l: s.instr.lineNo + 1, x: s.instr.text, f: s.branch ? 'decision' : wrote.length ? 'write' : 'other', w: [...wrote, ...(s.diff?.mem?.length ? ['memory'] : [])], c: at(i + 1), cw: wrote.map((r: string) => regs.indexOf(r)), o: s.diff?.out ? [s.diff.out] : [] }; + }), + error: trace.error?.message ?? null, truncated: trace.truncated || trace.count > n, + }; + } + const cols = runColumns(trace); + let follow = defaultFollow(cols, 6); + if (req.follow?.length) { + const want = req.follow.map((f) => f.toLowerCase()); + const picked = cols.filter((c) => want.includes(c.name.toLowerCase()) || want.includes(c.key.toLowerCase())).map((c) => c.key); + if (picked.length) follow = picked; + } + const byKey = new Map(cols.map((c) => [c.key, c])); + const many = new Set(follow.map((k) => k.split('.')[0])).size > 1; + const rows: RunRow[] = runRows(trace, follow, 0, n); + // what the run prints after its last step (a call's result, "F returned 3") belongs to that step + const printed = rows.reduce((k, r) => k + r.printed.length, 0); + if (n === trace.count && rows.length && printed < trace.output.length) rows[rows.length - 1].printed.push(...trace.output.slice(printed)); + return { + lang: trace.lang, count: n, t: Math.min(req.t ?? 0, n), + cols: follow.map((k) => { const c = byKey.get(k)!; return { label: many ? `${c.fn}.${c.name}` : c.name, type: c.type }; }), + c0: valuesAt(trace, follow, 0).map((v) => v.text), + rows: rows.map((r) => ({ l: r.line, x: r.text, f: familyOf({ kind: r.kind, text: r.text, writes: r.writes }, trace.lang), w: r.writes, c: follow.map((k) => r.cells[k]?.text ?? null), cw: follow.map((k, i) => (r.cells[k]?.wrote ? i : -1)).filter((i) => i >= 0), o: r.printed })), + error: trace.error?.message ?? null, truncated: trace.truncated || trace.count > n, + }; +} + +/** The stepper's panels at position `t` (after t steps), drawn the way pplus.js redraws them; also the page without script. */ +export function stepsPanel(data: StepsData, t: number): { now: string; vals: Array; wrote: number[]; out: string[]; next: number | null; last: number | null } { + const last = t > 0 ? data.rows[t - 1] : null; + const next = t < data.count ? data.rows[t] : null; + const out = data.rows.slice(0, t).flatMap((r) => r.o); + const now = t === 0 ? (data.count ? 'Before the first step.' : 'The program takes no steps.') : `Step ${t}: ${last!.x}${last!.w.length ? ` — writes ${last!.w.join(', ')}` : ''}`; + return { now, vals: last ? last.c : data.c0, wrote: last ? last.cw : [], out, next: next?.l ?? null, last: last?.l ?? null }; +} + +function stepsOf(p: Prepared, req: RenderRequest): RenderResult { + const { session } = p; + const data = stepsData(session, req); + const lang = session.traceLang(); + if (!data) { + const why = session.runError ?? 'It does not run yet; the check view lists what the checker found.'; + return result('steps', lang, el('div', {}, el('p', { class: 'pplus-err' }, why)), `*${why}*`, [`steps: ${why}`]); + } + const source = session.source(data.lang); + const t = data.t; + const at = stepsPanel(data, t); + const code = highlighted(source, data.lang, { numbers: true }); + for (const ln of [...code.querySelectorAll('.pplus-ln')]) { + const n = Number(ln.getAttribute('data-line')); + if (n === at.next) ln.classList.add('is-next'); + if (n === at.last) ln.classList.add('is-last'); + } + const btn = (go: string, label: string, title: string) => el('button', { type: 'button', class: 'pplus-btn', 'data-go': go, title, 'aria-label': title }, label); + const vars = el('table', { class: 'pplus-vars' }); + data.cols.forEach((c, i) => add(vars, el('tr', { class: at.wrote.includes(i) ? 'is-wrote' : '' }, el('th', { title: c.type }, c.label), el('td', { 'data-col': String(i) }, at.vals[i] ?? '—')))); + const json = JSON.stringify(data).replace(/ c.label)], data.rows.slice(0, 60).map((r, i) => [String(i + 1), String(r.l ?? ''), r.x, ...r.c.map((v) => v ?? '')]))].join('\n') + (data.count > 60 ? `\n\n*…and ${data.count - 60} more steps in the HTML version.*` : ''); + return result('steps', data.lang, node, md); +} + +/* ---------- table, flow, data, life ---------- */ + +function tableOf(p: Prepared): RenderResult { + const { session } = p; + const node = appView((h) => traceTableView(session, h), 'view-table'); + const trace = session.trace(); + let md = '*The table of values needs a run that works.*'; + if (trace && trace.lang !== 'asm') { + const follow = defaultFollow(runColumns(trace), 8); + const rows = runRows(trace, follow, 0, trace.count, { onlyWrites: true }).slice(0, 80); + md = mdTable(['step', 'line', ...follow.map((k) => k.slice(k.indexOf('.') + 1)), 'printed'], rows.map((r) => [String(r.step + 1), String(r.line ?? ''), ...follow.map((k) => (r.cells[k]?.wrote ? r.cells[k].text ?? '' : '')), r.printed.join(' ⏎ ')])); + } + return result('table', trace?.lang ?? session.traceLang(), node, md); +} + +function graphOf(p: Prepared, view: 'flow' | 'data'): RenderResult { + const { session } = p; + // the flowchart and the data flow draw the pseudo (or the Mojo); a lingo or matho program is drawn as its pseudo + if (session.state.lang !== 'mojo') session.state.lang = 'pseudo'; + const node = appView((h) => (view === 'flow' ? flowView(session, h) : dataFlowView(session, h)), view === 'flow' ? 'view-flow' : 'view-data'); + const what = view === 'flow' ? 'flowchart' : 'data-flow graph'; + return result(view, session.state.lang, node, `*The ${what} of this procedure is drawn in the HTML version of this page.*`); +} + +function lifeOf(p: Prepared): RenderResult { + const { session } = p; + session.state.lang = 'mojo'; + const node = appView((h) => lifetimesView(session, h), 'view-life'); + const warnings = p.given.includes('mojo') ? [] : ['life: lifetimes are drawn for a Mojo file (mojo=)']; + return result('life', 'mojo', node, '*Each value\'s lifetime is drawn in the HTML version of this page.*', warnings); +} + +/* ---------- proof, tests, check ---------- */ + +function proofOf(p: Prepared): RenderResult { + const { session } = p; + session.state.lang = 'pseudo'; + const node = appView((h) => proofView(session, h, noHooks), 'view-proof'); + const pr = session.proof(); + const md = pr ? [`**${pr.report.counts.proved} proved, ${pr.report.counts.broken} broken, ${pr.report.counts.open} open.**`, '', ...pr.report.units.flatMap((u) => u.obligations.map((o) => `- ${o.status}: ${o.label} (line ${(o as any).specoLine ?? (o as any).pseudoLine ?? o.line})`))].join('\n') : '*The proof needs pseudocode that parses.*'; + return result('proof', 'pseudo', node, md, pr && pr.report.counts.broken ? [`proof: ${pr.report.counts.broken} claim(s) broken`] : []); +} + +function testsOf(p: Prepared): RenderResult { + const { session } = p; + if (session.state.lang !== 'mojo') session.state.lang = 'pseudo'; + const node = appView((h) => testsView(session, h, noHooks), 'view-tests'); + const reps = session.tests(); + const md = reps.length ? reps.map((r) => `- \`${r.name}\`: ${r.failures.length ? `${r.failures.length} way(s) to fail, e.g. \`${r.failures[0].call}\`: ${r.failures[0].message}` : 'no failures'} on ${r.checked} generated inputs`).join('\n') : '*Nothing to test: generated-input testing needs a routine.*'; + return result('tests', session.state.lang, node, md); +} + +function checkOf(p: Prepared): RenderResult { + const { session, given } = p; + // only the files the page gave: a notation the hub filled in is not the author's to answer for + const view = Object.create(session) as Session; + (view as any).allDiagnostics = () => given.flatMap((l) => session.diagnostics(l)); + const node = appView((h) => problemsView(view, h, noHooks), 'view-problems'); + const diags = given.flatMap((l) => session.diagnostics(l)); + const md = diags.length ? diags.map((d) => `- **${d.severity}**, ${LANG_NAMES[d.lang]} line ${d.line}: ${d.message}`).join('\n') : '*The checker has nothing to report.*'; + return result('check', given[0] ?? null, node, md); +} + +/* ---------- translate ---------- */ + +const LABEL: Record = { lingo: 'lingo', matho: 'matho', pseudo: 'pseudo', speco: 'speco', mojo: 'Mojo', asm: 'x86-64' }; + +function translateOf(p: Prepared, req: RenderRequest): RenderResult { + const { sources, given, header } = p; + const warnings: string[] = []; + const call = req.call !== undefined ? req.call : header.call ?? null; + const linkedGiven = given.filter((l) => (LINKED as readonly string[]).includes(l)); + const panes: TranslatedPane[] = []; + let hub: { sources: Partial>; stale: Partial>; mojo: string; lead: LangId } | null = null; + if (linkedGiven.length) { + // the first file the page gave leads, as if typed into its pane; the notations it was not given follow from it + // (a file the page gives is always shown as written) + const lead = linkedGiven.includes(req.lang as any) ? req.lang! : linkedGiven[0]; + const r = new SyncHub({ lingo: '', matho: '', pseudo: '', speco: '' }, undefined, { call }).edit(lead as any, sources[lead] ?? ''); + hub = { sources: r.sources, stale: r.stale, mojo: r.mojo.source, lead }; + } + const want = req.to?.length ? req.to : [...LINKED, 'mojo'] as LangId[]; + for (const l of want) { + if (given.includes(l)) { panes.push({ lang: l, label: LABEL[l], text: sources[l] ?? '', authored: true, generated: false }); continue; } + if (l === 'mojo') { + const text = hub?.mojo ?? (hub?.sources.pseudo ? mojoFromPseudo(hub.sources.pseudo, call).source : ''); + if (text.trim()) panes.push({ lang: 'mojo', label: 'Mojo', text, authored: false, generated: true, from: 'pseudo', note: 'Generated from the pseudo: a literal translation, not reviewed for Mojo best practices.' }); + continue; + } + if (!hub || !(LINKED as readonly string[]).includes(l)) continue; + const text = hub.sources[l] ?? ''; + const stale = hub.stale[l]; + if (stale) { panes.push({ lang: l, label: LABEL[l], text: '', authored: false, generated: false, note: stale }); continue; } + if (text.trim()) panes.push({ lang: l, label: LABEL[l], text, authored: false, generated: true, from: hub.lead }); + } + // the notations the page gave first, as written; then what was made from them + panes.sort((a, b) => Number(b.authored) - Number(a.authored)); + if (!panes.some((x) => x.text.trim())) warnings.push('translate: nothing to show; give a lingo, matho, pseudo or speco file'); + const node = el('div', { class: 'pplus-translate-grid' }); + for (const pane of panes) { + add(node, el('div', { class: `pplus-pane pplus-pane-${pane.lang}` }, + el('div', { class: 'pplus-pane-head' }, chip(pane.lang), pane.authored ? el('span', { class: 'pplus-muted' }, 'as written') : pane.generated ? el('span', { class: 'pplus-tag-generated' }, 'generated') : null), + pane.text ? highlighted(pane.text, pane.lang) : null, + pane.note ? el('p', { class: pane.text ? 'pplus-muted pplus-small' : 'pplus-note' }, pane.text ? pane.note : `Cannot be written in ${pane.label}: ${pane.note}`) : null)); + } + const md = panes.map((x) => `**${x.label}**${x.generated ? ' (generated)' : ''}\n\n${x.text ? fence(x.text, x.lang === 'matho' ? 'latex' : x.lang) : `*${x.note}*`}`).join('\n\n'); + return result('translate', panes[0]?.lang ?? null, node, md, warnings, { panes }); +} + +/* ---------- machine ---------- */ + +function machineOf(p: Prepared): RenderResult { + const { session } = p; + session.state.lang = 'asm'; + const node = appView((h) => machineView(session, h), 'view-asm'); + const rows = [...node.querySelectorAll('.perf-tbl tr')].map((tr) => [...tr.children].map((c) => (c.textContent ?? '').trim())); + const md = rows.length ? mdTable(['', 'value'], rows) : '*The machine view needs an x86-64 file that assembles (asm=).*'; + return result('machine', 'asm', node, md, p.given.includes('asm') ? [] : ['machine: the machine view needs an x86-64 file (asm=)']); +} + +/* ---------- hw: the machine board ---------- */ + +function hwOf(p: Prepared, req: RenderRequest): RenderResult { + const b = machineBoard(p.session, { views: req.hw, preset: req.preset, t: req.t, max: req.max, listing: req.listing, stepper: req.stepper }); + const r = result('hw', 'asm', b.node, b.markdown, b.warnings); + return { ...r, html: spliceFrames(r.html, b.node) }; +} diff --git a/src/quarto/shortcodes.ts b/src/quarto/shortcodes.ts new file mode 100644 index 0000000..1d97cf8 --- /dev/null +++ b/src/quarto/shortcodes.ts @@ -0,0 +1,150 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +/** + * The shortcodes of the Quarto extension (quarto/_extensions/pplus/pplus.lua), as data: what each is called, what + * it shows, and the options it reads. The app's "With Quarto" gallery (src/ui/quarto.ts) is written from this, + * scripts/check-pages.mjs reads it to know a shortcode when it sees one, and tests/quarto.test.mjs holds it to the + * names pplus.lua returns. DOM-free. + */ +import type { LangId } from '#core/common/types.js'; +import type { StaticView, RenderRequest } from './render.js'; +import { listingText } from './program.js'; +import { emptyState, type PlayState } from '../core/state.js'; +import { boardView } from '../core/hardware.js'; +import { HW_NAMES } from './machine.js'; + +export type ShortcodeKind = 'rendered' | 'machine' | 'live' | 'text'; + +export interface ShortcodeDef { + name: string; + kind: ShortcodeKind; + /** rendered: the view render.ts draws; live: the embed view (or `any`, chosen by view=). */ + view?: StaticView | 'playground' | 'any'; + /** machine: the board view it shows (its pplus-hw-), or none for the whole board. */ + hw?: string; + title: string; + summary: string; + /** The options it reads besides the shared ones (SHARED_OPTIONS). */ + options: string[]; +} + +/** Read by every shortcode that names program files. */ +export const SHARED_OPTIONS = ['lingo', 'matho', 'pseudo', 'speco', 'mojo', 'asm', 'setup', 'lang', 'call', 'input', 'machine', 't', 'title', 'caption', 'collapse', 'area'] as const; + +/** Read by every rendered view (the machine's too). */ +export const RENDERED_OPTIONS = ['code', 'numbers', 'live', 'height', 'column'] as const; + +export const SHORTCODES: ShortcodeDef[] = [ + { name: 'pplus-run', kind: 'rendered', view: 'run', title: 'Run it', summary: 'What the program prints and returns, checked against its EXPECT lines. A Mojo file runs on the real compiler when the machine that renders has one.', options: ['compiler'] }, + { name: 'pplus-steps', kind: 'rendered', view: 'steps', title: 'Step through it', summary: 'The listing beside a stepper: every step, the line it ran, what it wrote, the values after it, and what was printed so far. The run is in the page; a small script moves through it.', options: ['follow', 'max'] }, + { name: 'pplus-table', kind: 'rendered', view: 'table', title: 'Table of values', summary: 'The table you would draw by hand: a column per step that changed something, a row per name.', options: [] }, + { name: 'pplus-flow', kind: 'rendered', view: 'flow', title: 'Flowchart', summary: 'The routine as a flowchart, laid out from its structure; each box shaded by how often its line ran, each arrow labeled with how often it was taken.', options: [] }, + { name: 'pplus-dataflow', kind: 'rendered', view: 'data', title: 'Data flow', summary: 'Which names feed which: the parameters on the left, what leaves on the right, an arrow for each assignment.', options: [] }, + { name: 'pplus-lifetimes', kind: 'rendered', view: 'life', title: 'Lifetimes', summary: 'Each Mojo value from the step it is made to the step it is destroyed or moved out of, with every copy and move on the way.', options: [] }, + { name: 'pplus-proof', kind: 'rendered', view: 'proof', title: 'Proof', summary: 'Every claim the specification makes (ENSURE, INVARIANT, a .speco file woven in): proved, broken by a run, or open.', options: [] }, + { name: 'pplus-tests', kind: 'rendered', view: 'tests', title: 'Generated tests', summary: 'The fuzzer\'s report for each routine: what each input must do, how the inputs were made, every failure shrunk to the smallest input, every case run.', options: [] }, + { name: 'pplus-check', kind: 'rendered', view: 'check', title: 'The checker', summary: 'What Programming+ finds in each file before anything runs, on the file\'s own lines, with a link to the guide.', options: [] }, + { name: 'pplus-translate', kind: 'rendered', view: 'translate', title: 'Every notation', summary: 'One file in, the procedure in every notation out: lingo, matho, pseudo, speco, and Mojo generated from the pseudo (and labeled so). As tabs, columns, or the app\'s panes.', options: ['to', 'layout'] }, + { name: 'pplus-machine', kind: 'rendered', view: 'machine', title: 'The machine', summary: 'An x86-64 run on the model machine: instructions, cycles on an in-order and an out-of-order core, cache misses, branches, and what bounds it.', options: [] }, + { name: 'pplus-view', kind: 'rendered', view: undefined, title: 'Any view by name', summary: 'Any of the rendered views, chosen with view= (run, steps, table, flow, data, life, proof, tests, check, translate, machine).', options: ['view'] }, + { name: 'pplus-hw', kind: 'machine', view: 'hw', title: 'The machine board', summary: 'The Hardware area\'s board over an x86-64 run: the listing beside the cards of a preset (registers and memory, caches, pipeline, the whole chip) or the views you name, every one drawn at every step, with a stepper.', options: ['preset', 'views', 'listing', 'stepper', 'max'] }, + ...Object.entries(HW_NAMES).map(([name, id]): ShortcodeDef => { + const v = boardView(id)!; + return { name: `pplus-hw-${name}`, kind: 'machine', view: 'hw', hw: name, title: v.label, summary: v.blurb, options: ['listing', 'stepper', 'max'] }; + }), + { name: 'pplus-playground', kind: 'live', view: 'playground', title: 'The whole playground', summary: 'The app in the page: every pane, the stepper, every inspect tab and the dock. The reader\'s edits are kept in their browser; Reset brings the page\'s version back.', options: ['panel', 'build', 'dock', 'docktab', 'editor', 'side', 'dockheight', 'theme', 'ro', 'height', 'problem', 'state'] }, + { name: 'pplus-embed', kind: 'live', view: 'any', title: 'One live view', summary: 'One view of the app with the code it reads: trace, table, flow, data, life, problems, proof, tests, compiler, asm, or one pane.', options: ['view', 'panel', 'build', 'theme', 'ro', 'showcall', 'split', 'height', 'problem', 'state'] }, + { name: 'pplus', kind: 'live', view: 'any', title: 'The original shortcode', summary: 'A live embed, a listing, or both (show=). Pages written for it keep working.', options: ['view', 'show', 'mode', 'text', 'panel', 'build', 'theme', 'ro', 'showcall', 'split', 'height', 'problem', 'state'] }, + { name: 'pplus-listing', kind: 'text', title: 'Listings', summary: 'The files as highlighted code blocks, without their header lines; a .tex file typeset as equations.', options: ['numbers', 'math', 'link', 'text'] }, + { name: 'pplus-tabs', kind: 'text', title: 'Tabs', summary: 'The files as a tabset, one tab per notation.', options: ['numbers', 'math'] }, + { name: 'pplus-link', kind: 'text', title: 'A link', summary: 'A link that opens the program in the app.', options: ['view', 'text'] }, +]; + +export const SHORTCODE_NAMES: readonly string[] = SHORTCODES.map((s) => s.name); + +export const OPTION_DOCS: Record = { + lingo: 'a lingo file beside the page', matho: 'a LaTeX (.tex) file of equations', pseudo: 'a pseudo file', speco: 'a speco file (the specification)', + mojo: 'a Mojo file', asm: 'an x86-64 listing', setup: 'the x86-64 setup block: registers and memory', + lang: 'the pane that runs (default: the first of lingo, matho, pseudo, mojo, asm given)', + call: 'the call to run (default: the file\'s // CALL: line)', input: 'lines INPUT reads, separated by |', machine: 'the x86-64 machine model preset', + t: 'the step the stepper starts on', title: 'a title over the view', caption: 'a sentence under it', collapse: '1 folds it into a block the reader opens', + area: 'bridge, dev or hw: where "open in the playground" goes', + code: '1 prints the program above the view', numbers: '1 numbers the listing\'s lines', live: 'click adds "make it live", which puts the live view in its place', + height: 'the live frame\'s height in px (auto: fits its content)', compiler: 'auto (the real mojo when on the PATH), on, or off', + follow: 'the variables to show, comma-separated', max: 'the most steps kept (default 400; a longer machine run is sampled)', to: 'the notations to show, comma-separated', + layout: 'tabs (default), columns, or grid', + preset: 'the board\'s arrangement: regs (default), caches, pipeline or chip', views: 'the machine views to show, comma-separated (registers, memory, cache, pipeline, chip...)', + listing: '0 leaves out the x86-64 listing', column: 'Quarto\'s column for the figure: body, page (pplus-hw\'s default), screen...', stepper: '0 draws only step t, without a stepper', view: 'which view', panel: 'the tab the playground opens on', build: 'O0 (as written) or default (as mojo build does)', + dock: 'open or closed', docktab: 'the dock\'s tab', editor: 'the editor column\'s share of the width', side: 'the variables panel\'s share', dockheight: 'the editors\' share of the height', + theme: 'light or dark (default: follow the page)', ro: '1: read-only, nothing saved', showcall: '0 hides the run box', split: 'the code\'s share of the frame', + problem: 'a catalog problem instead of files', state: 'a state from the playground\'s Share dialog', show: 'embed, listing or both', mode: 'link: only a link', text: 'the link\'s text', math: '0 prints a .tex file as code', link: '1 adds a link to the app', +}; + +/** The shortcode as a page writes it. */ +export function shortcodeText(name: string, attrs: Record): string { + const parts = Object.entries(attrs).map(([k, v]) => `${k}="${v.replace(/"/g, '"')}"`); + return `{{< ${name}${parts.length ? ' ' + parts.join(' ') : ''} >}}`; +} + +/** + * A title from a state (which anyone can write into a link) as a shortcode argument the Share dialog hands to a page + * author: one line, at most 120 characters, a double quote as `"` (pplus.lua reads it back), and none of the + * characters that could end the shortcode or start markup in the page it is pasted into (`<`, `>`, `{`, `}`). + */ +export function shortcodeTitle(title: string): string { + return title.replace(/[<>{}]/g, '').replace(/\s+/g, ' ').trim().slice(0, 120).replace(/"/g, '"'); +} + +const PANES: LangId[] = ['lingo', 'matho', 'pseudo', 'speco', 'mojo', 'asm']; +const list = (s: string | undefined) => (s ? s.split(/[\s,]+/).filter(Boolean) : undefined); + +/** + * What a rendered shortcode asks render.ts for, given its options and the files beside the page (by name): the + * same request pplus.lua builds, for the gallery to draw what a page would get. + */ +export function requestFor(view: StaticView, attrs: Record, files: Record): RenderRequest { + const req: RenderRequest = { view, files: {} }; + for (const p of PANES) if (attrs[p] && files[attrs[p]] !== undefined) req.files[p] = files[attrs[p]]; + if (attrs.lang) req.lang = attrs.lang as LangId; + if (attrs.call) req.call = attrs.call; + if (attrs.input) req.input = attrs.input.split('|'); + if (attrs.setup && files[attrs.setup] !== undefined) req.setup = files[attrs.setup]; + if (attrs.machine) req.machine = attrs.machine; + if (attrs.t && Number.isFinite(Number(attrs.t))) req.t = Number(attrs.t); + if (attrs.title) req.title = attrs.title; + if (attrs.max && Number.isFinite(Number(attrs.max))) req.max = Number(attrs.max); + if (attrs.views) req.hw = list(attrs.views); + if (attrs.preset) req.preset = attrs.preset; + if (attrs.listing === '0') req.listing = false; + if (attrs.stepper === '0') req.stepper = false; + req.follow = list(attrs.follow); + req.to = list(attrs.to) as LangId[] | undefined; + return req; +} + +/** The state a live shortcode puts in its iframe's URL: the same one pplus.lua writes. */ +export function liveStateFor(attrs: Record, files: Record): PlayState { + const s = emptyState(); + let first: LangId | null = null; + let call: string | undefined; let input: string[] | undefined; + for (const p of PANES) { + const text = attrs[p] ? files[attrs[p]] : undefined; + if (text === undefined) continue; + s.sources[p] = listingText(text, p); + first ??= p; + for (const line of text.split('\n')) { + const m = /^\s*(?:\/\/|%|#)\s*(CALL|INPUT):\s?(.*)$/.exec(line); + if (m?.[1] === 'CALL') call ??= m[2].trim(); + if (m?.[1] === 'INPUT') (input ??= []).push(m[2]); + } + } + s.lang = (attrs.lang as LangId) || first || 'pseudo'; + s.view = 'trace'; + if (attrs.setup && files[attrs.setup] !== undefined) s.setup = files[attrs.setup]; + const c = attrs.call ?? call; + if (c) s.call = c; + if (attrs.input) s.input = attrs.input.split('|').join('\n'); else if (input) s.input = input.join('\n'); + if (attrs.title) s.title = attrs.title; + if (attrs.t) s.t = Number(attrs.t); + return s; +} diff --git a/src/ui/consent.ts b/src/ui/consent.ts new file mode 100644 index 0000000..e4b4895 --- /dev/null +++ b/src/ui/consent.ts @@ -0,0 +1,38 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +/** + * Before the first Compile & run in this browser: what is sent, to whom, and a choice. Plain words, once; the + * answer is kept by prefs.ts. Every way of compiling (the toolbar, Ctrl+Enter, the Compiler view, an embed) asks here. + */ +import { el, add, button } from './dom.js'; +import { allowSend, sendAllowed } from '../core/prefs.js'; +import { compileBackend } from '#core/services/compile-backend.js'; + +/** The notice, as one sentence, for the places that say it without asking (the Compiler view before a compile). */ +export function sendNotice(): string { + const host = compileBackend().host; + return `Compile & run sends the program in the Mojo pane, and the lines in the input box, to ${host} (Compiler Explorer, a public service run by others), which builds and runs it and sends back the result. Nothing else leaves your browser.`; +} + +export function confirmSend(): Promise { + if (sendAllowed()) return Promise.resolve(true); + if (typeof document === 'undefined' || typeof (document.createElement('dialog') as any).showModal !== 'function') { + const ok = typeof confirm === 'function' ? confirm(`${sendNotice()}\n\nSend it?`) : false; + if (ok) allowSend(); + return Promise.resolve(ok); + } + return new Promise((resolve) => { + const host = compileBackend().host; + const dlg = el('dialog', { class: 'share send-consent', 'aria-labelledby': 'send-consent-title' }); + let answer = false; + add(dlg, el('h3', { id: 'send-consent-title' }, `Send this program to ${host}?`), + el('p', {}, sendNotice()), + el('p', { class: 'small muted' }, `Programming+ ships no compiler of its own, so this is the only way it can show what the real Mojo compiler says. ${host} is a public service with its own privacy policy: do not send anything private. Programming+ asks once in this browser.`), + el('div', { class: 'share-actions' }, + button(`Send to ${host}`, () => { answer = true; allowSend(); dlg.close(); }, { class: 'btn btn-primary' }), + button('Cancel', () => dlg.close(), { class: 'btn' }))); + document.body.appendChild(dlg); + dlg.addEventListener('close', () => { dlg.remove(); resolve(answer); }); + dlg.showModal(); + }); +} diff --git a/src/ui/dom.ts b/src/ui/dom.ts new file mode 100644 index 0000000..b048f32 --- /dev/null +++ b/src/ui/dom.ts @@ -0,0 +1,62 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +/** Minimal DOM helpers. No framework; the app is small enough to render by hand. */ + +type Child = Node | string | number | null | undefined | false | Child[]; + +export function el(tag: K, attrs: Record = {}, ...children: Child[]): HTMLElementTagNameMap[K] { + const node = document.createElement(tag); + for (const [k, v] of Object.entries(attrs)) { + if (v == null || v === false) continue; + if (k === 'class') node.className = String(v); + else if (k === 'style' && typeof v === 'object') Object.assign(node.style, v); + else if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2).toLowerCase(), v); + else if (k === 'dataset') Object.assign(node.dataset, v); + else if (k === 'value' || k === 'checked' || k === 'selected' || k === 'disabled' || k === 'readOnly') (node as any)[k] = v; + else if (k in node && typeof v !== 'string') (node as any)[k] = v; + else node.setAttribute(k, String(v)); + } + add(node, children); + return node; +} + +export function add(parent: Node, ...children: Child[]): void { + for (const c of children) { + if (c == null || c === false) continue; + if (Array.isArray(c)) add(parent, ...c); + else parent.appendChild(typeof c === 'string' || typeof c === 'number' ? document.createTextNode(String(c)) : c); + } +} + +export function clear(node: Node): void { + while (node.firstChild) node.removeChild(node.firstChild); +} + +export function frag(...children: Child[]): DocumentFragment { + const f = document.createDocumentFragment(); + add(f, children); + return f; +} + +/** A button with the app's `btn` look; classes given in `attrs` are added to it, never in place of it. */ +export function button(label: string, onClick: (e: MouseEvent) => void, attrs: Record = {}): HTMLButtonElement { + const cls = new Set(['btn', ...String(attrs.class ?? '').split(/\s+/).filter(Boolean)]); + return el('button', { type: 'button', onClick, ...attrs, class: [...cls].join(' ') }, label); +} + +export function debounce void>(fn: T, ms: number): T { + let h: number | undefined; + return ((...a: any[]) => { clearTimeout(h); h = window.setTimeout(() => fn(...a), ms); }) as T; +} + +export async function copyText(text: string): Promise { + try { await navigator.clipboard.writeText(text); return true; } catch { + const ta = el('textarea', { value: text, style: { position: 'fixed', opacity: '0' } }); + document.body.appendChild(ta); ta.select(); + try { return document.execCommand('copy'); } finally { ta.remove(); } + } +} + +export function escapeHtml(s: string): string { + return s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c] as string)); +} diff --git a/src/ui/editor.ts b/src/ui/editor.ts new file mode 100644 index 0000000..e3c9b13 --- /dev/null +++ b/src/ui/editor.ts @@ -0,0 +1,422 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +/** + * The code editor: CodeMirror 6 (vendored as src/vendor/codemirror.js) behind + * the small interface the shell and the embeds program against. What + * Programming+ adds on top of a stock editor: + * + * - highlighting from the language service's own tokenizer (the same one + * the reference and the home page use), so the editor cannot drift from + * the parser; + * - a gutter that is a teaching instrument: diagnostic marks, breakpoints, + * how often each line ran, and an arrow on the line about to run; + * - the line about to run, the line that just ran, and lines linked from + * a view, as line decorations; + * - each line's first diagnostic at the end of the line, so nothing needs a + * hover; and the reference entry for whatever the pointer rests on. + * + * Tab indents (Shift+Tab outdents), Enter follows the language's own + * indentation rule, Ctrl+/ toggles the line comment, Ctrl+Z/Y undo and redo, + * Ctrl+F searches, Ctrl+G goes to a line, Ctrl+] / Ctrl+[ indent and outdent. + */ +import { el } from './dom.js'; +import { LANG_NAMES, type Diagnostic, type LangId, type QuickFix } from '#core/common/types.js'; +import { explain } from '#core/common/reference.js'; +import { tooltip } from './tooltip.js'; +import { + EditorView, EditorState, Decoration, type DecorationSet, StateField, StateEffect, RangeSetBuilder, RangeSet, + gutter, GutterMarker, gutterLineClass, lineNumbers, keymap, placeholder, WidgetType, Compartment, + history, historyKeymap, defaultKeymap, searchKeymap, search, highlightSelectionMatches, gotoLine, indentMore, indentLess, + bracketMatching, indentUnit, Transaction, type Extension, +} from '../vendor/codemirror.js'; + +export type Tokenizer = (line: string) => Array<{ text: string; cls: string }>; +/** A whole document at once, for languages whose strings span lines. */ +export type DocumentTokenizer = (source: string) => Array>; + +export interface EditorOptions { + tokenize?: Tokenizer; + /** Preferred over `tokenize` when given: the editor tokenizes the document, not each line alone. */ + tokenizeLines?: DocumentTokenizer; + /** The indentation for the line after `line` (Enter); the default rule is the pseudocode's. */ + nextIndent?: (line: string, step: string) => string; + /** The line comment, for Ctrl+/ (Cmd+/). */ + lineComment?: string; + readOnly?: boolean; + placeholder?: string; + onChange?: (value: string) => void; + onCursorLine?: (line: number) => void; + /** Called when the user clicks a diagnostic mark in the gutter. */ + onDiagnosticClick?: (d: Diagnostic) => void; + tabSize?: number; + /** Which language's reference explains hovered words. */ + lang?: LangId; + /** Extra explanations for hovered words (a target language's keywords, say). */ + explainWord?: (word: string, line: string) => { title: string; body: string; where?: string } | null; + /** Show each line's first diagnostic at the end of the line, so nothing needs a hover. */ + inlineMessages?: boolean; + /** A click on a line number (breakpoints). */ + onLineClick?: (line: number) => void; + /** Smaller type, for a companion or an embed. */ + compact?: boolean; +} + +export interface LineDecorations { + /** Line about to run. */ + current?: number | null; + /** Line that just ran. */ + last?: number | null; + /** How many times each line has run. */ + hits?: Map; + /** Lines linked from the other pane (hover). */ + linked?: Set; + /** Breakpoints. */ + breakpoints?: Set; +} + +/* ------------------------------------------------------------------ */ +/* State the shell pushes in: diagnostics and line decorations */ +/* ------------------------------------------------------------------ */ + +interface Extras { diagnostics: Diagnostic[]; deco: LineDecorations; inline: boolean } +const setExtras = StateEffect.define(); +const extrasField = StateField.define({ + create: () => ({ diagnostics: [], deco: {}, inline: true }), + update(v, tr) { for (const e of tr.effects) if (e.is(setExtras)) v = e.value; return v; }, +}); + +function worstOf(ds: Diagnostic[]): '' | 'error' | 'warning' | 'note' { + return ds.some((d) => d.severity === 'error') ? 'error' : ds.some((d) => d.severity === 'warning') ? 'warning' : ds.length ? 'note' : ''; +} + +function byLine(ds: Diagnostic[]): Map { + const m = new Map(); + for (const d of ds) { const a = m.get(d.line) || []; a.push(d); m.set(d.line, a); } + return m; +} + +class MessageWidget extends WidgetType { + constructor(private text: string, private cls: string) { super(); } + eq(o: MessageWidget) { return o.text === this.text && o.cls === this.cls; } + toDOM() { return el('span', { class: `ed-msg ed-msg-${this.cls}` }, this.text); } + ignoreEvent() { return true; } +} + +/** Line classes (current, last, linked, diagnostics) and the inline messages. */ +const lineDecorations = EditorView.decorations.compute([extrasField, 'doc'], (state) => { + const { diagnostics, deco, inline } = state.field(extrasField); + const lines = byLine(diagnostics); + const touched = new Set([...lines.keys()]); + if (deco.current) touched.add(deco.current); + if (deco.last) touched.add(deco.last); + for (const l of deco.linked ?? []) touched.add(l); + const items: Array<{ from: number; deco: Decoration }> = []; + for (const n of touched) { + if (n < 1 || n > state.doc.lines) continue; + const line = state.doc.line(n); + const ds = lines.get(n) || []; + const worst = worstOf(ds); + const cls = ['ed-line', worst && `ed-line-${worst}`, deco.current === n && 'ed-current', deco.last === n && 'ed-last', deco.linked?.has(n) && 'ed-linked'].filter(Boolean).join(' '); + items.push({ from: line.from, deco: Decoration.line({ class: cls }) }); + const shown = ds.filter((d) => d.severity !== 'note'); + if (inline && shown.length) { + const msg = shown[0].message.length > 110 ? shown[0].message.slice(0, 107) + '…' : shown[0].message; + items.push({ from: line.to, deco: Decoration.widget({ widget: new MessageWidget(` ◂ ${msg}${shown.length > 1 ? ` (+${shown.length - 1} more)` : ''}`, worst || 'note'), side: 1 }) }); + } + } + items.sort((a, b) => a.from - b.from || (a.deco.spec.widget ? 1 : -1)); + const b = new RangeSetBuilder(); + for (const it of items) b.add(it.from, it.from, it.deco); + return b.finish(); +}); + +/* ------------------------------------------------------------------ */ +/* Gutters */ +/* ------------------------------------------------------------------ */ + +class TextMarker extends GutterMarker { + constructor(private text: string, private cls: string, private title = '', private click?: () => void) { super(); } + eq(o: TextMarker) { return o.text === this.text && o.cls === this.cls && o.title === this.title; } + toDOM() { + const s = el('span', { class: this.cls, title: this.title }, this.text); + if (this.click) s.addEventListener('mousedown', (e) => { e.preventDefault(); e.stopPropagation(); this.click!(); }); + return s; + } +} +class ClassMarker extends GutterMarker { + constructor(cls: string) { super(); this.elementClass = cls; } + eq(o: ClassMarker) { return o.elementClass === this.elementClass; } +} +const SEV_ICON: Record = { error: '●', warning: '▲', note: '○' }; + +function gutters(opts: EditorOptions): Extension { + const changed = (u: { startState: EditorState; state: EditorState }) => u.startState.field(extrasField) !== u.state.field(extrasField); + const marks = gutter({ + class: 'ed-g ed-g-marks', + lineMarker(view, line) { + const ds = byLine(view.state.field(extrasField).diagnostics).get(view.state.doc.lineAt(line.from).number) || []; + const worst = worstOf(ds); + return worst ? new TextMarker(SEV_ICON[worst], `ed-mark ed-mark-${worst}`, ds.map((d) => d.message).join('\n'), () => opts.onDiagnosticClick?.(ds[0])) : null; + }, + lineMarkerChange: changed, + }); + const numbers = lineNumbers({ + domEventHandlers: { + mousedown(view, line, e) { + if (!opts.onLineClick) return false; + (e as MouseEvent).preventDefault(); + opts.onLineClick(view.state.doc.lineAt(line.from).number); + return true; + }, + }, + }); + const hits = gutter({ + class: 'ed-g ed-g-hits', + lineMarker(view, line) { + const n = view.state.field(extrasField).deco.hits?.get(view.state.doc.lineAt(line.from).number); + return n ? new TextMarker(`×${n}`, 'ed-hits', `ran ${n} time${n === 1 ? '' : 's'}`) : null; + }, + lineMarkerChange: changed, + }); + const arrow = gutter({ + class: 'ed-g ed-g-arrow', + lineMarker(view, line) { + return view.state.field(extrasField).deco.current === view.state.doc.lineAt(line.from).number ? new TextMarker('▶', 'ed-arrow') : null; + }, + lineMarkerChange: changed, + }); + const lineClasses = gutterLineClass.compute([extrasField, 'doc'], (state) => { + const { deco } = state.field(extrasField); + const out: Array<{ from: number; m: ClassMarker }> = []; + for (const n of new Set([...(deco.breakpoints ?? []), ...(deco.current ? [deco.current] : [])])) { + if (n < 1 || n > state.doc.lines) continue; + const cls = [deco.breakpoints?.has(n) && 'ed-gbreak', deco.current === n && 'ed-gcurrent'].filter(Boolean).join(' '); + out.push({ from: state.doc.line(n).from, m: new ClassMarker(cls) }); + } + out.sort((a, b) => a.from - b.from); + return RangeSet.of(out.map((o) => o.m.range(o.from))); + }); + return [marks, numbers, hits, arrow, lineClasses]; +} + +/* ------------------------------------------------------------------ */ +/* Highlighting from the language's tokenizer */ +/* ------------------------------------------------------------------ */ + +function highlighting(opts: EditorOptions): Extension { + const tok = opts.tokenize || ((l: string) => [{ text: l, cls: '' }]); + const compute = (state: EditorState): DecorationSet => { + const b = new RangeSetBuilder(); + const doc = state.doc; + const docTokens = opts.tokenizeLines ? opts.tokenizeLines(doc.toString()) : null; + for (let i = 1; i <= doc.lines; i++) { + const line = doc.line(i); + let at = line.from; + for (const t of docTokens ? (docTokens[i - 1] ?? []) : tok(line.text)) { + const to = Math.min(line.to, at + t.text.length); + if (t.cls && to > at) b.add(at, to, Decoration.mark({ class: t.cls })); + at = to; + } + } + return b.finish(); + }; + const field = StateField.define({ + create: compute, + update: (v, tr) => (tr.docChanged ? compute(tr.state) : v), + provide: (f) => EditorView.decorations.from(f), + }); + return field; +} + +/* ------------------------------------------------------------------ */ +/* Keys */ +/* ------------------------------------------------------------------ */ + +const DEFAULT_OPENERS = /^\s*(FOR|WHILE|REPEAT|IF|ELSE|ELSEIF|CASE|FUNCTION|PROCEDURE|TYPE|LOOP|SPEC)\b.*[^:]$|:\s*$|^\s*\.?\w+:\s*$/; +const DEFAULT_CLOSERS = /^\s*(NEXT|END\w+|UNTIL)\b/; + +function keys(opts: EditorOptions): Extension { + const tab = ' '.repeat(opts.tabSize ?? 4); + const insertTab = (view: EditorView) => { + const { from, to } = view.state.selection.main; + if (from !== to) return indentMore(view); + view.dispatch(view.state.replaceSelection(tab)); + return true; + }; + const enter = (view: EditorView) => { + const { from } = view.state.selection.main; + const line = view.state.doc.lineAt(from); + const before = line.text.slice(0, from - line.from); + let indent = before.match(/^\s*/)?.[0] ?? ''; + if (opts.nextIndent) indent = opts.nextIndent(before, tab); + else if (DEFAULT_OPENERS.test(before) && !DEFAULT_CLOSERS.test(before)) indent += tab; + view.dispatch(view.state.replaceSelection('\n' + indent), { scrollIntoView: true }); + return true; + }; + const comment = (view: EditorView) => { + const mark = opts.lineComment; + if (!mark) return false; + const { from, to } = view.state.selection.main; + const first = view.state.doc.lineAt(from).number; + const last = view.state.doc.lineAt(to > from && view.state.doc.lineAt(to).from === to ? to - 1 : to).number; + const esc = mark.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const lines = []; for (let n = first; n <= last; n++) lines.push(view.state.doc.line(n)); + const all = lines.filter((l) => l.text.trim()).every((l) => new RegExp(`^\\s*${esc}`).test(l.text)); + const changes = lines.filter((l) => l.text.trim()).map((l) => { + if (all) { const m = new RegExp(`^(\\s*)${esc} ?`).exec(l.text)!; return { from: l.from + m[1].length, to: l.from + m[0].length, insert: '' }; } + const ws = l.text.match(/^\s*/)![0].length; return { from: l.from + ws, to: l.from + ws, insert: `${mark} ` }; + }); + view.dispatch({ changes }); + return true; + }; + return keymap.of([ + { key: 'Tab', run: insertTab, shift: indentLess }, + { key: 'Enter', run: enter }, + { key: 'Mod-/', run: comment }, + { key: 'Mod-]', run: indentMore }, { key: 'Mod-[', run: indentLess }, + { key: 'Mod-g', run: gotoLine }, + ...historyKeymap, ...searchKeymap, ...defaultKeymap, + ]); +} + +/* ------------------------------------------------------------------ */ +/* The editor */ +/* ------------------------------------------------------------------ */ + +export class Editor { + readonly root: HTMLElement; + private view: EditorView; + private diagnostics: Diagnostic[] = []; + private deco: LineDecorations = {}; + private inline: boolean; + private opts: EditorOptions; + private readOnlyPart = new Compartment(); + + constructor(opts: EditorOptions = {}) { + this.opts = opts; + this.inline = opts.inlineMessages !== false; + this.root = el('div', { class: 'ed' + (opts.readOnly ? ' ed-ro' : '') + (opts.compact ? ' ed-compact' : '') }); + let hoverTimer: number | undefined; + const state = EditorState.create({ + doc: '', + extensions: [ + extrasField, lineDecorations, gutters(opts), highlighting(opts), + history(), bracketMatching(), search({ top: true }), highlightSelectionMatches(), + indentUnit.of(' '.repeat(opts.tabSize ?? 4)), EditorState.tabSize.of(opts.tabSize ?? 4), + keys(opts), + // the editable area has a name for a screen reader: which pane it is. tabindex 0 keeps it in the tab order when + // it is read-only too (CodeMirror then drops contenteditable), so the keyboard can always reach and scroll it + EditorView.contentAttributes.of({ 'aria-label': opts.lang ? `${LANG_NAMES[opts.lang]} editor` : 'Code editor', tabindex: '0' }), + opts.placeholder ? placeholder(opts.placeholder) : [], + this.readOnlyPart.of(opts.readOnly ? [EditorState.readOnly.of(true), EditorView.editable.of(false)] : []), + EditorView.updateListener.of((u) => { + // a change the app made to follow another pane (setSynced) is not the student typing: nothing is told + if (u.transactions.some((tr) => tr.docChanged && !tr.isUserEvent('sync'))) this.opts.onChange?.(u.state.doc.toString()); + if (u.selectionSet || u.docChanged) this.opts.onCursorLine?.(u.state.doc.lineAt(u.state.selection.main.head).number); + if (u.docChanged || u.selectionSet) tooltip.hide(); + }), + EditorView.domEventHandlers({ + mousemove: (e) => { clearTimeout(hoverTimer); hoverTimer = window.setTimeout(() => this.hover(e), 120); return false; }, + mouseleave: () => { clearTimeout(hoverTimer); tooltip.hide(); return false; }, + scroll: () => { tooltip.hide(); return false; }, + keydown: () => { tooltip.hide(); return false; }, + }), + ], + }); + this.view = new EditorView({ state, parent: this.root }); + } + + /** The word or symbol under the pointer, and its explanation if the reference has one. */ + private hover(e: MouseEvent): void { + const pos = this.view.posAtCoords({ x: e.clientX, y: e.clientY }, false); + if (pos == null) { tooltip.hide(); return; } + const line = this.view.state.doc.lineAt(pos); + const col = pos - line.from; + const text = line.text; + if (col < 0 || col >= text.length) { tooltip.hide(); return; } + const lineTokens = this.opts.tokenizeLines ? (this.opts.tokenizeLines(this.view.state.doc.toString())[line.number - 1] ?? []) : (this.opts.tokenize || ((l: string) => [{ text: l, cls: '' }]))(text); + let at = 0; let found: { text: string; cls: string } | null = null; + for (const t of lineTokens) { if (col >= at && col < at + t.text.length) { found = t; break; } at += t.text.length; } + if (!found || !found.text.trim()) { tooltip.hide(); return; } + let word = found.text; + let info: { title: string; body: string; where?: string } | null = null; + // English: the longest known phrase around the pointer wins over the single word under it + if (this.opts.lang === 'lingo') { + const words = text.split(/(\s+)/); + let p = 0; let idx = -1; + for (let i = 0; i < words.length; i++) { if (col >= p && col < p + words[i].length) { idx = i; break; } p += words[i].length; } + if (idx >= 0 && idx % 2 === 0) for (let span = 6; span >= 2 && !info; span--) for (let start = Math.max(0, idx - (span - 1) * 2); start <= idx && !info; start += 2) { + if (start + (span - 1) * 2 >= words.length) continue; + const phrase = words.slice(start, start + (span - 1) * 2 + 1).join('').replace(/[.,:;]+$/, ''); + info = explain('lingo', phrase, text); + if (info) word = phrase; + } + } + if (!info) info = this.opts.explainWord?.(word, text) || (this.opts.lang ? explain(this.opts.lang, word, text) : null); + if (!info) { tooltip.hide(); return; } + tooltip.show(e.clientX, e.clientY, info); + } + + get value(): string { return this.view.state.doc.toString(); } + set value(v: string) { + const cur = this.view.state.doc.toString(); + if (cur === v) return; + // loading text (opening a problem, Reset, a file) is not an edit: Ctrl+Z must not be able to undo the pane to empty + this.view.dispatch({ changes: { from: 0, to: cur.length, insert: v }, annotations: Transaction.addToHistory.of(false) }); + } + + /** + * Bring the text up to date with another pane, without disturbing this one: only the part that differs is + * replaced (so a cursor outside it, the scroll position and the selection stay where they are), no change is + * reported, and the update is its own undo step (the `sync` user event is not one that history joins to typing), + * so Ctrl+Z here undoes the sync and nothing the student typed elsewhere. + */ + setSynced(v: string): void { + const cur = this.view.state.doc.toString(); + if (cur === v) return; + let a = 0; + const max = Math.min(cur.length, v.length); + while (a < max && cur.charCodeAt(a) === v.charCodeAt(a)) a++; + let b = 0; + while (b < max - a && cur.charCodeAt(cur.length - 1 - b) === v.charCodeAt(v.length - 1 - b)) b++; + this.view.dispatch({ changes: { from: a, to: cur.length - b, insert: v.slice(a, v.length - b) }, userEvent: 'sync' }); + } + + focus(): void { this.view.focus(); } + + setReadOnly(ro: boolean): void { + this.view.dispatch({ effects: this.readOnlyPart.reconfigure(ro ? [EditorState.readOnly.of(true), EditorView.editable.of(false)] : []) }); + this.root.classList.toggle('ed-ro', ro); + } + + setDiagnostics(d: Diagnostic[]): void { this.diagnostics = d; this.push(); } + setInlineMessages(on: boolean): void { this.inline = on; this.push(); } + /** A partial update: keys you leave out keep their value; pass null to clear one. */ + setDecorations(d: LineDecorations): void { this.deco = { ...this.deco, ...d }; this.push(); } + private push(): void { this.view.dispatch({ effects: setExtras.of({ diagnostics: this.diagnostics, deco: this.deco, inline: this.inline }) }); } + + cursorLine(): number { return this.view.state.doc.lineAt(this.view.state.selection.main.head).number; } + + /** Apply a quick fix (1-based line and cols; endCol exclusive, null = to the end of the line). */ + applyFix(f: QuickFix): void { + const doc = this.view.state.doc; + if (f.line < 1 || f.line > doc.lines) return; + const line = doc.line(f.line); + const last = doc.line(Math.min(Math.max(f.endLine ?? f.line, f.line), doc.lines)); + const from = line.from + Math.max(0, f.col - 1); + const to = f.endCol == null ? last.to : last.from + Math.max(0, f.endCol - 1); + this.view.dispatch({ changes: { from: Math.min(from, line.to), to: Math.min(Math.max(to, from), last.to), insert: f.text } }); + } + + scrollToLine(line: number): void { + const doc = this.view.state.doc; + if (line < 1 || line > doc.lines) return; + this.view.dispatch({ effects: EditorView.scrollIntoView(doc.line(line).from, { y: 'nearest', yMargin: 48 }) }); + } + + /** Kept for callers that used to force a repaint; CodeMirror repaints itself. */ + render(): void { this.view.requestMeasure(); } + + destroy(): void { this.view.destroy(); } +} + diff --git a/src/ui/embed.ts b/src/ui/embed.ts new file mode 100644 index 0000000..3f20bef --- /dev/null +++ b/src/ui/embed.ts @@ -0,0 +1,230 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +/** + * Embed mode: one view, no chrome, sized for an `; + // the Quarto extension's shortcode for the same state: this layout, panes, build and step, on any page + const title = this.session.state.title || PROBLEMS.find((p) => p.id === this.session.state.problem)?.title; + // the title comes from the state, which anyone can write: it must not end the shortcode in the author's page + const titled = title && shortcodeTitle(title) ? ` title="${shortcodeTitle(title)}"` : ''; + const shortcode = view === 'playground' + ? `{{< pplus-playground state="${blob}" height="${tall}"${titled} >}}` + : `{{< pplus-embed state="${blob}" view="${view}"${titled} >}}`; + add(embedRow, el('label', {}, 'embed'), el('input', { class: 'input mono', readOnly: true, value: snippet }), button('Copy', async (e) => { await copyText(snippet); (e.target as HTMLButtonElement).textContent = 'Copied'; }, { class: 'btn btn-small' })); + add(quartoRow, el('label', {}, 'Quarto'), el('input', { class: 'input mono', readOnly: true, value: shortcode }), button('Copy', async (e) => { await copyText(shortcode); (e.target as HTMLButtonElement).textContent = 'Copied'; }, { class: 'btn btn-small' }), + el('a', { class: 'small', href: '#/quarto', target: '_blank', rel: 'noopener', title: 'Every shortcode of the Quarto extension, and the views it renders into a page' }, 'more ways ↗')); + }; + embedView.addEventListener('change', renderEmbed); + renderEmbed(); + add(dlg, el('h3', {}, 'Share this exact state'), + el('p', { class: 'small muted' }, `${blob.length} characters in the link. The link carries every pane, the call, the setup, the chosen language, the layout, and the step you are on.`), + row('open in Programming+', appLink), + this.session.provenance() || this.session.compileBadge() + ? el('div', { class: 'share-row' }, el('label', {}, 'the Mojo'), el('span', { class: 'share-badges' }, ...mojoBadges(this.session)), + el('span', { class: 'small muted' }, this.session.provenance() ? 'The label stays with the Mojo wherever it is shown. ' : '', 'Compile results stay in this browser: a link never carries them.')) : null, + el('div', { class: 'share-row' }, el('label', {}, 'embed which view'), embedView), + embedRow, + quartoRow, + el('div', { class: 'share-row' }, el('label', {}, 'as a file'), el('span', { class: 'small muted' }, `${this.fileName()} holds the same state; Open… loads it back, here or on another machine.`), button('Download', () => this.download(withVersions.checked), { class: 'btn btn-small' })), + this.session.versions().length ? el('div', { class: 'share-row' }, el('label', {}, 'versions'), el('label', { class: 'small' }, withVersions, ` Include my ${this.session.versions().length} saved version${this.session.versions().length === 1 ? '' : 's'} in the file (a link never carries them)`)) : null, + el('div', { class: 'share-actions' }, button('Close', () => dlg.close(), { class: 'btn' }))); + document.body.appendChild(dlg); + dlg.addEventListener('close', () => dlg.remove()); + dlg.showModal(); + } + + /* ---------- hooks for the views ---------- */ + + private hooks(): PanelHooks { + return { + reveal: (lang, line) => { + this.setNarrow('code'); + if (lang !== this.session.state.lang) { this.session.setLang(lang); this.showPane(lang); } + const ed = this.editors.get(lang)!; + ed.scrollToLine(line); + ed.setDecorations({ linked: new Set([line]) }); + setTimeout(() => ed.setDecorations({ linked: undefined }), 1200); + }, + fix: (lang, f: QuickFix) => { this.editors.get(lang)!.applyFix(f); }, + }; + } +} diff --git a/src/ui/splitter.ts b/src/ui/splitter.ts new file mode 100644 index 0000000..bc88fd7 --- /dev/null +++ b/src/ui/splitter.ts @@ -0,0 +1,40 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +/** A draggable divider between two grid tracks. Fractions persist through `onChange`; `start` restores a + * saved fraction, while double-click still resets to `initial`. */ +import { el } from './dom.js'; + +export function splitter(opts: { container: HTMLElement; axis: 'x' | 'y'; initial: number; start?: number; min?: number; max?: number; onChange: (fraction: number) => void; apply: (fraction: number) => void }): HTMLElement { + const bar = el('div', { class: `splitter splitter-${opts.axis}`, role: 'separator', 'aria-orientation': opts.axis === 'x' ? 'vertical' : 'horizontal', tabIndex: 0, title: 'Drag to resize; double-click to reset' }); + let f = opts.start ?? opts.initial; + const clamp = (v: number) => Math.min(opts.max ?? 0.85, Math.max(opts.min ?? 0.15, v)); + // a focusable separator is a widget: it says where it stands, as a percentage + bar.setAttribute('aria-valuemin', String(Math.round((opts.min ?? 0.15) * 100))); + bar.setAttribute('aria-valuemax', String(Math.round((opts.max ?? 0.85) * 100))); + bar.setAttribute('aria-label', 'Resize'); + const applied = opts.apply; + opts = { ...opts, apply: (v) => { bar.setAttribute('aria-valuenow', String(Math.round(v * 100))); applied(v); } }; + opts.apply(f); + bar.addEventListener('pointerdown', (e) => { + e.preventDefault(); + bar.setPointerCapture(e.pointerId); + bar.classList.add('dragging'); + document.body.classList.add('resizing', `resizing-${opts.axis}`); + const move = (ev: PointerEvent) => { + const r = opts.container.getBoundingClientRect(); + f = clamp(opts.axis === 'x' ? (ev.clientX - r.left) / r.width : (ev.clientY - r.top) / r.height); + opts.apply(f); + }; + const stop = () => { bar.classList.remove('dragging'); document.body.classList.remove('resizing', `resizing-${opts.axis}`); bar.removeEventListener('pointermove', move); bar.removeEventListener('pointerup', stop); bar.removeEventListener('pointercancel', stop); opts.onChange(f); }; + bar.addEventListener('pointermove', move); + bar.addEventListener('pointerup', stop); + bar.addEventListener('pointercancel', stop); + }); + bar.addEventListener('dblclick', () => { f = opts.initial; opts.apply(f); opts.onChange(f); }); + bar.addEventListener('keydown', (e) => { + const step = 0.02; + if ((opts.axis === 'x' && e.key === 'ArrowLeft') || (opts.axis === 'y' && e.key === 'ArrowUp')) { f = clamp(f - step); opts.apply(f); opts.onChange(f); e.preventDefault(); } + if ((opts.axis === 'x' && e.key === 'ArrowRight') || (opts.axis === 'y' && e.key === 'ArrowDown')) { f = clamp(f + step); opts.apply(f); opts.onChange(f); e.preventDefault(); } + }); + return bar; +} diff --git a/src/ui/stepkinds.ts b/src/ui/stepkinds.ts new file mode 100644 index 0000000..733b292 --- /dev/null +++ b/src/ui/stepkinds.ts @@ -0,0 +1,38 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +/** + * One palette for what a step does, shared by the pseudo and Mojo interpreters' + * traces (each records a `kind` on every step) so that the trace table, the + * "next" box, the table of values and the legend all say the same thing with + * the same color. + */ +export type StepFamily = 'write' | 'decision' | 'loop' | 'call' | 'return' | 'io' | 'life' | 'error' | 'other'; + +const FAMILY: Record = { + // pseudo (src/engines/pseudo/interp.js) + assign: 'write', declare: 'write', builtin: 'write', expr: 'write', + test: 'decision', select: 'decision', check: 'decision', + next: 'loop', break: 'loop', continue: 'loop', 'loop-start': 'loop', 'loop-test': 'loop', 'loop-end': 'loop', pass: 'loop', passes: 'loop', + call: 'call', return: 'return', + input: 'io', output: 'io', + error: 'error', + // Mojo (src/mojo/interp.ts) + stmt: 'write', loop: 'loop', + raise: 'error', except: 'error', destroy: 'life', +}; + +export const FAMILY_LABEL: Record = { + write: 'writes a value', decision: 'decides (a test)', loop: 'loop control', call: 'enters a routine', return: 'returns', io: 'input or output', life: 'a value is destroyed', error: 'raises or fails', other: 'other', +}; + +/** A Mojo `stmt` that prints is really output; a step that writes nothing and tests nothing is "other". */ +export function familyOf(step: { kind?: string; text?: string; writes?: unknown[] } | null | undefined, lang?: string): StepFamily { + if (!step) return 'other'; + const k = step.kind ?? ''; + if (lang === 'mojo' && k === 'stmt' && /^\s*print\s*\(/.test(step.text ?? '')) return 'io'; + if (lang === 'mojo' && k === 'stmt' && /^\s*input\s*\(|=\s*input\s*\(/.test(step.text ?? '')) return 'io'; + if (lang === 'mojo' && k === 'stmt' && !(step.writes?.length)) return 'other'; + return FAMILY[k] ?? 'other'; +} + +export const FAMILIES: StepFamily[] = ['write', 'decision', 'loop', 'call', 'return', 'io', 'life', 'error']; diff --git a/src/ui/theme.ts b/src/ui/theme.ts new file mode 100644 index 0000000..ab08d50 --- /dev/null +++ b/src/ui/theme.ts @@ -0,0 +1,71 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +/** Light, dark, or follow the system. Stored in this browser; `?theme=` on an embed wins. */ +export type Theme = 'light' | 'dark' | 'system'; +const KEY = 'pplus.theme'; + +/** + * The class the course stylesheets read (styles/course/README.md): they draw dark on `body.quarto-dark`, and + * follow the operating system only when the body has neither class. The app always says which, so a light app + * on a dark system never draws dark widgets. `forced` is a host page's choice (an embed's `?theme=`, or the + * Quarto extension's switch), which wins over the setting. + */ +export function themeBodyClass(setting: Theme, systemDark: boolean, forced: 'light' | 'dark' | null = null): 'quarto-light' | 'quarto-dark' { + const shown = forced ?? (setting === 'system' ? (systemDark ? 'dark' : 'light') : setting); + return shown === 'dark' ? 'quarto-dark' : 'quarto-light'; +} + +let forced: 'light' | 'dark' | null = null; + +const systemDark = (): boolean => { try { return matchMedia('(prefers-color-scheme: dark)').matches; } catch { return false; } }; + +/** Put exactly one of `quarto-light` or `quarto-dark` on ``, matching what the page shows. */ +export function syncBodyTheme(): void { + const body = typeof document !== 'undefined' ? document.body : null; + if (!body) return; + const want = themeBodyClass(currentTheme(), systemDark(), forced); + body.classList.toggle('quarto-dark', want === 'quarto-dark'); + body.classList.toggle('quarto-light', want === 'quarto-light'); +} + +let watching = false; +/** Keep the body class right from now on: once at load, and whenever the system preference changes. */ +export function watchTheme(): void { + syncBodyTheme(); + if (watching) return; + watching = true; + try { matchMedia('(prefers-color-scheme: dark)').addEventListener('change', syncBodyTheme); } catch { /* an old browser: the class follows the next change made here */ } +} + +export function currentTheme(): Theme { + try { const t = localStorage.getItem(KEY); if (t === 'light' || t === 'dark') return t; } catch { /* ignore */ } + return 'system'; +} + +export function applyTheme(t: Theme): void { + const root = document.documentElement; + forced = null; + if (t === 'system') root.removeAttribute('data-theme'); else root.setAttribute('data-theme', t); + try { if (t === 'system') localStorage.removeItem(KEY); else localStorage.setItem(KEY, t); } catch { /* ignore */ } + syncBodyTheme(); +} + +/** What the page is showing right now, resolving "system" (and a host page's forced choice). */ +export function effectiveTheme(): 'light' | 'dark' { + if (forced) return forced; + const t = currentTheme(); + if (t !== 'system') return t; + return systemDark() ? 'dark' : 'light'; +} + +export function cycleTheme(): Theme { + const next: Theme = effectiveTheme() === 'dark' ? 'light' : 'dark'; + applyTheme(next); + return next; +} + +export function forceTheme(t: 'light' | 'dark'): void { + forced = t; + document.documentElement.setAttribute('data-theme', t); + syncBodyTheme(); +} diff --git a/src/ui/tooltip.ts b/src/ui/tooltip.ts new file mode 100644 index 0000000..33dc309 --- /dev/null +++ b/src/ui/tooltip.ts @@ -0,0 +1,28 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +/** One shared tooltip for hover explanations, positioned near the pointer. */ +import { el, clear, add } from './dom.js'; + +class Tooltip { + private node: HTMLElement | null = null; + private ensure(): HTMLElement { + if (!this.node) { this.node = el('div', { class: 'tip', role: 'tooltip', style: { display: 'none' } }); document.body.appendChild(this.node); } + return this.node; + } + show(x: number, y: number, info: { title: string; body: string; where?: string }): void { + const n = this.ensure(); + clear(n); + add(n, el('div', { class: 'tip-title' }, el('code', {}, info.title), info.where ? el('span', { class: 'tip-where' }, info.where) : null), el('div', { class: 'tip-body' }, info.body)); + n.style.display = ''; + const w = Math.min(380, window.innerWidth - 24); + n.style.maxWidth = `${w}px`; + const left = Math.min(x + 14, window.innerWidth - w - 12); + n.style.left = `${Math.max(8, left)}px`; + n.style.top = `${y + 18}px`; + const r = n.getBoundingClientRect(); + if (r.bottom > window.innerHeight - 8) n.style.top = `${Math.max(8, y - r.height - 10)}px`; + } + hide(): void { if (this.node) this.node.style.display = 'none'; } +} + +export const tooltip = new Tooltip(); diff --git a/src/ui/views/compiler.ts b/src/ui/views/compiler.ts new file mode 100644 index 0000000..8336a01 --- /dev/null +++ b/src/ui/views/compiler.ts @@ -0,0 +1,265 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +/** + * The Compiler view: what the real Mojo compiler made of the Mojo pane. + * Everything here is godbolt's answer, kept by the session with exactly the + * source, input, and build it answered; an edit since is said, not hidden. + * + * output what the program printed, its input, and how it ended + * messages the compiler's errors and notes, each a link to its line + * listing the instructions, one block per function: the student's own + * functions first, the runtime and the standard library folded + * away; Intel syntax (what the x86-64 pane reads) or godbolt's + * AT&T original; and "Open in Hardware" to step one. + */ +import { el, clear, add, button } from '../dom.js'; +import type { Session, CompileRecord } from '../../core/session.js'; +import type { AsmLine, BuildLevel, ListingFunction } from '#core/services/godbolt.js'; +import { intelListing } from '#core/mojo/att.js'; +import { tokenizeAsm } from '#core/services/asm.js'; +import { MOJO_BUILD_ARGS, MOJO_VERSION } from '#core/mojo/generated/pin.js'; +import { compileBackend } from '#core/services/compile-backend.js'; +import { confirmSend, sendNotice } from '../consent.js'; +import type { PanelHooks } from './panels.js'; +import { generatedLabel } from '../provenance.js'; +import { inputNote } from '../../core/inputnote.js'; + +/** + * How every build is asked for, and why, for the tooltip on a compile's summary line (core's docs/trust.md has the + * whole account). The arguments come from the pin, so this text cannot name others than the request sends. + */ +export const HOW_BUILT = `Every build here uses ${MOJO_BUILD_ARGS}: for an x86-64 machine with AVX2, so the listing is the same whichever machine compiles it, and with a multiply never fused with an add, so a decimal result is the one the Run view shows. "mojo build" on your own computer targets its own processor and may fuse, so its listing and its last digit can differ.`; + +export interface CompilerHooks extends PanelHooks { + /** Put one function (and the user's functions it calls) in the x86-64 pane. */ + sendToAsm(functions: ListingFunction[], fn: ListingFunction): void; + /** Compile & run: shows the kept answer when the source, input and build level are unchanged, and asks otherwise. */ + compile(): void; + /** Ask the compiler again even though this browser has its answer for exactly this work. */ + askAgain?(): void; +} + +let syntax: 'intel' | 'att' = 'intel'; +/** By function (the listing's order) or by line (each Mojo line, then the instructions it became). */ +let layout: 'line' | 'function' = 'line'; +/** Whether to show the other build level's listing beside this one. */ +let compare = false; +/** The Mojo pane's cursor line, and the view to show it in: its instructions are highlighted. */ +let cursorLine: number | null = null; +let liveRoot: HTMLElement | null = null; +export function focusCompilerLine(line: number): void { + cursorLine = line; + if (!liveRoot) return; + let first: HTMLElement | null = null; + for (const g of liveRoot.querySelectorAll('[data-line]')) { + const on = Number(g.dataset.line) === line; + g.classList.toggle('asm-group-active', on); + if (on && !first) first = g; + } + first?.scrollIntoView({ block: 'nearest' }); +} + +/** The standard-library functions a function calls: what the x86-64 pane cannot run. */ +export function libraryCalls(fn: ListingFunction): string[] { + const out = new Set(); + for (const l of fn.lines) { + const m = /^\s*callq?\s+\*?(?:"((?:[^"\\]|\\.)*)"|(\S+))/.exec(l.text); + const raw = m && (m[1] ?? m[2]); + if (!raw || raw.startsWith('example::') || raw.startsWith('.L') || raw.startsWith('%')) continue; + const path = raw.replace(/@PLT$/, '').replace(/[\[(].*$/, '').split('::').filter(Boolean); + if (!path.length) continue; + const name = path[path.length - 1]; + out.add(path.length > 1 ? `${name} (${path.slice(0, -1).join('.')})` : name); + } + return [...out]; +} + +/** + * One function's instructions under the Mojo lines they came from, in source order. An instruction + * with no line of the program's own (inlined from the standard library, or with no line at all) + * stays with the line before it, counted as inlined. + */ +function byLine(fn: ListingFunction, rec: CompileRecord, hooks: CompilerHooks, fresh: boolean): HTMLElement { + const src = rec.source.split('\n'); + const groups = new Map; inlined: number }>(); + const rows = intelListing(fn, rec.functions); + let current: number | null = null; + rows.forEach((r, i) => { + const l = fn.lines[i]; + if (l.line != null) current = l.line; + if (current == null) return; + if (!groups.has(current)) groups.set(current, { lines: [], intel: [], inlined: 0 }); + const g = groups.get(current)!; + g.lines.push(l); g.intel.push(r.intel); + if (l.line == null && r.intel && !r.intel.endsWith(':')) g.inlined++; + }); + const box = el('div', { class: 'asm-bylines' }); + for (const [line, g] of [...groups].sort((a, b) => a[0] - b[0])) { + const n = g.intel.filter((t) => t && !t.endsWith(':')).length; + const head = el('div', { class: 'asm-group-head' }, + el('button', { type: 'button', class: 'linkish mono', disabled: !fresh, onClick: () => hooks.reveal('mojo', line) }, `line ${line}`), + el('code', { class: 'asm-group-src' }, (src[line - 1] ?? '').trim()), + el('span', { class: 'spacer' }), + el('span', { class: 'small muted' }, `${n} instruction${n === 1 ? '' : 's'}${g.inlined ? `, ${g.inlined} inlined from the standard library` : ''}`)); + add(box, el('div', { class: `asm-group${cursorLine === line ? ' asm-group-active' : ''}`, 'data-line': String(line) }, head, asmPre(g.lines, syntax === 'intel' ? g.intel : null, null))); + } + if (!groups.size) add(box, el('p', { class: 'muted small' }, 'No instruction here carries a line of your program.')); + return box; +} + +function asmPre(lines: AsmLine[], intel: Array | null, reveal: ((line: number) => void) | null): HTMLElement { + const pre = el('pre', { class: 'compile-asm' }); + const withLines = lines.some((l) => l.line != null || l.from); + lines.forEach((l, i) => { + const text = intel ? intel[i] : l.text.trim(); + if (text == null) return; + if (withLines) { + if (l.line != null) add(pre, reveal + ? el('button', { type: 'button', class: 'asm-src linkish', title: `from line ${l.line} of the Mojo pane; click to show it`, onClick: () => reveal(l.line!) }, String(l.line).padStart(4) + ' ') + : el('span', { class: 'asm-src', title: `from line ${l.line} (an earlier version of the program)` }, String(l.line).padStart(4) + ' ')); + else add(pre, el('span', { class: 'asm-src asm-src-lib', title: l.from ? `inlined from ${l.from.file}, line ${l.from.line}: standard library code, not a line of your program` : '' }, l.from ? ' · ' : ' ')); + } + const isLabel = /:$/.test(text); + const shown = isLabel ? text : ' ' + text; + if (intel) for (const t of tokenizeAsm(shown)) add(pre, t.cls ? el('span', { class: t.cls }, t.text) : t.text); + else add(pre, shown); + add(pre, '\n'); + }); + return pre; +} + +function functionBlock(fn: ListingFunction, rec: CompileRecord, hooks: CompilerHooks, open: boolean, fresh: boolean): HTMLElement { + const rows = intelListing(fn, rec.functions); + const det = el('details', { class: `asm-fn asm-fn-${fn.kind}`, open }, + el('summary', {}, el('code', {}, fn.name), el('span', { class: 'muted small' }, ` ${fn.lines.filter((l) => !/:\s*$/.test(l.text)).length} instructions`))); + const actions = el('div', { class: 'asm-fn-actions' }); + const calls = fn.kind === 'user' ? libraryCalls(fn) : []; + if (fn.kind === 'user') add(actions, button('Open in Hardware', () => hooks.sendToAsm(rec.functions, fn), { class: 'btn btn-small', title: calls.length ? `Step this function on the model machine. It calls ${calls.join(', ')}: standard-library code the model machine cannot run, so it stops there.` : 'Step this function on the model machine.' })); + if (calls.length) add(actions, el('span', { class: 'small muted' }, `calls into the standard library: ${calls.join(', ')}. The model machine stops at those.`)); + const withLines = fn.lines.some((l) => l.line != null); + add(det, actions, fn.kind === 'user' && layout === 'line' && withLines ? byLine(fn, rec, hooks, fresh) : asmPre(fn.lines, syntax === 'intel' ? rows.map((r) => r.intel) : null, fresh ? (line) => hooks.reveal('mojo', line) : null)); + return det; +} + +/** Each of the program's functions at both build levels, side by side, with their instruction counts. */ +function comparison(rec: CompileRecord, other: CompileRecord | null, pending: boolean): HTMLElement { + const box = el('div', { class: 'build-compare' }); + if (!other) { add(box, el('p', { class: 'muted small' }, pending ? 'Compiling the other build…' : 'The other build has not been compiled for this source yet.')); return box; } + const [o0, opt] = rec.level === 'O0' ? [rec, other] : [other, rec]; + const count = (f: ListingFunction | undefined) => (f ? f.lines.filter((l) => !/:\s*$/.test(l.text)).length : 0); + const users = [...new Set([...o0.functions, ...opt.functions].filter((f) => f.kind === 'user').map((f) => f.name))]; + add(box, el('p', { class: 'small muted' }, 'The same source, built as written (-O0) and optimized. What the optimizer keeps, merges, or removes is the point: a function absent from the optimized build was inlined into its callers, or computed away.')); + for (const name of users) { + const a = o0.functions.find((f) => f.name === name), b = opt.functions.find((f) => f.name === name); + // the student's main() gone from the optimized build: the program's entry point absorbed it + const entry = !b && name === 'main()' ? opt.functions.find((f) => f.label === 'main' || f.name === 'main') : undefined; + const col = (f: ListingFunction | undefined, recd: CompileRecord, label: string, note?: string) => el('div', { class: 'build-col' }, + el('div', { class: 'small' }, el('b', {}, label), ' ', el('span', { class: 'muted' }, f ? `${count(f)} instructions${note ? `: ${note}` : ''}` : 'not in this build')), + f ? asmPre(f.lines, syntax === 'intel' ? intelListing(f, recd.functions).map((r) => r.intel) : null, null) : el('p', { class: 'muted small' }, 'Inlined into its callers, or computed away.')); + add(box, el('div', { class: 'build-pair' }, el('code', {}, name), el('div', { class: 'build-cols' }, + col(a, o0, '-O0'), + entry ? col(entry, opt, 'optimized', 'main() is not a function of its own here; it, and what it calls, were inlined into the program\'s entry point, main') : col(b, opt, 'optimized')))); + } + return box; +} + +export function compilerView(session: Session, root: HTMLElement, hooks: CompilerHooks): () => void { + liveRoot = root; + function render() { + clear(root); + const last = session.lastCompile(); + const head = el('div', { class: 'compile-head' }); + add(root, head); + // the compiler's answer is about the source it was sent; if that source was generated, say so beside it + const kind = session.provenance(); + if (kind) add(head, generatedLabel(kind)); + if (session.compiling) { + add(head, el('span', { class: 'badge badge-open' }, 'compiling'), el('span', { class: 'small muted' }, `Asking ${compileBackend().host} (${compileBackend().compiler}) to build and run the Mojo pane…`)); + if (!last) { + const lines = session.inputLines(); + const note = inputNote(session.source('mojo'), lines.join('\n')); + if (note) add(root, el('p', { class: 'hint compile-input-note' }, note)); + return; + } + } + if (!last) { + add(head, el('span', { class: 'small muted' }, 'Not compiled yet.'), el('span', { class: 'spacer' }), button('Compile & run', () => hooks.compile(), { class: 'btn btn-small' })); + add(root, el('p', { class: 'muted' }, `Compile & run (Ctrl+Enter) builds the Mojo pane with the real Mojo ${MOJO_VERSION} compiler on ${compileBackend().host}, runs it, and shows here what it printed, what the compiler said, and the instructions it produced. Programming+ ships no compiler of its own and never says a program compiles without asking one. The stepper beside the editor goes through it line by line in Programming+'s own interpreter, and says so when it meets something it does not model yet.`), + el('p', { class: 'small compile-send-note' }, sendNotice())); + return; + } + const { record: rec, fresh } = last; + const o = rec.outcome; + const a = o.answer; + if (!session.compiling) { + const badge = !a ? ['badge-broken', 'no answer'] : !a.compiled ? ['badge-broken', 'did not compile'] : a.timedOut ? ['badge-broken', 'timed out'] : !a.executed ? ['badge-open', 'compiled, did not run'] : a.exitCode === 0 ? ['badge-proved', 'ran, exit 0'] : ['badge-broken', `exited with ${a.exitCode}`]; + add(head, el('span', { class: `badge ${badge[0]}` }, badge[1]), + el('span', { class: 'small muted', title: HOW_BUILT }, `Mojo ${MOJO_VERSION} on ${rec.host ?? 'godbolt.org'} · ${rec.level === 'O0' ? 'as written (-O0)' : 'optimized'} · ${MOJO_BUILD_ARGS} · ${o.seconds.toFixed(1)} s`), + el('span', { class: 'spacer' }), button('Compile again', () => hooks.compile(), { class: 'btn btn-small btn-quiet' })); + } + if (!fresh) add(root, el('p', { class: 'hint' }, 'You have edited the Mojo pane since this answer; it is the answer for the earlier version. Compile again to see the current one.')); + else if (!session.compiling && session.reusedCompile() === rec) add(root, el('p', { class: 'hint compile-kept' }, + `Nothing was sent: the source, the input and the build level are the ones ${rec.host ?? 'godbolt.org'} answered on ${new Date(rec.at).toLocaleString('en-US')}, so this is that answer, kept in this browser. `, + hooks.askAgain ? button('Ask again', () => hooks.askAgain!(), { class: 'btn btn-small', title: `Send the same program to ${rec.host ?? 'godbolt.org'} again (a program that reads the clock or draws random numbers may answer differently)` }) : null)); + if (!a) { add(root, el('p', { class: 'compile-err' }, o.error || 'No answer.')); return; } + + // output + const out = el('section', { class: 'compile-section' }, el('h4', {}, 'Output')); + if (rec.stdin) add(out, el('div', { class: 'small muted' }, 'input: ', el('code', {}, rec.stdin.replace(/\n$/, '').split('\n').join(' ⏎ ')))); + // Mojo 1.2.0's input() and a pipe: why the compiler's run may stop with EOF where the Run view does not + const note = inputNote(rec.source, rec.stdin); + if (note) add(out, el('p', { class: 'hint compile-input-note' }, note)); + if (a.executed) add(out, el('pre', { class: 'compile-std' }, a.stdout || '(no output)')); + else add(out, el('p', { class: 'muted small' }, a.compiled ? 'The program was built but not run.' : 'Nothing ran: the program did not compile.')); + if (a.stderr.trim()) add(out, el('pre', { class: 'compile-err' }, a.stderr.trim())); + add(root, out); + + // messages + if (rec.diagnostics.length) { + const sec = el('section', { class: 'compile-section' }, el('h4', {}, 'What the compiler said')); + const list = el('ul', { class: 'problems' }); + for (const d of rec.diagnostics) add(list, el('li', { class: `problem problem-${d.severity}` }, + el('button', { type: 'button', class: 'linkish mono', onClick: () => hooks.reveal('mojo', d.line), disabled: !fresh }, `line ${d.line}`), + el('span', { class: 'problem-msg' }, `${d.severity}: ${d.message}`), + d.fix && fresh ? button(d.fix.label, () => hooks.fix('mojo', d.fix!), { class: 'btn btn-small' }) : null, + ...(d.question && fresh ? d.question.options.map((opt) => button(opt.label, () => hooks.fix('mojo', opt), { class: 'btn btn-small btn-option' })) : []))); + add(sec, list); + add(root, sec); + } + + // listing + if (a.compiled && rec.functions.length) { + const sec = el('section', { class: 'compile-section' }); + const toggle = button(syntax === 'intel' ? 'Show AT&T (as godbolt sent it)' : 'Show Intel (as the x86-64 pane reads it)', () => { syntax = syntax === 'intel' ? 'att' : 'intel'; render(); }, { class: 'btn btn-small btn-quiet' }); + const other: BuildLevel = rec.level === 'O0' ? 'default' : 'O0'; + const otherRec = session.compileAt(rec.source, other); + const cmp = button(compare ? 'Hide the other build' : `Compare with ${other === 'O0' ? '-O0 (as written)' : 'the optimized build'}`, () => { + compare = !compare; + if (compare && !otherRec && fresh) void confirmSend().then((ok) => { if (ok) void session.compile(undefined, other).then(() => render()); }); + render(); + }, { class: 'btn btn-small btn-quiet', disabled: !fresh && !otherRec, title: 'Compile the same source at the other level, and show each function at both' }); + const arrange = button(layout === 'line' ? 'In listing order' : 'By Mojo line', () => { layout = layout === 'line' ? 'function' : 'line'; render(); }, { class: 'btn btn-small btn-quiet', title: 'By Mojo line: each line of your program, then the instructions it became. Move the cursor in the Mojo pane to find a line here.' }); + add(sec, el('div', { class: 'compile-head' }, el('h4', {}, 'What the processor runs'), el('span', { class: 'spacer' }), cmp, arrange, toggle)); + if (compare) add(sec, comparison(rec, otherRec, session.compiling !== null)); + const user = rec.functions.filter((f) => f.kind === 'user'); + const rest = rec.functions.filter((f) => f.kind !== 'user' && f.kind !== 'data'); + if (!user.length) add(sec, el('p', { class: 'hint' }, rec.level === 'default' + ? 'The optimizer folded your functions into main, so none of them has instructions of its own here. Build "as written" in the toolbar to see each one.' + : 'None of the instructions are labeled as your functions.')); + user.forEach((f, i) => add(sec, functionBlock(f, rec, hooks, i < 3, fresh))); + if (rest.length) { + const lib = el('details', { class: 'asm-library' }, el('summary', {}, `The runtime and the standard library (${rest.length} function${rest.length === 1 ? '' : 's'})`)); + add(lib, el('p', { class: 'muted small' }, 'main is the entry point the runtime calls; it sets up the runtime and calls your main. The rest is standard library code compiled into the program: print, String, and what they use.')); + for (const f of rest) add(lib, functionBlock(f, rec, hooks, false, fresh)); + add(sec, lib); + } + add(sec, el('p', { class: 'muted small' }, syntax === 'intel' + ? 'Shown in Intel syntax, translated from godbolt\'s AT&T listing: the destination comes first. The number before an instruction is the line of your program it came from (click it); a dot marks code inlined from the standard library. Lines the x86-64 pane does not model are still shown; it refuses them when you send them there.' + : 'AT&T syntax, exactly as godbolt sent it: the destination comes last, registers start with %, constants with $.')); + add(root, sec); + } + } + const off = session.onChange(render); + render(); + return () => { off(); if (liveRoot === root) liveRoot = null; }; +} diff --git a/src/ui/views/lifetimes.ts b/src/ui/views/lifetimes.ts new file mode 100644 index 0000000..9937721 --- /dev/null +++ b/src/ui/views/lifetimes.ts @@ -0,0 +1,77 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +/** + * The Lifetimes view (Stage 4): one row per value whose lifecycle can be seen, + * from the step it is made to the step it is destroyed or moved out of, with + * each copy, move, and naming on the way. It reads the lifecycle events the + * interpreter records on its steps (src/mojo/interp.ts, LifeEvent), so what it + * shows is when the compiled program does these things: a value dies at its + * last use, a move makes a new value from the old one, which ends there. + * + * Click a mark to step there; the cursor is where the stepper is. + */ +import { el, clear, add } from '../dom.js'; +import type { Session } from '../../core/session.js'; + +interface Row { id: number; label: string; names: string[]; start: number; end: number | null; endKind: 'destroyed' | 'moved' | null; movedTo?: number; from?: number; how: 'made' | 'copied' | 'moved'; marks: Array<{ step: number; kind: string; text: string }> } + +export function lifetimesView(session: Session, root: HTMLElement, opts: { goto?: (t: number) => void } = {}): () => void { + const render = () => { + clear(root); + const trace = session.trace(); + if (!trace) { add(root, el('p', { class: 'muted' }, session.runError ?? 'Step through the Mojo pane to see its values\' lifetimes here.')); return; } + if (trace.lang !== 'mojo') { add(root, el('p', { class: 'muted' }, 'Lifetimes are shown for Mojo runs: when each value is made, copied, moved, and destroyed.')); return; } + const steps = trace.steps as any[]; + const rows = new Map(); + steps.forEach((s, i) => { + for (const e of s.life ?? []) { + if (e.kind === 'made' || e.kind === 'copied' || e.kind === 'moved') { + rows.set(e.id, { id: e.id, label: e.label, names: [], start: i, end: null, endKind: null, from: e.from, how: e.kind, marks: [{ step: i, kind: e.kind, text: e.kind === 'made' ? `made: ${e.label}` : `${e.kind} from #${e.from}` }] }); + if (e.kind === 'moved' && e.from && rows.has(e.from)) { const old = rows.get(e.from)!; old.end = i; old.endKind = 'moved'; old.movedTo = e.id; old.marks.push({ step: i, kind: 'moved-out', text: `moved into #${e.id}` }); } + } else if (e.kind === 'named') { + const r = rows.get(e.id); if (r && !r.names.includes(e.name)) { r.names.push(e.name); r.marks.push({ step: i, kind: 'named', text: `named ${e.name}` }); } + } else if (e.kind === 'destroyed') { + const r = rows.get(e.id); if (r) { r.end = i; r.endKind = 'destroyed'; r.marks.push({ step: i, kind: 'destroyed', text: `destroyed (line ${s.line})` }); } + } + } + }); + if (!rows.size) { + add(root, el('p', { class: 'muted' }, 'No value in this run has a lifecycle that can be seen. Give a struct a __deinit__ (or a copy or move constructor) that prints, and each of its values gets a row here: when it is made, copied, moved, and destroyed.')); + if (trace.error) add(root, el('p', { class: 'small err' }, trace.error.message)); + return; + } + const n = Math.max(1, trace.count); + const t = Math.min(session.state.t ?? n, n); + add(root, el('p', { class: 'small muted' }, `One row per value. A move makes a new value from the old one, which ends there; a value is destroyed at its last use, not at the end of its scope.${opts.goto ? ' Click a mark to step there.' : ''}`)); + const table = el('div', { class: 'life' }); + for (const r of [...rows.values()].sort((a, b) => a.id - b.id)) { + const name = r.names.length ? r.names.join(', ') : 'temporary'; + const lane = el('div', { class: 'life-lane' }); + const left = (r.start / n) * 100, right = ((r.end ?? n) / n) * 100; + add(lane, el('div', { class: `life-bar life-bar-${r.how}${r.end === null ? ' life-bar-open' : ''}`, style: { left: `${left}%`, width: `${Math.max(0.6, right - left)}%` } })); + for (const m of r.marks) { + add(lane, el('button', { type: 'button', class: `life-mark life-mark-${m.kind}`, title: `step ${m.step + 1}: ${m.text}`, style: { left: `${(m.step / n) * 100}%` }, onClick: () => opts.goto?.(m.step + 1) })); + } + add(lane, el('div', { class: 'life-cursor', style: { left: `${(t / n) * 100}%` } })); + const ending = r.endKind === 'destroyed' ? 'destroyed' : r.endKind === 'moved' ? `moved into #${r.movedTo}` : 'alive at the end'; + const origin = r.how === 'made' ? 'made' : `${r.how} from #${r.from}`; + add(table, el('div', { class: 'life-row' }, + el('div', { class: 'life-name' }, el('span', { class: 'life-id' }, `#${r.id}`), ' ', el('b', { class: 'mono' }, name), el('div', { class: 'small muted mono' }, r.label)), + lane, + el('div', { class: 'life-sum small muted' }, `${origin} · ${ending}`))); + } + add(root, table); + add(root, el('div', { class: 'life-legend small muted' }, + el('span', { class: 'life-mark life-mark-made legend' }), ' made ', + el('span', { class: 'life-mark life-mark-copied legend' }), ' copied ', + el('span', { class: 'life-mark life-mark-moved legend' }), ' moved in ', + el('span', { class: 'life-mark life-mark-moved-out legend' }), ' moved out ', + el('span', { class: 'life-mark life-mark-named legend' }), ' named ', + el('span', { class: 'life-mark life-mark-destroyed legend' }), ' destroyed')); + if (trace.error) add(root, el('p', { class: 'small err' }, trace.error.message)); + }; + const off = session.onChange(render); + const offStep = session.onStep(render); + render(); + return () => { off(); offStep(); }; +} diff --git a/src/ui/views/panels.ts b/src/ui/views/panels.ts new file mode 100644 index 0000000..a4bf87e --- /dev/null +++ b/src/ui/views/panels.ts @@ -0,0 +1,179 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +/** + * The non-stepping views: problems (every diagnostic, with one-click + * rewrites), proof (obligations), and machine + * (the hardware model's perf-stat numbers for an assembly run). + */ +import { machineLabel } from '../../core/hardware.js'; +import { el, clear, add, button } from '../dom.js'; +import type { Diagnostic, LangId, QuickFix } from '#core/common/types.js'; +import { LANG_NAMES } from '#core/common/types.js'; +import type { Session } from '../../core/session.js'; +import { toMath } from '#core/services/speco.js'; + +export const GUIDE_URL = 'https://biosc1540.scient.ing/programmingplus/reference/pseudocode/'; + +export interface PanelHooks { + /** Jump the editor to a line of a language. */ + reveal(lang: LangId, line: number): void; + /** Apply a rewrite to a language's source. */ + fix(lang: LangId, f: QuickFix): void; +} + +const SEV_ICON: Record = { error: '●', warning: '▲', note: '○' }; + +export function problemsView(session: Session, root: HTMLElement, hooks: PanelHooks): () => void { + function render() { + clear(root); + const diags = session.allDiagnostics(); + if (!diags.length) { add(root, el('p', { class: 'muted' }, 'Nothing to report. The panes read cleanly.')); return; } + const list = el('ul', { class: 'problems' }); + for (const d of diags) { + const item = el('li', { class: `problem problem-${d.severity}` }); + add(item, + el('span', { class: 'problem-sev', title: d.severity }, SEV_ICON[d.severity]), + el('button', { type: 'button', class: 'linkish mono', onClick: () => hooks.reveal(d.lang, d.line) }, `${LANG_NAMES[d.lang]} ${d.line}`), + el('span', { class: 'problem-msg' }, d.message), + d.origin && d.severity === 'note' ? el('span', { class: 'problem-origin', title: 'Who says so' }, d.origin) : null, + ); + if (d.guide) add(item, el('a', { class: 'problem-guide', href: `${GUIDE_URL}#${d.guide}`, target: '_blank', rel: 'noopener' }, 'guide ↗')); + if (d.docUrl) add(item, el('a', { class: 'problem-guide', href: d.docUrl, target: '_blank', rel: 'noopener' }, 'manual ↗')); + if (d.fix) add(item, button(d.fix.label === 'Fix' ? `Fix: ${d.fix.text || 'remove'}` : d.fix.label, () => hooks.fix(d.lang, d.fix!), { class: 'btn btn-small' })); + if (d.question) { + const q = el('div', { class: 'problem-question' }, el('div', { class: 'problem-q' }, d.question.text)); + for (const o of d.question.options) add(q, button(o.label, () => hooks.fix(d.lang, o), { class: 'btn btn-small btn-option' })); + add(item, q); + } + add(list, item); + } + add(root, list); + } + const off = session.onChange(render); + render(); + return off; +} + +const STATUS_WORD: Record = { proved: 'proved', broken: 'broken by a run', open: 'open' }; + +export function proofView(session: Session, root: HTMLElement, hooks: PanelHooks): () => void { + function render() { + clear(root); + const pr = session.proof(); + if (!pr) { add(root, el('p', { class: 'muted' }, 'The proof view needs pseudocode that parses. Fix the errors in the problems view first.')); return; } + const { report } = pr; + const speco = session.parsedSpeco(); + if (speco && speco.program?.spec.units.length) add(root, el('p', { class: 'hint' }, `Proving against the ${speco.program.spec.units.length} SPEC${speco.program.spec.units.length === 1 ? '' : 'S'} in the speco pane, woven into the pseudocode.`)); + add(root, el('div', { class: 'proof-counts' }, + el('span', { class: 'badge badge-proved' }, `${report.counts.proved} proved`), + el('span', { class: 'badge badge-broken' }, `${report.counts.broken} broken`), + el('span', { class: 'badge badge-open' }, `${report.counts.open} open`), + )); + if (!report.counts.total) add(root, el('p', { class: 'muted' }, 'No claims to check. Add an ENSURE under a FUNCTION line, or a SPEC in the speco pane.')); + for (const u of report.units) { + const sec = el('details', { class: 'proof-unit', open: true }, el('summary', {}, el('b', {}, u.name), ` · ${u.obligations.length} claim${u.obligations.length === 1 ? '' : 's'}`, u.partial ? el('span', { class: 'badge badge-open' }, 'partial: not every path was examined') : null)); + if (u.inferred.length) add(sec, el('p', { class: 'muted small' }, 'Invariants the checker found on its own: ', ...u.inferred.map((x) => el('code', { class: 'math' }, toMath(String(x)), ' ')))); + for (const n of u.notes) add(sec, el('p', { class: 'muted small' }, n)); + const list = el('ul', { class: 'obligations' }); + for (const o of u.obligations) { + const where = (o as any).specoLine ? { lang: 'speco' as LangId, line: (o as any).specoLine } : { lang: 'pseudo' as LangId, line: (o as any).pseudoLine ?? o.line }; + const item = el('li', { class: `obligation ob-${o.status}` }, + el('span', { class: `badge badge-${o.status}` }, STATUS_WORD[o.status]), + el('button', { type: 'button', class: 'linkish mono', onClick: () => hooks.reveal(where.lang, where.line) }, `${LANG_NAMES[where.lang]} ${where.line}`), + el('span', {}, o.label), + ); + const det = el('details', { class: 'ob-detail' }, el('summary', {}, 'what is known, and what has to follow')); + if (o.facts.length) add(det, el('div', { class: 'small muted' }, 'Known:'), el('ul', { class: 'facts' }, ...o.facts.map((f) => el('li', { class: 'math' }, toMath(f))))); + add(det, el('div', { class: 'small muted' }, 'Must follow:'), el('div', { class: 'math goal' }, toMath(o.goal))); + if (o.reason) add(det, el('p', { class: 'small muted' }, o.reason)); + add(item, det); + add(list, item); + } + add(sec, list); + add(root, sec); + } + add(root, el('p', { class: 'small muted' }, 'Proved means: on every path the checker examined, the claim follows from what is known. Open means the checker could not finish the argument; usually a loop needs an invariant. Broken means a generated input violated it.')); + } + const off = session.onChange(render); + render(); + return off; +} + +export function machineView(session: Session, root: HTMLElement): () => void { + function render() { + clear(root); + const tr = session.state.lang === 'asm' || session.traceLang() === 'asm' ? session.trace() : null; + if (!tr || tr.lang !== 'asm') { add(root, el('p', { class: 'muted' }, 'The machine view shows the hardware model for an assembly run. Open the x86-64 pane.')); return; } + let perf: any; + try { perf = (tr.raw as any).hardware().perf(); } catch (e: any) { add(root, el('p', { class: 'muted' }, `The hardware model could not run: ${e.message}`)); return; } + const machine = (tr.raw as any).machine; + const byLine = mojoCost(session, tr); + if (byLine) add(root, byLine); + add(root, el('p', { class: 'hint' }, `Machine: ${machineLabel(machine)}, a model machine: every count here is the model's, not a measurement of a real processor. Two cycle counts are shown because the course models two cores: an in-order 5-stage pipeline and an out-of-order core. They charge memory differently, so compare each against itself across edits, not against each other.`)); + const rows: Array<[string, string]> = [ + ['instructions', String(perf.instructions)], + ['micro-ops', String(perf.uops)], + ['cycles, in-order pipeline', String(perf.cyclesInOrder)], + ['cycles, out-of-order core', String(perf.cyclesOoO)], + ['instructions per cycle (OoO)', perf.ipc?.toFixed?.(2) ?? String(perf.ipc)], + ['branches', `${perf.branches} (${perf.mispredicts} mispredicted)`], + ['L1d loads / misses', `${perf.l1dLoads} / ${perf.l1dMisses}`], + ['L1i misses', String(perf.l1iMisses)], + ['L2 misses', String(perf.l2Misses)], + ['L3 misses', String(perf.l3Misses)], + ['memory reads', String(perf.memoryReads)], + ['TLB misses', perf.tlbMisses == null ? '—' : String(perf.tlbMisses)], + ['time at this clock', `${(perf.seconds * 1e9).toFixed(0)} ns`], + ]; + const table = el('table', { class: 'tbl perf-tbl' }); + for (const [k, v] of rows) add(table, el('tr', {}, el('td', {}, k), el('td', { class: 'mono' }, v))); + add(root, table); + if (Array.isArray(perf.bounds) && perf.bounds.length) { + add(root, el('h4', {}, 'What bounds the out-of-order core'), el('ul', { class: 'bounds' }, ...perf.bounds.map((b: any) => el('li', {}, el('b', {}, b.name), ': ', el('span', { class: 'mono' }, `${b.cycles} cycles`), ' — ', b.text)))); + } + } + const off = session.onChange(render); + render(); + return off; +} + +export function diagnosticsFor(session: Session, lang: LangId): Diagnostic[] { return session.diagnostics(lang); } + +/** + * For code sent from the Compiler view (each instruction marked `; mojo line N`): what each Mojo + * line cost on the model machine, as instructions executed and in-order pipeline cycles. An + * instruction's cycles are how far it moves the finish line (its write-back after the previous + * one's), so they add up to the run's total; the first one also pays for filling the pipeline and + * fetching code not yet in the cache. + */ +function mojoCost(session: Session, tr: any): HTMLElement | null { + const asm = session.source('asm').split('\n'); + const mojoOf = (asmLine: number): number | null => { const m = /;\s*mojo line (\d+)/.exec(asm[asmLine] ?? ''); return m ? Number(m[1]) : null; }; + if (!asm.some((l) => /;\s*mojo line \d+/.test(l))) return null; + let rows: any[]; + try { rows = (tr.raw as any).hardware().pipeline().rows; } catch { return null; } + const lines = new Map(); + let prev = 0, first: number | null | undefined; + for (const r of rows) { + const ln = mojoOf(r.step?.instr?.lineNo ?? -1); + if (first === undefined) first = ln; + const e = lines.get(ln) ?? { executed: 0, cycles: 0 }; + e.executed++; e.cycles += r.E.WB - prev; prev = r.E.WB; + lines.set(ln, e); + } + const total = [...lines.values()].reduce((a, e) => a + e.cycles, 0) || 1; + const src = session.source('mojo').split('\n'); + const tbl = el('table', { class: 'tbl' }, el('tr', {}, el('th', {}, 'Mojo line'), el('th', {}, ''), el('th', {}, 'instructions run'), el('th', {}, 'cycles (in-order)'), el('th', {}, 'share'))); + for (const [ln, e] of [...lines].sort((a, b) => (a[0] ?? 1e9) - (b[0] ?? 1e9))) { + add(tbl, el('tr', {}, + el('td', { class: 'mono' }, ln == null ? '—' : String(ln)), + el('td', { class: 'mono' }, ln == null ? 'no line of the program (inlined library code, or added by the compiler)' : (src[ln - 1] ?? '').trim()), + el('td', { class: 'mono' }, String(e.executed)), + el('td', { class: 'mono' }, String(e.cycles)), + el('td', { class: 'mono' }, `${Math.round((100 * e.cycles) / total)}%`))); + } + return el('div', { class: 'cost-by-line' }, + el('h4', {}, 'What each Mojo line cost on the model machine'), + el('p', { class: 'small muted' }, `On the model machine's in-order pipeline: each instruction counts the cycles it adds to the finish. ${first != null ? `The first instruction (line ${first}) also pays for filling the pipeline and fetching code not yet in the cache, which is why its line looks expensive on a short run.` : ''}`), + tbl); +} diff --git a/src/ui/views/practices.ts b/src/ui/views/practices.ts new file mode 100644 index 0000000..18b4244 --- /dev/null +++ b/src/ui/views/practices.ts @@ -0,0 +1,45 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +/** + * The Best practices tab (the Bridge, when the helper is on): what the rules find in the generated Mojo. Each + * finding shows the Mojo line, the pseudo line it came from, the reason, the before and after, the manual's page, + * and, where it is true, how to write the pseudo or lingo so the translator writes the better form. The Mojo here + * is read-only, so rewrites are shown, not applied; clicking a finding lights both lines. + */ +import { el, clear, add } from '../dom.js'; +import type { Session } from '../../core/session.js'; +import { RULES } from '#core/mojo/practices.js'; +import type { LangId } from '#core/common/types.js'; + +export interface PracticesHooks { + /** Light these lines, each in its own pane, for a moment. */ + highlight(pairs: Array<[LangId, number]>): void; +} + +export function practicesView(session: Session, root: HTMLElement, hooks: PracticesHooks): () => void { + function render() { + clear(root); + const found = session.practices(); + add(root, el('p', { class: 'hint' }, 'The Mojo here is a literal translation of your pseudo, so it keeps habits Mojo programmers drop. These notes show what they would change. The translation itself never changes, and nothing here edits your work.')); + if (!session.source('mojo').trim()) { add(root, el('p', { class: 'muted' }, 'There is no Mojo yet: it is made from the pseudo.')); return; } + if (!found.length) { add(root, el('p', { class: 'muted' }, `Nothing to suggest. ${RULES.length} checks ran on the generated Mojo and found nothing to change.`)); return; } + const list = el('ul', { class: 'practices' }); + for (const f of found) { + const pseudo = session.pseudoLinesOfMojo(f.line); + const rule = RULES.find((r) => r.id === f.rule)!; + const item = el('li', { class: 'practice', onClick: () => hooks.highlight([['mojo', f.line], ...pseudo.map((l): [LangId, number] => ['pseudo', l])]) }, + el('div', { class: 'practice-head' }, + el('strong', {}, rule.title), + el('span', { class: 'mono small muted' }, `Mojo ${f.line}${f.endLine && f.endLine !== f.line ? `–${f.endLine}` : ''}`, pseudo.length ? ` · pseudo ${pseudo[0]}${pseudo.length > 1 ? `–${pseudo[pseudo.length - 1]}` : ''}` : '')), + el('p', {}, f.message), + el('div', { class: 'practice-diff' }, el('pre', { class: 'mono practice-before', title: 'as generated' }, f.before), el('pre', { class: 'mono practice-after', title: 'as a person might write it' }, f.after)), + f.pseudoHint ? el('p', { class: 'small' }, el('b', {}, 'In the pseudo: '), f.pseudoHint) : null, + el('p', { class: 'small' }, el('a', { href: f.docUrl, target: '_blank', rel: 'noopener' }, 'The Mojo manual ↗'))); + add(list, item); + } + add(root, list); + } + const off = session.onChange((what) => { if (what === 'source' || what === 'state') render(); }); + render(); + return off; +} diff --git a/src/ui/views/run.ts b/src/ui/views/run.ts new file mode 100644 index 0000000..e1ca97a --- /dev/null +++ b/src/ui/views/run.ts @@ -0,0 +1,208 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +/** + * The Run view: the whole run read top to bottom, one row per step, with a column for each variable the student + * follows (its value after the step: written now in color, carried over faded, out of scope blank) and the + * lifecycle of the value it names marked in the same cell. Above the rows, the followed variables as they stand + * at the stepper's position, with a ruler for strings and lists and a grid for tables. Click a row to step there. + * + * It replaces the Variables panel, the trace table, the table of values and the lifetimes: the data is + * core/runview.ts, the stepper is the one docked under the editor (it moves this view through session.onStep). + */ +import { el, add, clear } from '../dom.js'; +import type { Session } from '../../core/session.js'; +import { runColumns, runRows, defaultFollow, valuesAt, type RunColumn, type RunRow, type LifeKind } from '#core/common/runview.js'; +import { familyOf, FAMILY_LABEL } from '../stepkinds.js'; + +export interface RunHooks { + goto(t: number): void; + /** The followed variables kept for this area (null: not chosen yet), and where a new choice is kept. */ + follow(): string[] | null; + setFollow(keys: string[]): void; +} + +const LIFE_MARK: Record = { made: '●', copied: '⧉', 'moved-in': '⇢', 'moved-out': '⇥', destroyed: '✕' }; +/** Every step is drawn while the run is this short; a longer one shows a window around the stepper. */ +const ALL_UP_TO = 800; +const WINDOW = 300; +/** The types whose value is drawn with a ruler of cells (rulerCells in core/runview.ts), pseudo's and Mojo's. */ +const RULED = /^(STRING|LIST\b|String|List\[)/; + +export function runView(session: Session, root: HTMLElement, hooks: RunHooks): () => void { + let onlyWrites = false; + let built: { trace: any; key: string; cols: RunColumn[]; follow: string[] } | null = null; + let rowEls = new Map(); + let windowAt = 0; + const head = el('div', { class: 'run-head' }); + const now = el('div', { class: 'run-now' }); + // scrolls on its own: focusable, so a keyboard can scroll it too + const scroll = el('div', { class: 'run-scroll', tabindex: '0', role: 'region', 'aria-label': 'The run, step by step' }); + clear(root); + add(root, head, now, scroll); + + const t = () => session.state.t ?? 0; + + function followed(cols: RunColumn[]): string[] { + const keys = new Set(cols.map((c) => c.key)); + const kept = (hooks.follow() ?? []).filter((k) => keys.has(k)); + return kept.length || hooks.follow()?.length === 0 ? kept : defaultFollow(cols); + } + + function short(text: string, n = 22): string { return text.length > n ? `${text.slice(0, n - 1)}…` : text; } + + let picking = false; + + function renderHead(cols: RunColumn[], follow: string[]) { + clear(head); + const order = (keys: string[]) => keys.sort((a, b) => cols.findIndex((x) => x.key === a) - cols.findIndex((x) => x.key === b)); + const set = (keys: string[]) => { hooks.setFollow(order(keys)); build(true); }; + const where = (c: RunColumn) => (c.fn === 'main' ? 'the main program' : c.fn); + const multi = new Set(cols.map((c) => c.fn)).size > 1; + const chips = el('div', { class: 'run-follow' }, el('span', { class: 'run-follow-label' }, 'Follow')); + for (const k of follow) { + const c = cols.find((x) => x.key === k)!; + add(chips, el('span', { class: 'run-chip on', title: `${c.name}${c.type ? ` (${c.type})` : ''} in ${where(c)}` }, + multi ? el('span', { class: 'run-chip-fn' }, `${c.fn === 'main' ? 'main' : c.fn}.`) : null, c.name, + el('button', { type: 'button', class: 'run-chip-x', title: `Stop following ${c.name}`, 'aria-label': `stop following ${c.name}`, onClick: () => set(follow.filter((x) => x !== k)) }, '×'))); + } + if (!follow.length) add(chips, el('span', { class: 'small muted' }, 'nothing yet')); + add(chips, el('button', { type: 'button', class: 'run-chip run-chip-add' + (picking ? ' open' : ''), 'aria-expanded': picking, title: 'Choose the variables to follow', onClick: () => { picking = !picking; renderHead(cols, follow); } }, picking ? 'done' : '+ variables')); + const filter = el('label', { class: 'run-filter small', title: 'Hide the steps that change nothing, print nothing and end nothing' }, + el('input', { type: 'checkbox', checked: onlyWrites, onChange: (e: Event) => { onlyWrites = (e.target as HTMLInputElement).checked; build(true); } }), ' only steps that change something'); + add(head, chips, filter); + if (!picking) return; + // the picker: every variable of the run, by routine; clicking one follows it or stops following it + const picker = el('div', { class: 'run-picker' }); + const byFn = new Map(); + for (const c of cols) byFn.set(c.fn, [...(byFn.get(c.fn) ?? []), c]); + for (const [fn, list] of byFn) { + add(picker, el('div', { class: 'run-picker-row' }, + el('span', { class: 'run-fn' }, fn === 'main' ? 'main program' : fn), + ...list.map((c) => { + const on = follow.includes(c.key); + return el('button', { + type: 'button', class: 'run-chip' + (on ? ' on' : ''), 'aria-pressed': on, + title: `${c.name}${c.type ? ` (${c.type})` : ''}: ${c.writes ? `written by ${c.writes} step${c.writes === 1 ? '' : 's'}` : 'never written after it is made'}`, + onClick: () => set(on ? follow.filter((k) => k !== c.key) : [...follow, c.key]), + }, c.name, c.writes ? el('sup', {}, String(c.writes)) : null); + }), + el('button', { type: 'button', class: 'linkish small', onClick: () => set([...new Set([...follow, ...list.filter((c) => c.name !== 'self').map((c) => c.key)])]) }, 'all'))); + } + add(picker, el('div', { class: 'run-picker-row' }, el('button', { type: 'button', class: 'linkish small', onClick: () => set(defaultFollow(cols)) }, 'back to the suggested ones'), el('button', { type: 'button', class: 'linkish small', onClick: () => set([]) }, 'none'))); + add(head, picker); + } + + function renderNow(trace: any, follow: string[], cols: RunColumn[]) { + clear(now); + if (!follow.length) { add(now, el('p', { class: 'small muted' }, 'Choose variables to follow above: each gets a column of its values, step by step.')); return; } + const at = valuesAt(trace, follow, t()); + const rows = (trace.steps as any[]); + const next = rows[t()]; + const readNext = new Set((next?.reads ?? []).map((r: any) => r.name)); + const last = rows[t() - 1]; + const wroteLast = new Set((last?.writes ?? []).map((w: any) => w.name)); + for (const v of at) { + const c = cols.find((x) => x.key === v.key)!; + const box = el('div', { class: 'run-var' + (wroteLast.has(c.name) && v.inScope ? ' run-var-wrote' : '') + (readNext.has(c.name) && v.inScope ? ' run-var-read' : '') }, + el('span', { class: 'run-var-name mono' }, c.name), v.type ? el('span', { class: 'run-var-type' }, v.type) : null, + el('span', { class: 'run-var-value mono', title: v.text ?? '' }, v.inScope ? (v.text ?? el('i', { class: 'muted' }, 'no value yet')) : el('i', { class: 'muted' }, 'not in scope'))); + if (v.inScope && v.ruler) { + const reads = (next?.reads ?? []).filter((r: any) => r.name === c.name && r.path).map((r: any) => Number(r.path[0])); + const writes = (last?.writes ?? []).filter((w: any) => w.name === c.name && w.path).map((w: any) => Number(w.path[0])); + const r = el('div', { class: 'ruler' }); + v.ruler.forEach((x, i) => add(r, el('span', { class: 'ruler-cell' + (reads.includes(i) ? ' read' : '') + (writes.includes(i) ? ' wrote' : '') }, el('b', {}, x === ' ' ? '␣' : x), el('i', {}, String(i))))); + add(box, r); + } else if (v.inScope && v.grid) { + const g = el('table', { class: 'run-grid' }); + const at = (list: any[], kind: string) => new Set(list.filter((a: any) => a.name === c.name && a.path?.length === 2).map((a: any) => `${a.path[0]},${a.path[1]}`)); + const wrote = at(last?.writes ?? [], 'w'), reads = at(next?.reads ?? [], 'r'); + v.grid.forEach((row, i) => add(g, el('tr', {}, el('th', {}, String(i)), ...row.map((x, j) => el('td', { class: (wrote.has(`${i},${j}`) ? 'wrote' : '') + (reads.has(`${i},${j}`) ? ' read' : '') }, x))))); + add(box, g); + } else if (RULED.test(c.type) && (!v.inScope || v.text == null)) { + // a string or list out of scope, or with no value yet: the same height as with its ruler, so the boxes + // under and beside it do not move when it gets one + add(box, el('div', { class: 'ruler ruler-placeholder', 'aria-hidden': 'true' }, el('span', { class: 'ruler-cell' }, el('b', {}, '\u00a0'), el('i', {}, '0')))); + } + add(now, box); + } + // while one run is stepped the panel never gets shorter (a table, or a value that wraps, can still grow it once) + if (heldFor !== trace) { heldFor = trace; now.style.minHeight = ''; } + const h = now.offsetHeight; + if (h > (Number.parseFloat(now.style.minHeight) || 0)) now.style.minHeight = `${h}px`; + } + let heldFor: any = null; + + function cell(row: RunRow, key: string): HTMLElement { + const c = row.cells[key]; + const td = el('td', { class: 'run-cell mono' + (c.wrote ? ' wrote' : '') + (c.read ? ' read' : '') + (c.text == null ? ' out' : '') }); + for (const m of c.life) add(td, el('span', { class: `run-life run-life-${m.kind}`, title: m.text }, LIFE_MARK[m.kind])); + if (c.at.length) add(td, el('span', { class: 'run-at', title: `this step wrote ${c.at.map((x) => `[${x}]`).join(' and ')}` }, c.at.map((x) => `[${x}]`).join(' '), ' ')); + if (c.text != null) add(td, el('span', { title: c.text }, short(c.text))); + return td; + } + + function build(force = false) { + const trace = session.trace(); + if (!trace) { clear(head); clear(now); clear(scroll); add(scroll, el('p', { class: 'muted run-empty' }, session.runError || 'Nothing to run yet.')); built = null; return; } + if (trace.lang === 'asm') { clear(head); clear(now); clear(scroll); add(scroll, el('p', { class: 'muted run-empty' }, 'The machine\'s run is drawn on the board: registers, memory and the rest.')); built = null; return; } + const cols = runColumns(trace); + const follow = followed(cols); + const key = JSON.stringify([follow, onlyWrites, windowAt]); + if (!force && built?.trace === trace && built.key === key) { mark(); return; } + built = { trace, key, cols, follow }; + renderHead(cols, follow); + clear(scroll); + rowEls = new Map(); + const n = trace.count; + let from = 0, to = n; + if (n > ALL_UP_TO) { from = Math.max(0, Math.min(windowAt - WINDOW / 2, n - WINDOW)); to = Math.min(n, from + WINDOW); } + const rows = runRows(trace, follow, from, to, { onlyWrites }); + const thead = el('thead', {}, el('tr', {}, el('th', { class: 'run-no' }, '#'), el('th', { class: 'run-line' }, 'line'), el('th', { class: 'run-what' }, 'what ran'), + ...follow.map((k) => { const c = cols.find((x) => x.key === k)!; return el('th', { class: 'run-colhead mono', title: `${c.name} in ${c.fn === 'main' ? 'the main program' : c.fn}` }, c.name); }))); + const tbody = el('tbody'); + const jump = (label: string, at: number) => el('tr', { class: 'run-more' }, el('td', { colspan: 3 + follow.length }, el('button', { type: 'button', class: 'linkish', onClick: () => { windowAt = at; build(true); } }, label))); + if (from > 0) add(tbody, jump(`… ${from} earlier steps: show them`, from)); + for (const r of rows) { + const fam = familyOf((trace.steps as any[])[r.step], trace.lang); + const what = el('td', { class: 'run-what mono' }, el('span', { class: 'run-indent', style: { width: `${Math.min(r.depth, 6) * 10}px` } }), r.text); + if (r.otherLife.length) add(what, el('div', { class: 'run-note' }, r.otherLife.join(' · '))); + if (r.printed.length) add(what, el('div', { class: 'run-note run-printed' }, `prints ${r.printed.map((x) => JSON.stringify(x)).join(', ')}`)); + const tr = el('tr', { class: `run-row k-${fam}`, title: FAMILY_LABEL[fam], onClick: () => hooks.goto(r.step + 1) }, + el('td', { class: 'run-no muted' }, el('span', { class: `k-dot k-${fam}` }), String(r.step + 1)), el('td', { class: 'run-line mono muted' }, r.line == null ? '' : String(r.line)), what, + ...follow.map((k) => cell(r, k))); + rowEls.set(r.step, tr); + add(tbody, tr); + } + if (to < n) add(tbody, jump(`… ${n - to} later steps: show them`, to + WINDOW / 2)); + if (!rows.length) add(tbody, el('tr', {}, el('td', { colspan: 3 + follow.length, class: 'muted' }, 'No step changes anything.'))); + add(scroll, el('table', { class: 'tbl run-tbl' }, thead, tbody)); + if (trace.error) add(scroll, el('p', { class: 'small err run-error' }, `The run stopped: ${trace.error.message}`)); + renderNow(trace, follow, cols); + mark(); + } + + /** Where the stepper is: the step that just ran, and the one that runs next. */ + function mark() { + if (!built) return; + const at = t(); + const trace = built.trace; + if (trace.count > ALL_UP_TO && (at < windowAt - WINDOW / 2 || at > windowAt + WINDOW / 2)) { windowAt = at; build(true); return; } + for (const r of scroll.querySelectorAll('.row-last, .row-next')) r.classList.remove('row-last', 'row-next'); + rowEls.get(at - 1)?.classList.add('row-last'); + const nextRow = rowEls.get(at); + nextRow?.classList.add('row-next'); + const target = nextRow ?? rowEls.get(at - 1); + if (target) { + // keep the row in view inside this panel only (never scroll the page) + const top = target.offsetTop - scroll.clientHeight / 3; + if (target.offsetTop < scroll.scrollTop + 40 || target.offsetTop > scroll.scrollTop + scroll.clientHeight - 40) scroll.scrollTop = Math.max(0, top); + } + renderNow(trace, built.follow, built.cols); + } + + windowAt = t(); + build(true); + const offStep = session.onStep(() => mark()); + const offChange = session.onChange((what) => { if (what === 'source' || what === 'run') build(); }); + return () => { offStep(); offChange(); }; +} diff --git a/src/ui/views/tests.ts b/src/ui/views/tests.ts new file mode 100644 index 0000000..f99ee51 --- /dev/null +++ b/src/ui/views/tests.ts @@ -0,0 +1,151 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +/** + * The Tests view: the fuzzer's report (core/fuzz.ts) for each routine, written out so a student can see exactly + * what was tried and what was checked, not just "we tested it": + * + * what each input must do, how the inputs were made (each parameter's generator, each strategy and how many + * inputs it made), every way of failing with the input that found it and each step of shrinking it, the lines + * the inputs reached and the ones none did, the answers given and how often, and every case run. + * + * The seed and the number of inputs are chosen here; the same seed always makes the same inputs. + */ +import { el, add, clear, button, copyText } from '../dom.js'; +import type { Session } from '../../core/session.js'; +import type { LangId } from '#core/common/types.js'; +import { BUDGETS, STRATEGY, type FuzzCase, type FuzzReport, type Strategy } from '#core/common/fuzz.js'; + +export interface TestsHooks { + reveal(lang: LangId, line: number): void; + /** Run this call in the stepper (pseudo: the call box), and show the run. */ + stepThrough?(call: string): void; +} + +const KIND: Record = { + index: 'index out of range', bounds: 'index out of bounds', unset: 'value used before it is set', value: 'bad value', type: 'wrong type', divide: 'division by zero', + ensure: 'ENSURE broken', invariant: 'INVARIANT broken', decreases: 'DECREASES broken', assert: 'ASSERT broken', limit: 'does not finish', raise: 'uncaught raise', + depth: 'calls too deep', nondeterministic: 'a different answer the second time', +}; + +const OUTCOME_WORD: Record = { pass: 'passed', fail: 'failed', skip: 'skipped', raises: 'raised' }; + +export function testsView(session: Session, root: HTMLElement, hooks: TestsHooks): () => void { + let seed = 1; + let budget = 300; + const filters = new Map(); // per routine: 'all' | 'fail' | 'skip' | a strategy + const open = new Set(); + + function render() { + clear(root); + const mojo = session.state.lang === 'mojo'; + const pane: LangId = mojo ? 'mojo' : 'pseudo'; + const reports = session.fuzz({ seed, budget }); + const seedBox = el('input', { class: 'input mono fuzz-seed', type: 'number', min: 1, value: String(seed), title: 'The seed: the same seed always makes the same inputs' }) as HTMLInputElement; + seedBox.addEventListener('change', () => { seed = Math.max(1, Math.floor(Number(seedBox.value) || 1)); render(); }); + const budgetBox = el('select', { class: 'select', 'aria-label': 'Inputs per routine', title: 'How many inputs to try for each routine', onChange: (e: Event) => { budget = Number((e.target as HTMLSelectElement).value); render(); } }, + ...BUDGETS.map((b) => el('option', { value: String(b), selected: b === budget }, `${b} inputs`))); + add(root, el('div', { class: 'fuzz-bar' }, + el('span', { class: 'small muted' }, mojo ? 'Each function other than main, in Programming+\'s interpreter.' : 'Each routine of the pseudo, with the speco woven in.'), + el('span', { class: 'spacer' }), + el('label', { class: 'tool-label' }, 'seed ', seedBox), button('new seed', () => { seed = 1 + Math.floor(Math.random() * 99999); render(); }, { class: 'btn btn-small', title: 'Different inputs from the same strategies' }), + budgetBox)); + if (!reports.length) { add(root, el('p', { class: 'muted' }, mojo ? 'Generated-input testing needs a function other than main, in a Mojo program with no problems.' : 'Generated-input testing needs a FUNCTION or PROCEDURE that parses.')); return; } + reports.forEach((r, i) => add(root, routine(r, pane, i === 0 || r.failures.length > 0))); + } + + function routine(r: FuzzReport, pane: LangId, first: boolean): HTMLElement { + const covered = r.coverage.filter((c) => c.inputs > 0).length; + const isOpen = open.has(r.name) || (!open.size && first); + const sec = el('details', { class: 'fuzz-unit', open: isOpen }); + sec.addEventListener('toggle', () => { if (sec.open) open.add(r.name); else open.delete(r.name); }); + const tried = r.cases.filter((c) => c.strategy !== 'shrink' && c.strategy !== 'repeat').length; + add(sec, el('summary', {}, + el('code', { class: 'fuzz-sig' }, r.signature), + r.problem && !r.cases.length ? el('span', { class: 'badge badge-open' }, 'not tested') : el('span', { class: `badge ${r.failures.length ? 'badge-broken' : 'badge-proved'}` }, r.failures.length ? `${r.failures.length} way${r.failures.length === 1 ? '' : 's'} of failing` : 'no failures'), + r.cases.length ? el('span', { class: 'small muted' }, ` ${tried} inputs · ${r.counts.fail} failed · ${r.counts.skip} skipped${r.counts.raises ? ` · ${r.counts.raises} raised` : ''}${r.coverage.length ? ` · ${covered}/${r.coverage.length} lines reached` : ''}`) : null)); + if (r.problem) add(sec, el('p', { class: r.cases.length ? 'hint' : 'muted' }, r.problem)); + if (!r.cases.length) return sec; + + // what each input must do + add(sec, el('h5', {}, 'What each input must do'), el('ul', { class: 'fuzz-checks' }, ...r.checks.map((c) => el('li', {}, c)))); + + // how the inputs were made + const gens = el('table', { class: 'tbl fuzz-gens' }, el('tr', {}, el('th', {}, 'parameter'), el('th', {}, 'type'), el('th', {}, 'values tried'))); + for (const p of r.params) add(gens, el('tr', {}, el('td', { class: 'mono' }, p.name), el('td', { class: 'mono muted' }, p.type), el('td', {}, p.how))); + const strat = el('ul', { class: 'fuzz-strats' }, ...r.strategies.map((s) => el('li', {}, el('b', {}, `${s.count} ${s.label}`), ': ', s.how))); + add(sec, el('h5', {}, `How the inputs were made (seed ${r.seed})`), r.params.length ? gens : el('p', { class: 'small muted' }, 'It takes no parameters, so it runs once.'), strat); + + // the failures, each with the input that found it and every step of shrinking it + if (r.failures.length) { + add(sec, el('h5', {}, 'Failures')); + for (const f of r.failures) { + const card = el('div', { class: 'fuzz-fail' }, + el('div', { class: 'fuzz-fail-head' }, el('span', { class: 'badge badge-broken' }, KIND[f.kind] ?? f.kind), ' ', el('code', {}, f.call), + f.line ? button(`line ${f.line}`, () => hooks.reveal(pane, f.line!), { class: 'btn btn-small btn-quiet mono' }) : null, el('span', { class: 'spacer' }), + hooks.stepThrough && r.lang === 'pseudo' ? button('Step through this input', () => hooks.stepThrough!(f.call), { class: 'btn btn-small', title: 'Put this call in the call box and show the run' }) : button('Copy the call', async (e) => { await copyText(f.call); (e.target as HTMLButtonElement).textContent = 'Copied'; }, { class: 'btn btn-small' })), + el('p', { class: 'fuzz-msg' }, f.message)); + if (f.shrink.length > 1) add(card, el('div', { class: 'small muted' }, `Found by case #${f.n} and shrunk in ${f.shrink.length - 1} step${f.shrink.length === 2 ? '' : 's'} to the smallest input that still fails this way:`), + el('ol', { class: 'fuzz-shrink' }, ...f.shrink.map((c, i) => el('li', { class: i === f.shrink.length - 1 ? 'fuzz-shrink-last' : '' }, el('code', {}, c))))); + else add(card, el('div', { class: 'small muted' }, `Found by case #${f.n}; no smaller input fails the same way.`)); + add(sec, card); + } + } + + // coverage: the lines the inputs reached, and the ones none did + if (r.coverage.length) { + const src = session.source(pane).split('\n'); + const most = Math.max(1, ...r.coverage.map((c) => c.inputs)); + const never = r.coverage.filter((c) => !c.inputs); + const list = el('div', { class: 'fuzz-cov' }); + for (const c of r.coverage) { + add(list, el('button', { type: 'button', class: 'fuzz-cov-row' + (c.inputs ? '' : ' never'), title: c.inputs ? `${c.inputs} of the inputs reached line ${c.line}, ${c.hits} time${c.hits === 1 ? '' : 's'} in all` : `No input reached line ${c.line}`, onClick: () => hooks.reveal(pane, c.line) }, + el('span', { class: 'fuzz-cov-line mono' }, String(c.line)), + el('span', { class: 'fuzz-cov-bar' }, el('span', { style: { width: `${(100 * c.inputs) / most}%` } })), + el('span', { class: 'fuzz-cov-n mono' }, c.inputs ? String(c.inputs) : 'never'), + el('code', { class: 'fuzz-cov-src' }, (src[c.line - 1] ?? '').trim()))); + } + add(sec, el('h5', {}, `Lines reached: ${r.coverage.length - never.length} of ${r.coverage.length}`), + never.length ? el('p', { class: 'hint' }, `No input reached ${never.length === 1 ? `line ${never[0].line}` : `lines ${never.map((c) => c.line).join(', ')}`}. Either no input of these kinds can get there, or the generators need a case they do not make; a line no input reaches is a line no test has checked.`) : null, + list); + } + + // the answers it gave + if (r.results.length) { + const total = r.results.reduce((a, x) => a + x.count, 0); + const top = r.results.slice(0, 10); + add(sec, el('h5', {}, `Answers: ${r.results.length} different${r.results.length > 10 ? ', the 10 most common' : ''}`), + el('div', { class: 'fuzz-results' }, ...top.map((x) => el('div', { class: 'fuzz-result' }, el('code', {}, x.value.length > 40 ? `${x.value.slice(0, 39)}…` : x.value), el('span', { class: 'fuzz-cov-bar' }, el('span', { style: { width: `${(100 * x.count) / total}%` } })), el('span', { class: 'small muted mono' }, String(x.count)))))); + } + + // every case run + const filter = filters.get(r.name) ?? (r.counts.fail ? 'fail' : 'all'); + const choose = (f: string) => { filters.set(r.name, f); open.add(r.name); render(); }; + const strategiesUsed = [...new Set(r.cases.map((c) => c.strategy))] as Strategy[]; + const chips = el('div', { class: 'fuzz-filter' }, + ...[['all', `all ${r.cases.length}`], ['fail', `failed ${r.counts.fail}`], ['skip', `skipped ${r.counts.skip}`], ...(r.counts.raises ? [['raises', `raised ${r.counts.raises}`]] : []), ...strategiesUsed.map((s) => [s, `${STRATEGY[s].label} ${r.cases.filter((c) => c.strategy === s).length}`])] + .map(([id, label]) => el('button', { type: 'button', class: 'run-chip' + (filter === id ? ' on' : ''), onClick: () => choose(id) }, label))); + const shown = r.cases.filter((c) => filter === 'all' || c.outcome === filter || c.strategy === filter); + const MAX = 300; + const table = el('table', { class: 'tbl fuzz-cases' }, el('thead', {}, el('tr', {}, el('th', {}, '#'), el('th', {}, 'how'), el('th', {}, 'input'), el('th', {}, 'outcome'), el('th', {}, 'answer, or what went wrong'), el('th', { title: 'steps the run took' }, 'steps')))); + const body = el('tbody'); + for (const c of shown.slice(0, MAX)) add(body, caseRow(c, pane)); + add(table, body); + add(sec, el('h5', {}, 'Every case run'), chips, el('div', { class: 'fuzz-cases-wrap' }, table), shown.length > MAX ? el('p', { class: 'small muted' }, `The first ${MAX} of ${shown.length} are shown.`) : null); + return sec; + } + + function caseRow(c: FuzzCase, pane: LangId): HTMLElement { + return el('tr', { class: `fuzz-case fuzz-${c.outcome}` }, + el('td', { class: 'muted mono' }, String(c.n)), + el('td', { class: 'small' }, STRATEGY[c.strategy].label), + el('td', { class: 'mono', title: c.call }, c.args.join(', ') || '()'), + el('td', {}, el('span', { class: `fuzz-out fuzz-out-${c.outcome}` }, OUTCOME_WORD[c.outcome])), + el('td', { class: 'mono small' }, c.outcome === 'pass' ? (c.result ?? '') : c.message ?? '', c.line ? el('button', { type: 'button', class: 'linkish', onClick: () => hooks.reveal(pane, c.line!) }, ` line ${c.line}`) : null, + c.newLines?.length ? el('span', { class: 'fuzz-new', title: 'This input reached lines no earlier input had; the fuzzer mutates it to explore further' }, ` new: line${c.newLines.length === 1 ? '' : 's'} ${c.newLines.join(', ')}`) : null), + el('td', { class: 'mono muted' }, String(c.steps))); + } + + const off = session.onChange((what) => { if (what === 'source' || what === 'run') render(); }); + render(); + return off; +} diff --git a/src/ui/views/trace.ts b/src/ui/views/trace.ts new file mode 100644 index 0000000..86bcd04 --- /dev/null +++ b/src/ui/views/trace.ts @@ -0,0 +1,538 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +/** + * The step-through view. One controller (back, step, play, slider, + * keyboard, breakpoints, loop-pass jumps, predict mode) over either trace + * shape; the body switches on the language: pseudocode shows what runs next, + * the trace table, and the variables with rulers and history; assembly shows + * registers, flags, memory, and what the instruction did. + */ +import { toCsv } from '../../core/csv.js'; +import { el, clear, add, button } from '../dom.js'; +import { frameAt, type Trace } from '#core/common/types.js'; +import { formatValue, UNSET } from '#core/engines/pseudo/lang.js'; +import { varIn } from '#core/common/runview.js'; +import { formatHex, FLAG_NAMES } from '#core/engines/asm86/interp.js'; +import type { Session } from '../../core/session.js'; +import { familyOf, FAMILY_LABEL } from '../stepkinds.js'; + +export interface StepperApi { goto(t: number): void; t: number; destroy(): void; toggleBreakpoint(line: number): void; breakpoints: Set } + +/** + * Where the stepper's parts go. With no hosts, everything stacks inside `root` + * (the embeds). The shell gives each part its own persistent panel: the + * controls stay in one place, the variables in another, and the trace table + * and the output in panels of their own. + */ +export interface TraceHosts { + controls: HTMLElement; + /** The "what runs next" box and the predict box. */ + next: HTMLElement; + /** The variables and the trace table, for a host that shows them itself; the workspace's Run view does instead (views/run.ts). */ + vars?: HTMLElement; + table?: HTMLElement; + output: HTMLElement; + /** One line: the loops in flight, or the machine's counts. */ + status: HTMLElement; +} + +export interface TraceOptions { + onStep?: (line: number | null, last: number | null, hits: Map) => void; + onBreakpoints?: (lines: Set) => void; + compact?: boolean; + hosts?: TraceHosts; + /** Called with the number of output lines so far and whether the run ended with an error (the dock's summary). */ + onOutput?: (lines: string[], error: string | null) => void; +} + +export function traceView(session: Session, root: HTMLElement, opts: TraceOptions = {}): StepperApi { + let t = session.state.t ?? 0; + let timer: number | null = null; + let trace: Trace | null = null; + let speed = 350; + let predictOn = false; + let onlyWrites = false; + const score = { right: 0, asked: 0 }; + const breakpoints = new Set(); + + const controls = el('div', { class: 'stepper' }); + const row2 = el('div', { class: 'stepper-row2' }); + const nextBox = el('div', { class: 'trace-next' }); + const predictBox = el('div', { class: 'predict', style: { display: 'none' } }); + const status = el('div', { class: 'trace-status' }); + const body = el('div', { class: 'trace-body' }); + const output = el('pre', { class: 'trace-output' }); + const H = opts.hosts; + // in the shell the variables and the table have panels of their own; in an embed they share `body` + const varsHost = H?.vars ?? el('div', { class: 'trace-col' }); + const tableHost = H?.table ?? el('div', { class: 'trace-col' }); + /** Whether this stepper draws the variables and the trace table at all (not when the Run view does). */ + const drawsBody = !H || !!(H.vars && H.table); + if (H) { add(H.controls, controls, row2); add(H.next, nextBox, predictBox); add(H.status, status); add(H.output, output); } + else add(root, controls, row2, nextBox, predictBox, status, body, output); + + const slider = el('input', { type: 'range', min: 0, max: 0, value: 0, class: 'stepper-slider', 'aria-label': 'step', onInput: () => goto(Number(slider.value)) }); + const counter = el('span', { class: 'stepper-count' }); + const playBtn = button('Play', () => (timer ? pause() : play()), { title: 'Space' }); + add(controls, + button('⏮', () => goto(0), { title: 'First step (Home)' }), + button('◀', () => goto(t - 1), { title: 'Back one step (←)' }), + button('▶', () => stepForward(), { title: 'One step (→)' }), + button('⏭', () => goto(trace?.count ?? 0), { title: 'Last step (End)' }), + playBtn, slider, counter, + ); + const passBack = button('↶ pass', () => jumpPass(-1), { class: 'btn-small', title: 'Previous pass of the loop you are in (Shift+←)' }); + const passFwd = button('pass ↷', () => jumpPass(1), { class: 'btn-small', title: 'Next pass of the loop you are in (Shift+→)' }); + const toBreak = button('to breakpoint', () => runToBreakpoint(), { class: 'btn-small', title: 'Run until a breakpointed line is next (click a line number to set one)' }); + const predictBtn = button('Predict mode', () => { predictOn = !predictOn; predictBtn.classList.toggle('on', predictOn); renderPredict(); }, { class: 'btn-small', title: 'Say what the next step will write before you take it (P)' }); + const writesBtn = button('Only writes', () => { onlyWrites = !onlyWrites; writesBtn.classList.toggle('on', onlyWrites); goto(t); }, { class: 'btn-small', title: 'Hide steps that change nothing' }); + const speedCtl = el('input', { type: 'range', min: 60, max: 1200, step: 10, value: 1200 - speed + 60, class: 'speed', title: 'Play speed', 'aria-label': 'Play speed', onInput: () => { speed = 1200 - Number(speedCtl.value) + 60; if (timer) { pause(); play(); } } }); + const csvBtn = button('CSV', () => exportCsv(), { class: 'btn-small btn-quiet', title: 'Download the trace table' }); + add(row2, passBack, passFwd, toBreak, predictBtn, drawsBody ? writesBtn : null, el('span', { class: 'spacer' }), el('span', {}, 'speed'), speedCtl, csvBtn); + + function pause() { if (timer) { clearInterval(timer); timer = null; playBtn.textContent = 'Play'; } } + function play() { + if (!trace || t >= trace.count) t = 0; + playBtn.textContent = 'Pause'; + timer = window.setInterval(() => { + if (!trace || t >= trace.count) return pause(); + const nextLine = lineOfStep(t); + if (breakpoints.size && nextLine != null && breakpoints.has(nextLine) && t !== 0) { pause(); return; } + goto(t + 1); + }, speed); + } + + function stepForward() { + if (!trace) return; + if (predictOn && t < trace.count && pendingPrediction()) { predictBox.querySelector('input')?.focus(); return; } + goto(t + 1); + } + + function lineOfStep(i: number): number | null { + if (!trace || i >= trace.count) return null; + const s: any = trace.steps[i]; + return trace.lang === 'asm' ? s.instr.lineNo + 1 : s.line ?? null; + } + + function runToBreakpoint() { + if (!trace) return; + if (!breakpoints.size) { status.textContent = 'No breakpoints yet: click a line number in the editor to set one.'; return; } + for (let i = t + 1; i < trace.count; i++) { const ln = lineOfStep(i); if (ln != null && breakpoints.has(ln)) { goto(i); return; } } + goto(trace.count); + } + + /** The loop the current step is inside, from the state's loop stack (pseudocode only). */ + function jumpPass(dir: 1 | -1) { + if (!trace || trace.lang === 'asm') { jumpBranch(dir); return; } + const st: any = trace.states[t]; + const loop = st?.loops?.[st.loops.length - 1]; + if (!loop) { status.textContent = 'Not inside a loop at this step.'; return; } + const passAt = (i: number) => { const s: any = trace!.states[i]; const l = s?.loops?.find((x: any) => x.line === loop.line); return l ? l.pass : null; }; + const cur = loop.pass; + if (dir > 0) { for (let i = t + 1; i <= trace.count; i++) { const p = passAt(i); if (p == null) { goto(i); return; } if (p === cur + 1) { goto(i); return; } } goto(trace.count); } + else { let i = t - 1; while (i > 0 && passAt(i) === cur) i--; const target = passAt(i); if (target == null) { goto(Math.max(0, i)); return; } while (i > 0 && passAt(i - 1) === target) i--; goto(i); } + } + + /** Assembly: the next (or previous) taken backward branch is the next pass. */ + function jumpBranch(dir: 1 | -1) { + if (!trace) return; + const isBack = (i: number) => { const s: any = trace!.steps[i]; return s?.branch && s.branch.taken && s.pcAfter < s.pcBefore; }; + if (dir > 0) { for (let i = t; i < trace.count; i++) if (isBack(i)) { goto(i + 1); return; } goto(trace.count); } + else { for (let i = t - 2; i >= 0; i--) if (isBack(i)) { goto(i + 1); return; } goto(0); } + } + + function goto(n: number) { + if (!trace) return; + t = Math.max(0, Math.min(n, trace.count)); + session.state.t = t; + slider.value = String(t); + counter.textContent = `step ${t} of ${trace.count}`; + const fr = frameAt(trace, t); + const nextLine = (fr.next as any)?.line ?? asmLine(trace, (fr.state as any)?.pc) ?? null; + const lastLine = (fr.last as any)?.line ?? asmLine(trace, (fr.last as any)?.pcBefore) ?? null; + opts.onStep?.(nextLine, lastLine, hitsUpTo(trace, t)); + renderNext(fr); + renderPredict(); + renderBody(fr); + session.notifyStep(t); + } + + function asmLine(tr: Trace, pc: number | undefined): number | null { + if (tr.lang !== 'asm' || pc == null) return null; + const instr = (tr.raw as any).trace.program.instrs[pc]; + return instr ? instr.lineNo + 1 : null; + } + + function hitsUpTo(tr: Trace, upto: number): Map { + const m = new Map(); + for (let i = 0; i < upto; i++) { const ln = lineOfStep(i); if (ln != null) m.set(ln, (m.get(ln) || 0) + 1); } + return m; + } + + /* ---------- what runs next ---------- */ + + function renderNext(fr: ReturnType) { + clear(nextBox); + if (!trace) return; + nextBox.className = 'trace-next'; + nextBox.title = ''; + // The box keeps one height whatever the step (two lines, in CSS): the step's line, and under it what it reads + // and writes. Each line is cut with an ellipsis rather than wrapped, and the whole text is in the tooltip. + const line = el('div', { class: 'trace-next-line' }); + add(nextBox, line); + if (!fr.next) { + nextBox.classList.add(trace.error ? 'k-error' : 'k-done'); + add(line, 'The run has finished.', trace.error ? ` It stopped with: ${trace.error.message}` : ''); + nextBox.title = line.textContent ?? ''; + return; + } + const s: any = fr.next; + if (trace.lang !== 'asm') { const fam = familyOf(s, trace.lang); nextBox.classList.add(`k-${fam}`); } + let sub = ''; + if (trace.lang === 'asm') { + const ins = s.instr; + add(line, 'Next: ', el('span', { class: 'mono' }, `${ins.op} ${ins.operands.map((o: any) => o.source ?? '').join(', ')}`), el('span', { class: 'muted' }, ` on line ${ins.lineNo + 1}`)); + } else { + const srcLine = sourceLine(s.line); + add(line, 'Next: line ', String(s.line ?? '?'), srcLine ? el('span', { class: 'mono' }, ` ${srcLine.trim()}`) : null); + const reads = (s.reads || []).map((r: any) => r.path ? `${r.name}[${r.path.join(', ')}]` : r.name); + const writes = (s.writes || []).map((w: any) => w.path ? `${w.name}[${w.path.join(', ')}]` : w.name); + sub = [reads.length ? `reads ${[...new Set(reads)].join(', ')}` : '', writes.length ? `writes ${[...new Set(writes)].join(', ')}` : ''].filter(Boolean).join(' · '); + } + // the second line is always there, empty or not, so a step that reads nothing does not shrink the box + add(nextBox, el('div', { class: 'trace-next-sub small muted' }, sub || '\u00a0')); + const fam = trace.lang !== 'asm' ? FAMILY_LABEL[familyOf(s, trace.lang)] : ''; + nextBox.title = [fam, line.textContent?.trim(), sub].filter(Boolean).join('\n'); + } + + function sourceLine(line: number | null): string | null { + if (line == null || !trace) return null; + const src = trace.lang === 'lingo' ? session.source('lingo') : trace.lang === 'matho' ? session.source('matho') : trace.lang === 'mojo' ? session.source('mojo') : session.source('pseudo'); + return src.split('\n')[line - 1] ?? null; + } + + /* ---------- predict mode ---------- */ + + /** The variable the next step writes, if exactly one scalar it is worth predicting. */ + function pendingPrediction(): { name: string; frame: number } | null { + if (!trace || trace.lang === 'asm') return null; + const s: any = trace.steps[t]; + const writes = (s?.writes || []).filter((w: any) => !w.path); + if (writes.length !== 1) return null; + return { name: writes[0].name, frame: writes[0].frame }; + } + + function valueAfter(name: string, frameId: number, at: number): { text: string } | null { + if (!trace) return null; + const st: any = trace.states[at]; + const f = (st?.frames || []).find((x: any) => x.id === frameId) || (st?.frames || []).slice(-1)[0]; + const v = varIn(f?.vars, name); + if (v && typeof v.text === 'string') return { text: v.text }; // a Mojo value carries its own display + if (!v || v.value === UNSET || typeof v.value === 'symbol') return null; + return { text: formatValue(v.value, v.type) }; + } + + function renderPredict() { + clear(predictBox); + if (!predictOn || !trace || trace.lang === 'asm') { predictBox.style.display = 'none'; return; } + predictBox.style.display = ''; + const p = pendingPrediction(); + const scoreEl = el('span', { class: 'predict-score' }, score.asked ? `${score.right} of ${score.asked} right` : 'no predictions yet'); + if (!p) { add(predictBox, el('div', { class: 'predict-row' }, el('span', { class: 'muted' }, t >= trace.count ? 'The run has finished.' : 'The next step writes nothing to predict; step on.'), scoreEl)); return; } + const input = el('input', { class: 'input mono', placeholder: `value of ${p.name} after this step`, style: { minWidth: '200px' } }); + const result = el('span'); + const check = () => { + const want = valueAfter(p.name, p.frame, t + 1); + const got = input.value.trim(); + if (!got) return; + score.asked++; + const norm = (x: string) => x.replace(/\s+/g, '').replace(/^"(.*)"$/, '$1').replace(/^'(.*)'$/, '$1').toUpperCase(); + const ok = !!want && norm(want.text) === norm(got); + if (ok) score.right++; + clear(result); + add(result, el('span', { class: ok ? 'predict-right' : 'predict-wrong' }, ok ? 'Right.' : `It will be ${want?.text ?? 'unset'}.`)); + scoreEl.textContent = `${score.right} of ${score.asked} right`; + input.disabled = true; + setTimeout(() => goto(t + 1), ok ? 500 : 1400); + }; + input.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); check(); } e.stopPropagation(); }); + add(predictBox, `Before you step: what will `, el('b', { class: 'mono' }, p.name), ' hold after this line?', + el('div', { class: 'predict-row' }, input, button('Check', check, { class: 'btn-small btn-primary' }), button('Skip', () => goto(t + 1), { class: 'btn-small btn-quiet' }), result, scoreEl)); + } + + /* ---------- pseudocode ---------- */ + + function renderBody(fr: ReturnType) { + clear(body); clear(varsHost); clear(tableHost); + if (!trace) return; + if (trace.lang === 'asm') renderAsm(fr); else renderPseudo(fr); + } + + /** The last step before `at` that wrote `name` in frame `frameId`. */ + function lastWrite(name: string, frameId: number, at: number): number | null { + if (!trace) return null; + for (let i = at - 1; i >= 0; i--) { const s: any = trace.steps[i]; if ((s.writes || []).some((w: any) => w.name === name && (w.frame == null || w.frame === frameId))) return i; } + return null; + } + + function ruler(value: any, type: any, reads: number[], writes: number[]): HTMLElement | null { + let cells: string[] | null = null; + if (typeof value === 'string') cells = value.length > 1 ? [...value] : null; + else if (Array.isArray(value) && value.length <= 64 && value.every((x) => typeof x !== 'object')) cells = value.map((x) => formatValue(x, type?.of, { bareChar: true })); + if (!cells || !cells.length || cells.length > 80) return null; + const r = el('div', { class: 'ruler' }); + cells.forEach((c, i) => add(r, el('span', { class: 'ruler-cell' + (reads.includes(i) ? ' read' : '') + (writes.includes(i) ? ' wrote' : '') }, el('b', {}, c === ' ' ? '␣' : c), el('i', {}, String(i))))); + return r; + } + + /** Every value a name took over the whole run, with the step that set it: the variable's timeline. */ + const histCache = new Map>(); + function history(name: string, frameId: number): Array<{ step: number; text: string }> { + const key = `${frameId}:${name}`; + const hit = histCache.get(key); + if (hit) return hit; + const out: Array<{ step: number; text: string }> = []; + if (trace) for (let i = 0; i < trace.count; i++) { + const s: any = trace.steps[i]; + if (!(s.writes || []).some((w: any) => w.name === name && (w.frame == null || w.frame === frameId))) continue; + const v = valueAfter(name, frameId, i + 1); + if (!v) continue; + if (out.length && out[out.length - 1].text === v.text) continue; + out.push({ step: i, text: v.text }); + } + histCache.set(key, out); + return out; + } + + /** The timeline as a row of chips: past values solid, the current one marked, values still to come faded. Click one to go there. */ + function track(name: string, frameId: number): HTMLElement | null { + const h = history(name, frameId); + if (h.length < 2) return null; + const cur = [...h].reverse().find((x) => x.step < t); + const row = el('div', { class: 'var-track', title: `${name}: every value it takes in this run, in order. Click one to step to where it was set.` }); + const MAX = 14; + let shown = h; + if (h.length > MAX) { + const ci = cur ? h.indexOf(cur) : 0; + const from = Math.max(0, Math.min(ci - 6, h.length - MAX)); + shown = h.slice(from, from + MAX); + if (from > 0) add(row, el('span', { class: 'var-chip var-chip-more' }, `…${from}`)); + } + for (const x of shown) { + const cls = 'var-chip' + (x === cur ? ' var-chip-now' : x.step < t ? ' var-chip-past' : ' var-chip-next'); + add(row, el('button', { type: 'button', class: cls, title: `step ${x.step + 1}`, onClick: (e: MouseEvent) => { e.stopPropagation(); goto(x.step + 1); } }, x.text.length > 18 ? x.text.slice(0, 17) + '…' : x.text)); + } + if (shown[shown.length - 1] !== h[h.length - 1]) add(row, el('span', { class: 'var-chip var-chip-more' }, `…${h.length - h.indexOf(shown[shown.length - 1]) - 1}`)); + return row; + } + + function renderPseudo(fr: ReturnType) { + const tr = trace!; + const state: any = fr.state; + if (!drawsBody) { renderStatus(state); renderOutput(tr, t >= tr.count ? tr.output.length : (state?.outputLength ?? tr.output.length)); return; } + const vars = el('div', { class: 'vars' }); + const lastWrites = ((fr.last as any)?.writes || []) as any[]; + const nextReads = ((fr.next as any)?.reads || []) as any[]; + const wroteKeys = new Set(lastWrites.map((w: any) => `${w.frame}:${w.name}`)); + const readKeys = new Set(nextReads.map((w: any) => `${w.frame}:${w.name}`)); + for (const f of (state?.frames || []).slice().reverse()) { + const table = el('table', { class: 'tbl vars-tbl' }, el('caption', {}, f.name === 'main' || !f.name ? 'main program' : `${f.name}`)); + const entries = Object.values(f.vars) as any[]; + if (!entries.length) add(table, el('tr', {}, el('td', { class: 'muted', colspan: 3 }, 'no names yet'))); + for (const v of entries) { + const key = `${f.id}:${v.name}`; + const own = typeof v.text === 'string'; // Mojo: the interpreter's display, "(moved out)" included + const unset = !own && (v.value === undefined || v.value === UNSET || typeof v.value === 'symbol'); + const shown = own ? v.text : unset ? '' : formatValue(v.value, v.type); + const prevIdx = lastWrite(v.name, f.id, t); + const prevVal = prevIdx != null ? valueAfter(v.name, f.id, prevIdx) : null; + const tl = H ? track(v.name, f.id) : null; + const hist = tl ?? (prevIdx != null ? el('div', { class: 'var-hist' }, prevVal && prevVal.text !== shown ? `was ${prevVal.text}; ` : '', el('button', { type: 'button', class: 'linkish', onClick: () => goto(prevIdx + 1) }, `changed at step ${prevIdx + 1}`)) : null); + add(table, el('tr', { class: (wroteKeys.has(key) ? 'just-wrote ' : '') + (readKeys.has(key) ? 'about-to-read' : '') }, + el('td', { class: 'mono' }, v.name), el('td', { class: 'muted' }, typeOf(v.type)), + el('td', { class: 'mono' }, unset ? el('span', { class: 'muted' }, 'no value yet') : shown, hist))); + if (!unset && !own) { + const reads = nextReads.filter((r: any) => r.name === v.name && r.frame === f.id && r.path).map((r: any) => Number(r.path[0])); + const writes = lastWrites.filter((w: any) => w.name === v.name && w.frame === f.id && w.path).map((w: any) => Number(w.path[0])); + const rl = ruler(v.value, v.type, reads, writes); + if (rl) add(table, el('tr', {}, el('td', { colspan: 3, class: 'var-ruler' }, rl))); + } + } + add(vars, table); + } + const rows = el('tbody'); + const idx: number[] = []; + for (let i = 0; i < tr.count; i++) if (!onlyWrites || ((tr.steps[i] as any).writes || []).length || i === t || i === t - 1) idx.push(i); + const pos = Math.max(0, idx.findIndex((i) => i >= t) === -1 ? idx.length - 1 : idx.findIndex((i) => i >= t)); + const win = opts.compact ? 4 : 9; + for (const i of idx.slice(Math.max(0, pos - win), pos + win)) { + const s: any = tr.steps[i]; + const w = (s.writes || []).map((x: any) => x.name).join(', '); + const fam = familyOf(s, tr.lang); + add(rows, el('tr', { class: `k-${fam} ` + (i === t - 1 ? 'row-last' : i === t ? 'row-next' : ''), onClick: () => goto(i + 1) }, + el('td', { class: 'muted step-no' }, el('span', { class: `k-dot k-${fam}`, title: FAMILY_LABEL[fam] }), String(i + 1)), el('td', { class: 'mono' }, String(s.line ?? '')), el('td', { class: 'mono' }, s.text || s.kind), el('td', { class: 'mono muted' }, w))); + } + const table = el('table', { class: 'tbl trace-tbl' }, el('thead', {}, el('tr', {}, el('th', {}, '#'), el('th', {}, 'line'), el('th', {}, 'what ran'), el('th', {}, 'wrote'))), rows); + if (H) { add(tableHost, table); add(varsHost, vars); (rows.querySelector('.row-next') ?? rows.querySelector('.row-last'))?.scrollIntoView({ block: 'nearest' }); } + else add(body, el('div', { class: 'trace-cols' }, el('div', { class: 'trace-col' }, el('h4', {}, 'Trace table'), table), el('div', { class: 'trace-col' }, el('h4', {}, 'Variables'), vars))); + renderStatus(state); + // at the end everything is shown, including the 'returned' line the run appends after its last step + renderOutput(tr, t >= tr.count ? tr.output.length : (state?.outputLength ?? tr.output.length)); + } + + /** The loops in flight, one line under the controls. */ + function renderStatus(state: any) { + const loops = state?.loops || []; + const lingo = trace?.lang === 'lingo'; + const say = (l: any) => { + // a lingo run is the pseudo's run underneath, so its loops name pseudo lines: name the English line instead + const line = lingo ? lingoLine(l.line) ?? l.line : l.line; + const what = lingo ? 'The loop' : l.kind === 'For' ? 'FOR' : l.kind === 'ForEach' ? 'FOR EACH' : String(l.kind).toUpperCase(); + // pass 0 is the moment before the first pass, when the trace's next row already reads "pass 1" + return `${what} on line ${line}: ${l.pass > 0 ? `pass ${l.pass}` : 'about to start its first pass'}`; + }; + status.textContent = loops.map(say).join(' · '); + status.title = status.textContent; + } + + /** The lingo line a pseudo line came from, read off the lingo run's own steps. */ + let lingoLines: { trace: any; map: Map } | null = null; + function lingoLine(pseudoLine: number): number | undefined { + if (lingoLines?.trace !== trace) { + const map = new Map(); + for (const s of (trace?.steps ?? []) as any[]) if (s.pseudoLine != null && s.line != null && !map.has(s.pseudoLine)) map.set(s.pseudoLine, s.line); + lingoLines = { trace, map }; + } + return lingoLines.map.get(pseudoLine); + } + + function typeOf(t: any): string { + if (!t) return ''; + if (typeof t === 'string') return t; + if (t.k === 'LIST') return `LIST OF ${typeOf(t.of)}`; + if (t.k === 'ARRAY') return 'ARRAY'; + if (t.k === 'HASHMAP') return 'HASHMAP'; + if (t.k === 'SET') return `SET OF ${typeOf(t.of)}`; + return t.k || t.name || ''; + } + + /* ---------- assembly ---------- */ + + const WATCH = ['rax', 'rbx', 'rcx', 'rdx', 'rsi', 'rdi', 'rbp', 'rsp', 'r8', 'r9', 'r10', 'r11', 'r12', 'r13', 'r14', 'r15']; + + function renderAsm(fr: ReturnType) { + const tr = trace!; + const st: any = fr.state; + const last: any = fr.last; + const changed = new Set((last?.diff?.regs || []).map((r: any) => r.name)); + const flagsChanged = new Set((last?.diff?.flags || []).map((f: any) => f.name)); + const regs = el('table', { class: 'tbl regs-tbl' }, el('caption', {}, 'Registers')); + for (const r of WATCH) { + const v: bigint = st.regs[r]; + add(regs, el('tr', { class: changed.has(r) ? 'just-wrote' : '' }, el('td', { class: 'mono' }, r), el('td', { class: 'mono' }, formatHex(v)), el('td', { class: 'mono muted' }, BigInt.asIntN(64, v).toString()))); + } + const flags = el('div', { class: 'flags' }, ...FLAG_NAMES.map((f: string) => el('span', { class: 'flag' + (st.flags[f] ? ' on' : '') + (flagsChanged.has(f) ? ' just-wrote' : '') }, f))); + const mem = el('div', { class: 'mem' }); + const touched = new Set((last?.accesses || []).flatMap((a: any) => Array.from({ length: a.size || 1 }, (_, k) => Number(a.addr) + k))); + for (const region of st.mem) { + if (region.hidden && ![...touched].some((a) => a >= region.addr && a < region.addr + region.bytes.length)) continue; + const row = el('div', { class: 'mem-region' }, el('div', { class: 'mem-label' }, `${region.label} at ${formatHex(BigInt(region.addr), 4)}`)); + const cells = el('div', { class: 'mem-cells' }); + const max = Math.min(region.bytes.length, 64); + for (let i = 0; i < max; i++) { + const b = region.bytes[i]; + const ch = b >= 32 && b < 127 ? String.fromCharCode(b) : '·'; + add(cells, el('span', { class: 'mem-cell' + (touched.has(region.addr + i) ? ' touched' : ''), title: `${formatHex(BigInt(region.addr + i), 4)} = ${b}` }, el('b', {}, ch), el('i', {}, b.toString(16).padStart(2, '0')))); + } + if (region.bytes.length > max) add(cells, el('span', { class: 'muted' }, ` … ${region.bytes.length - max} more`)); + add(row, cells); add(mem, row); + } + const explain = el('div', { class: 'explain' }); + if (last) { + const ins = last.instr; + const parts: string[] = [`${ins.op} ${ins.operands.map((o: any) => o.source ?? '').join(', ')}`]; + if (last.alu) parts.push(`${last.alu.kind}: ${formatHex(last.alu.a, last.alu.width)}${last.alu.b != null ? ' , ' + formatHex(last.alu.b, last.alu.width) : ''} → ${formatHex(last.alu.result, last.alu.width)}`); + if (last.branch) parts.push(last.branch.taken ? `branch taken${last.prediction ? (last.prediction.correct ? ', predicted' : ', mispredicted') : ''}` : `not taken${last.prediction ? (last.prediction.correct ? ', predicted' : ', mispredicted') : ''}`); + for (const r of last.diff.regs || []) parts.push(`${r.name}: ${formatHex(r.before)} → ${formatHex(r.after)}`); + for (const m of last.diff.mem || []) parts.push(`[${formatHex(BigInt(m.addr), 4)}]: ${m.before} → ${m.after}`); + if (last.diff.out) parts.push(`wrote "${last.diff.out}"`); + add(explain, el('h4', {}, 'What that instruction did'), el('ul', {}, ...parts.map((p) => el('li', { class: 'mono' }, p)))); + } else add(explain, el('p', { class: 'muted' }, 'Nothing has run yet. Step once.')); + if (H) { add(varsHost, regs, el('h4', {}, 'Flags'), flags); add(tableHost, el('h4', {}, 'Memory'), mem, explain); } + else add(body, el('div', { class: 'trace-cols' }, el('div', { class: 'trace-col' }, regs, el('h4', {}, 'Flags'), flags), el('div', { class: 'trace-col' }, el('h4', {}, 'Memory'), mem, explain))); + const stats = (tr.raw as any).trace.stats; + status.textContent = `${stats.instructions} instructions, ${stats.branches} branches (${stats.mispredicts} mispredicted), ${stats.reads} loads, ${stats.writes} stores` + (st.halted ? ', halted' : ''); + renderOutput(tr, t >= tr.count ? tr.output.length : (tr.output.length > 0 && tr.output[0] && !tr.output[0].startsWith('rax =') ? 1 : 0)); + } + + function renderOutput(tr: Trace, upto: number) { + const lines = tr.output.slice(0, upto); + const err = tr.error && t >= tr.count ? tr.error.message : null; + output.textContent = lines.join('\n') + (err ? `\n\n⚠ ${err}` : '') + (tr.truncated && t >= tr.count ? '\n(the run was cut off at the step limit)' : ''); + output.style.display = output.textContent.trim() ? '' : 'none'; + opts.onOutput?.(lines, err); + } + + function exportCsv() { + if (!trace) return; + const rows = trace.lang === 'asm' + ? [['step', 'line', 'instruction', 'changed'], ...trace.steps.map((s: any, i: number) => [i + 1, s.instr.lineNo + 1, `${s.instr.op} ${s.instr.operands.map((o: any) => o.source ?? '').join(', ')}`, (s.diff.regs || []).map((r: any) => `${r.name}=${formatHex(r.after)}`).join(' ')])] + : [['step', 'line', 'what ran', 'wrote'], ...trace.steps.map((s: any, i: number) => [i + 1, s.line ?? '', s.text || s.kind, (s.writes || []).map((w: any) => w.name).join(' ')])]; + const blob = new Blob([toCsv(rows)], { type: 'text/csv' }); + const url = URL.createObjectURL(blob); + const a = el('a', { href: url, download: `${(session.state.title || 'procedure').toLowerCase().replace(/[^a-z0-9]+/g, '-')}-trace.csv` }); + document.body.appendChild(a); a.click(); a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 1000); + } + + function refresh() { + trace = session.trace(); + histCache.clear(); + clear(body); + if (!trace) { + const why = session.runError || firstError(session) || 'Nothing to run yet.'; + status.textContent = ''; + clear(nextBox); nextBox.className = 'trace-next k-empty'; add(nextBox, el('div', { class: 'trace-next-line' }, why)); nextBox.title = String(why); predictBox.style.display = 'none'; + output.style.display = 'none'; opts.onOutput?.([], null); + clear(varsHost); clear(tableHost); + if (!H) add(body, el('p', { class: 'muted trace-empty' }, why)); + slider.max = '0'; counter.textContent = ''; + opts.onStep?.(null, null, new Map()); + return; + } + slider.max = String(trace.count); + goto(Math.min(t, trace.count)); + } + + function firstError(s: Session): string | null { + const lang = s.traceLang(); + const d = s.diagnostics(lang).find((x) => x.severity === 'error'); + return d ? `Line ${d.line}: ${d.message}` : null; + } + + const key = (e: KeyboardEvent) => { + const target = e.target as HTMLElement | null; + const tag = target?.tagName; + // anything that takes typing keeps its keys: form fields, and the editor (a contenteditable) + if (tag === 'TEXTAREA' || tag === 'INPUT' || tag === 'SELECT' || target?.isContentEditable || target?.closest?.('.cm-editor')) return; + if (e.key === 'ArrowRight') { e.shiftKey ? jumpPass(1) : stepForward(); e.preventDefault(); } + else if (e.key === 'ArrowLeft') { e.shiftKey ? jumpPass(-1) : goto(t - 1); e.preventDefault(); } + else if (e.key === 'Home') { goto(0); e.preventDefault(); } + else if (e.key === 'End') { goto(trace?.count ?? 0); e.preventDefault(); } + else if (e.key === ' ') { timer ? pause() : play(); e.preventDefault(); } + else if (e.key === 'p' || e.key === 'P') { predictBtn.click(); } + else if (e.key === 'b' || e.key === 'B') { runToBreakpoint(); } + }; + root.tabIndex = 0; + window.addEventListener('keydown', key); + + const off = session.onChange(() => refresh()); + refresh(); + return { + goto, + get t() { return t; }, + breakpoints, + toggleBreakpoint(line: number) { if (breakpoints.has(line)) breakpoints.delete(line); else breakpoints.add(line); opts.onBreakpoints?.(breakpoints); }, + destroy() { pause(); off(); window.removeEventListener('keydown', key); }, + }; +} diff --git a/src/ui/views/viz.ts b/src/ui/views/viz.ts new file mode 100644 index 0000000..1b30ce9 --- /dev/null +++ b/src/ui/views/viz.ts @@ -0,0 +1,861 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +/** + * Three pictures of one procedure, drawn from the pseudo and the last run: + * + * flow a flowchart of the routine, laid out from its structure (so loops + * loop and branches branch), with every box shaded by how often its + * line ran and every edge labeled with how often it was taken; + * data the data-flow graph: which names feed which, from the parameters + * on the left to RETURN and OUTPUT on the right, one arrow per + * assignment, dashed when a condition decides rather than computes; + * table the table of values a student draws by hand: a column per step that + * changed something, a row per name, the new value in the cell. + * + * Everything is SVG or a plain table built from the Session; nothing here + * touches an engine. The routine drawn is the one the run call names. + */ +import { toTsv } from '../../core/csv.js'; +import { el, add, clear, button } from '../dom.js'; +import type { Session } from '../../core/session.js'; +import { mojoRoutine, mojoFunctions } from '#core/mojo/flowir.js'; +import type { Trace } from '#core/common/types.js'; +import { formatValue, typeName } from '#core/engines/pseudo/lang.js'; +import { sourceOf } from '#core/engines/pseudo/parse.js'; +import type { PanelHooks } from './panels.js'; + +/* ------------------------------------------------------------------ */ +/* Shared */ +/* ------------------------------------------------------------------ */ + +const NS = 'http://www.w3.org/2000/svg'; + +function svg(tag: K, attrs: Record = {}, ...children: Array): SVGElementTagNameMap[K] { + const n = document.createElementNS(NS, tag); + for (const [k, v] of Object.entries(attrs)) { + if (v == null || v === false) continue; + if (k.startsWith('on') && typeof v === 'function') n.addEventListener(k.slice(2).toLowerCase(), v); + else n.setAttribute(k, String(v)); + } + for (const c of children) { if (c == null) continue; n.appendChild(typeof c === 'string' ? document.createTextNode(c) : c); } + return n; +} + +interface Routine { name: string; kind: 'Function' | 'Procedure' | 'main'; params: any[]; body: any[]; line: number; returns: any; symbols: any[] } + +/** The routine the run call names, else the main program, else the first subroutine. */ +/** The view's title; for Mojo, a choice of which function to draw. */ +function titleOf(session: Session, r: Routine, rerender: () => void): HTMLElement { + const p = session.state.lang === 'mojo' ? session.parsedMojo() : null; + const names = p?.program ? mojoFunctions(p.program.module) : []; + if (names.length < 2) return el('span', { class: 'viz-title' }, r.kind === 'main' ? 'the main program' : `${r.name}`); + const sel = el('select', { class: 'select', 'aria-label': 'Which function to draw', title: 'Which function to draw', onChange: () => { setMojoFocus(sel.value); rerender(); } }, + ...names.map((n) => el('option', { value: n, selected: n === r.name }, n))); + return el('label', { class: 'viz-title' }, sel); +} + +/** For Mojo: the function chosen in the view, else the one the run spent most steps in, else main. */ +export let mojoFocus: string | null = null; +export function setMojoFocus(name: string | null): void { mojoFocus = name; } + +function mojoRoutineOf(session: Session): Routine | null { + const p = session.parsedMojo(); + if (!p || !p.program || p.program.module.unread) return null; + const names = mojoFunctions(p.program.module); + let name = mojoFocus && names.includes(mojoFocus) ? mojoFocus : null; + if (!name) { + const trace = session.trace(); + if (trace?.lang === 'mojo') { + const count = new Map(); + for (const st of trace.steps as any[]) if (st.sub) count.set(st.sub, (count.get(st.sub) ?? 0) + 1); + name = [...count].filter(([n]) => names.includes(n)).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null; + } + } + return mojoRoutine(p.program.module, name ?? undefined) as Routine | null; +} + +export function routineOf(session: Session): Routine | null { + if (session.state.lang === 'mojo') return mojoRoutineOf(session); + const p = session.parsedPseudo(); + if (!p || !p.ok || !p.program) return null; + const prog = p.program.program; + const call = session.callText(); + const m = call ? /^\s*([A-Za-z_]\w*)/.exec(call) : null; + const pick = (sub: any): Routine => ({ name: sub.name, kind: sub.node.kind, params: sub.params?.length ? sub.params : sub.node.params || [], body: sub.node.body || [], line: sub.node.line, returns: sub.returns ?? sub.node.returns, symbols: sub.symbols || [] }); + if (m) { const sub = prog.subs.get(m[1].toUpperCase()); if (sub && sub.node) return pick(sub); } + if (prog.main?.body?.length) return { name: 'main', kind: 'main', params: [], body: prog.main.body, line: prog.main.body[0]?.line ?? 1, returns: null, symbols: prog.main.symbols || [] }; + const first = [...prog.subs.values()].find((s: any) => s.node); + return first ? pick(first) : null; +} + +/** How often each pseudo line ran in the trace up to step `upto` (lingo and matho traces carry the pseudo line on each step). */ +function pseudoHits(trace: Trace | null, upto = Infinity): Map { + const hits = new Map(); + if (!trace || trace.lang === 'asm') return hits; + (trace.steps as any[]).slice(0, upto).forEach((s) => { const ln = s.pseudoLine ?? s.line; if (ln != null) hits.set(ln, (hits.get(ln) || 0) + 1); }); + return hits; +} + +/** The pseudo line a step is on. */ +function stepLine(s: any): number | null { return s ? (s.pseudoLine ?? s.line ?? null) : null; } + +/** A node's classes for where the stepper is. */ +function cursorClass(ctx: FlowCtx, line: number | null): string { + if (line == null) return ''; + return (ctx.current === line ? ' flow-current' : '') + (ctx.last === line ? ' flow-last' : ''); +} + +function sourceLines(session: Session): string[] { + // Mojo: drop a trailing # comment (outside quotes) as pseudo's // comments are dropped + if (session.state.lang === 'mojo') return session.source('mojo').split('\n').map((l) => { let q: string | null = null; for (let i = 0; i < l.length; i++) { const c = l[i]; if (q) { if (c === '\\') i++; else if (c === q) q = null; } else if (c === '"' || c === "'") q = c; else if (c === '#') return l.slice(0, i).trimEnd(); } return l; }); + return session.source('pseudo').split('\n'); +} +function lineText(lines: string[], line: number): string { return (lines[line - 1] ?? '').replace(/\s*\/\/.*$/, '').trim(); } +function truncate(s: string, n: number): string { return s.length > n ? s.slice(0, n - 1) + '…' : s; } + +/** Every Name an expression (or statement fragment) mentions, in order, without duplicates. */ +function namesIn(e: any, out: string[] = []): string[] { + if (!e || typeof e !== 'object') return out; + if (Array.isArray(e)) { for (const x of e) namesIn(x, out); return out; } + if (e.kind === 'Name') { if (!out.includes(e.name)) out.push(e.name); return out; } + if (e.kind === 'CallExpr') { namesIn(e.args, out); return out; } + for (const [k, v] of Object.entries(e)) { if (k === 'type' || k === 'line' || k === 'col' || typeof v !== 'object') continue; namesIn(v, out); } + return out; +} + +function rootName(target: any): string | null { + let t = target; + while (t && (t.kind === 'Index' || t.kind === 'Field')) t = t.target; + return t && t.kind === 'Name' ? t.name : null; +} + +/** Scroll `box` (and only `box`) so that `target` is in view; scrollIntoView would also move the page. */ +function revealIn(box: HTMLElement | null, target: Element | null): void { + if (!box || !target) return; + const b = box.getBoundingClientRect(), t = target.getBoundingClientRect(); + if (t.left < b.left) box.scrollLeft += t.left - b.left - 24; + else if (t.right > b.right) box.scrollLeft += t.right - b.right + 24; + if (t.top < b.top) box.scrollTop += t.top - b.top - 24; + else if (t.bottom > b.bottom) box.scrollTop += t.bottom - b.bottom + 24; +} + +function emptyNote(root: HTMLElement, session: Session, what: string): void { + const p = session.parsedPseudo(); + add(root, el('p', { class: 'muted' }, !p ? `Write some pseudo (or lingo, or an equation) and the ${what} appears here.` : !p.ok ? `The pseudo has errors; fix them in the problems view and the ${what} appears here.` : `Nothing to draw yet.`)); +} + +/* ------------------------------------------------------------------ */ +/* Flowchart */ +/* ------------------------------------------------------------------ */ + +const FH = 30; // box height +const GAP = 22; // vertical gap between boxes +const HGAP = 34; // horizontal gap between branches +const CH = 7.3; // approximate width of one monospace character at 12px +const MAXCH = 40; // longest text in a box + +interface Block { + w: number; h: number; + /** x of the entry/exit spine inside the block */ + cx: number; + /** false when control never falls out of the bottom (RETURN, BREAK) */ + exits: boolean; + /** the line whose hits count how often the block was entered */ + entryLine: number | null; + draw(g: SVGGElement, x: number, y: number): void; +} + +interface FlowCtx { + /** The line about to run and the line that just ran, when the chart follows the stepper. */ + current: number | null; + last: number | null; + lines: string[]; + /** the pseudo line of every step, in order */ + stepLines: number[]; + hits: Map; + maxHits: number; + hasTrace: boolean; + onLine: ((line: number) => void) | null; + /** the set of lines of the loop headers, so the trace's loop steps are counted right */ + loopLines: Set; +} + +/** How often a loop went round again and how often it finished: from the step that follows each visit to its test line. */ +function loopCounts(ctx: FlowCtx, testLine: number, bodyFrom: number, bodyTo: number): { again: number; done: number } | null { + if (!ctx.hasTrace) return null; + let again = 0, done = 0; + for (let i = 0; i < ctx.stepLines.length; i++) { + if (ctx.stepLines[i] !== testLine) continue; + const next = ctx.stepLines[i + 1]; + if (next == null) { done++; continue; } + if (next >= bodyFrom && next <= bodyTo) again++; else if (next !== testLine) done++; + } + return { again, done }; +} + +function textWidth(s: string): number { return Math.max(96, Math.min(CH * MAXCH + 28, s.length * CH + 28)); } + +function shadeFor(ctx: FlowCtx, line: number | null): { fill: string; cls: string; count: number | null } { + if (!ctx.hasTrace || line == null) return { fill: 'var(--paper-2)', cls: '', count: null }; + const n = ctx.hits.get(line) || 0; + if (!n) return { fill: 'var(--paper-3)', cls: 'flow-never', count: 0 }; + const a = 0.1 + 0.55 * Math.sqrt(n / Math.max(1, ctx.maxHits)); + return { fill: `color-mix(in srgb, var(--accent) ${Math.round(a * 100)}%, var(--paper-2))`, cls: '', count: n }; +} + +function label(g: SVGGElement, x: number, y: number, text: string, cls = 'flow-text', anchor = 'middle'): void { + g.appendChild(svg('text', { x, y, class: cls, 'text-anchor': anchor, 'dominant-baseline': 'central' }, text)); +} + +function badge(g: SVGGElement, x: number, y: number, count: number | null): void { + if (count == null) return; + const t = count === 0 ? 'never ran' : `×${count.toLocaleString('en-US')}`; + const w = t.length * 6 + 10; + g.appendChild(svg('rect', { x: x - w + 4, y: y - 9, width: w, height: 16, rx: 8, class: 'flow-badge' + (count === 0 ? ' flow-badge-never' : '') })); + g.appendChild(svg('text', { x: x - w / 2 + 4, y, class: 'flow-badge-text', 'text-anchor': 'middle', 'dominant-baseline': 'central' }, t)); +} + +function line(g: SVGGElement, pts: Array<[number, number]>, opts: { arrow?: boolean; cls?: string } = {}): void { + const d = pts.map((p, i) => `${i ? 'L' : 'M'}${p[0]} ${p[1]}`).join(' '); + g.appendChild(svg('path', { d, class: 'flow-edge ' + (opts.cls || ''), 'marker-end': opts.arrow === false ? null : 'url(#flow-arrow)' })); +} + +function edgeLabel(g: SVGGElement, x: number, y: number, text: string): void { + const w = text.length * 6.2 + 8; + g.appendChild(svg('rect', { x: x - w / 2, y: y - 8, width: w, height: 16, rx: 3, class: 'flow-edge-label-bg' })); + g.appendChild(svg('text', { x, y, class: 'flow-edge-label', 'text-anchor': 'middle', 'dominant-baseline': 'central' }, text)); +} + +function clickable(ctx: FlowCtx, node: SVGElement, line: number | null, full: string): void { + node.appendChild(svg('title', {}, line != null ? `line ${line}: ${full}` : full)); + if (ctx.onLine && line != null) { node.classList.add('flow-clickable'); node.addEventListener('click', () => ctx.onLine!(line)); } +} + +/** A plain statement box; `shape` picks the flowchart glyph. */ +function box(ctx: FlowCtx, lineNo: number, text: string, shape: 'rect' | 'pill' | 'para' | 'term' = 'rect'): Block { + const t = truncate(text, MAXCH); + const w = textWidth(t); + return { + w, h: FH, cx: w / 2, exits: shape !== 'term', entryLine: lineNo, + draw(g, x, y) { + const s = shadeFor(ctx, lineNo); + const grp = svg('g', { class: 'flow-node ' + s.cls + cursorClass(ctx, lineNo), 'data-line': lineNo }); + if (shape === 'rect') grp.appendChild(svg('rect', { x, y, width: w, height: FH, rx: 5, fill: s.fill, class: 'flow-shape' })); + else if (shape === 'pill' || shape === 'term') grp.appendChild(svg('rect', { x, y, width: w, height: FH, rx: FH / 2, fill: s.fill, class: 'flow-shape' + (shape === 'term' ? ' flow-term' : '') })); + else grp.appendChild(svg('path', { d: `M${x + 10} ${y} H${x + w} L${x + w - 10} ${y + FH} H${x} Z`, fill: s.fill, class: 'flow-shape' })); + label(grp, x + w / 2, y + FH / 2, t); + badge(grp, x + w, y, s.count); + clickable(ctx, grp, lineNo, text); + g.appendChild(grp); + }, + }; +} + +function passthrough(): Block { return { w: 24, h: 0, cx: 12, exits: true, entryLine: null, draw() { /* nothing */ } }; } + +/** Blocks stacked, spines aligned, arrows between them. */ +function sequence(blocks: Block[]): Block { + if (!blocks.length) return passthrough(); + if (blocks.length === 1) return blocks[0]; + const left = Math.max(...blocks.map((b) => b.cx)); + const right = Math.max(...blocks.map((b) => b.w - b.cx)); + const h = blocks.reduce((a, b) => a + b.h, 0) + GAP * (blocks.length - 1); + const lastExits = blocks[blocks.length - 1].exits; + return { + w: left + right, h, cx: left, exits: lastExits, entryLine: blocks[0].entryLine, + draw(g, x, y) { + let yy = y; + blocks.forEach((b, i) => { + b.draw(g, x + left - b.cx, yy); + if (i < blocks.length - 1 && b.exits) line(g, [[x + left, yy + b.h], [x + left, yy + b.h + GAP]]); + yy += b.h + GAP; + }); + }, + }; +} + +/** A diamond on top, arms fanned out underneath, a merge bus below. Used for IF, ELSEIF chains and CASE. */ +function branching(ctx: FlowCtx, lineNo: number, condText: string, arms: Array<{ label: string; block: Block; countLine: number | null }>, fallthroughLabel: string | null): Block { + const t = truncate(condText, MAXCH); + const dw = Math.max(130, t.length * CH * 1.45 + 50); + const dh = 48; + const armsW = arms.reduce((a, b) => a + b.block.w, 0) + HGAP * (arms.length - 1); + const w = Math.max(armsW, dw + 24); + const off = (w - armsW) / 2; + const bodyH = Math.max(...arms.map((a) => a.block.h), 0); + const busY = dh + 20; // the fan-out bus + const topY = busY + 18; // where arms begin + const mergeY = topY + bodyH + GAP; // the merge bus + const h = mergeY + 12; + const anyExit = arms.some((a) => a.block.exits); + // the diamond is centered over the arms + const cx = w / 2; + return { + w, h, cx, exits: anyExit, entryLine: lineNo, + draw(g, x, y) { + const s = shadeFor(ctx, lineNo); + const grp = svg('g', { class: 'flow-node ' + s.cls + cursorClass(ctx, lineNo), 'data-line': lineNo }); + const dx = x + cx; + grp.appendChild(svg('path', { d: `M${dx} ${y} L${dx + dw / 2} ${y + dh / 2} L${dx} ${y + dh} L${dx - dw / 2} ${y + dh / 2} Z`, fill: s.fill, class: 'flow-shape flow-diamond' })); + label(grp, dx, y + dh / 2, t); + badge(grp, dx + dw / 2 + 6, y + 6, s.count); + clickable(ctx, grp, lineNo, condText); + g.appendChild(grp); + // fan out + let ax = x + off; + const armX: number[] = []; + for (const a of arms) { armX.push(ax + a.block.cx); ax += a.block.w + HGAP; } + const minX = Math.min(dx, ...armX), maxX = Math.max(dx, ...armX); + line(g, [[dx, y + dh], [dx, y + busY]], { arrow: false }); + if (arms.length > 1 || armX[0] !== dx) line(g, [[minX, y + busY], [maxX, y + busY]], { arrow: false }); + ax = x + off; + arms.forEach((a, i) => { + const b = a.block; + const sx = armX[i]; + line(g, [[sx, y + busY], [sx, y + topY]], { arrow: b.h > 0 }); + let n = ctx.hasTrace && a.countLine != null ? ctx.hits.get(a.countLine) || 0 : null; + if (ctx.hasTrace && n == null && arms.length === 2 && i === 1 && arms[0].countLine != null) n = Math.max(0, (ctx.hits.get(lineNo) || 0) - (ctx.hits.get(arms[0].countLine) || 0)); + const lbl = a.label + (n != null ? ` ×${n}` : ''); + if (lbl.trim()) edgeLabel(g, arms.length === 1 ? sx + 22 : i === 0 ? sx - 22 : i === arms.length - 1 ? sx + 22 : sx, y + busY + 9, lbl); + b.draw(g, ax, y + topY); + if (b.exits) line(g, [[sx, y + topY + b.h], [sx, y + mergeY]], { arrow: false }); + ax += b.w + HGAP; + }); + // merge bus + const exiting = arms.map((a, i) => (a.block.exits ? armX[i] : null)).filter((v): v is number => v != null); + if (exiting.length) { + const lo = Math.min(dx, ...exiting), hi = Math.max(dx, ...exiting); + if (lo !== hi) line(g, [[lo, y + mergeY], [hi, y + mergeY]], { arrow: false }); + line(g, [[dx, y + mergeY], [dx, y + h]], { arrow: false }); + } + void fallthroughLabel; + }, + }; +} + +/** A loop: the test on top, the body below, a back edge up the left, the exit down the right. */ +function loop(ctx: FlowCtx, lineNo: number, headText: string, body: Block, kind: 'pre' | 'post', bodyRange: [number, number] | null): Block { + const t = truncate(headText, MAXCH); + const dw = Math.max(140, t.length * CH * 1.45 + 50); + const counts = bodyRange ? loopCounts(ctx, lineNo, bodyRange[0], bodyRange[1]) : null; + const dh = 44; + const inner = Math.max(dw + 24, body.w); + const sideL = 26, sideR = 30; + const w = sideL + inner + sideR; + const cx = sideL + inner / 2; + const h = kind === 'pre' ? dh + GAP + body.h + GAP + 14 : body.h + GAP + dh + GAP + 6; + return { + w, h, cx, exits: true, entryLine: kind === 'pre' ? lineNo : body.entryLine ?? lineNo, + draw(g, x, y) { + const s = shadeFor(ctx, lineNo); + const dx = x + cx; + const drawDiamond = (dy: number) => { + const grp = svg('g', { class: 'flow-node ' + s.cls + cursorClass(ctx, lineNo), 'data-line': lineNo }); + grp.appendChild(svg('path', { d: `M${dx} ${dy} L${dx + dw / 2} ${dy + dh / 2} L${dx} ${dy + dh} L${dx - dw / 2} ${dy + dh / 2} Z`, fill: s.fill, class: 'flow-shape flow-diamond' })); + label(grp, dx, dy + dh / 2, t); + if (counts) { const tt = `${counts.again} pass${counts.again === 1 ? '' : 'es'}`; const bw = tt.length * 6 + 10; grp.appendChild(svg('rect', { x: dx + dw / 2 - bw + 10, y: dy - 8, width: bw, height: 16, rx: 8, class: 'flow-badge' + (counts.again === 0 ? ' flow-badge-never' : '') })); grp.appendChild(svg('text', { x: dx + dw / 2 - bw / 2 + 10, y: dy, class: 'flow-badge-text', 'text-anchor': 'middle', 'dominant-baseline': 'central' }, tt)); } + else badge(grp, dx + dw / 2 + 6, dy + 6, s.count); + clickable(ctx, grp, lineNo, headText); + g.appendChild(grp); + }; + const passes = counts ? counts.again : null; + if (kind === 'pre') { + drawDiamond(y); + const bodyY = y + dh + GAP; + line(g, [[dx, y + dh], [dx, bodyY]], { arrow: body.h > 0 }); + edgeLabel(g, dx + 26, y + dh + 10, 'again' + (passes != null ? ` ×${passes}` : '')); + body.draw(g, dx - body.cx, bodyY); + // back edge + const bottom = bodyY + body.h + GAP / 2; + if (body.exits) line(g, [[dx, bodyY + body.h], [dx, bottom], [x + 8, bottom], [x + 8, y + dh / 2], [dx - dw / 2, y + dh / 2]], { cls: 'flow-back' }); + // exit edge + line(g, [[dx + dw / 2, y + dh / 2], [x + w - 8, y + dh / 2], [x + w - 8, y + h], [dx, y + h]], { arrow: false }); + edgeLabel(g, x + w - 8, y + dh / 2 + 14, 'done' + (counts ? ` ×${counts.done}` : '')); + } else { + body.draw(g, dx - body.cx, y); + const dy = y + body.h + GAP; + if (body.exits) line(g, [[dx, y + body.h], [dx, dy]]); + drawDiamond(dy); + // back edge: not yet → body top + line(g, [[dx - dw / 2, dy + dh / 2], [x + 8, dy + dh / 2], [x + 8, y - 10], [dx, y - 10], [dx, y]], { cls: 'flow-back' }); + edgeLabel(g, x + 8 + 30, dy + dh / 2 - 12, 'not yet' + (counts ? ` ×${counts.again}` : '')); + line(g, [[dx, dy + dh], [dx, y + h]], { arrow: false }); + edgeLabel(g, dx + 30, dy + dh + 6, 'done' + (counts ? ` ×${counts.done}` : '')); + } + }, + }; +} + +function flowOf(ctx: FlowCtx, s: any): Block | null { + const text = (ln: number) => lineText(ctx.lines, ln); + switch (s.kind) { + case 'Declare': case 'Constant': case 'Define': case 'TypeDef': case 'SetTypeDef': case 'BlankStmt': return null; + case 'Assign': case 'Call': case 'BuiltinCall': case 'ExprStmt': return box(ctx, s.line, text(s.line)); + case 'Input': return box(ctx, s.line, text(s.line), 'para'); + case 'Output': return box(ctx, s.line, text(s.line), 'para'); + case 'Return': return box(ctx, s.line, text(s.line), 'term'); + case 'Break': case 'Continue': return box(ctx, s.line, text(s.line), 'term'); + case 'Assert': case 'Require': case 'Ensure': case 'Invariant': case 'Decreases': return box(ctx, s.line, text(s.line), 'pill'); + case 'If': { + // an ELSEIF chain is drawn as one diamond per test, nested in the "no" arm + const build = (i: number): Block => { + const br = s.branches[i]; + const then = blockOf(ctx, br.body); + const rest: Block = i + 1 < s.branches.length ? build(i + 1) : blockOf(ctx, s.elseBody || []); + const noLine = i + 1 < s.branches.length ? s.branches[i + 1].line : firstLine(s.elseBody || []); + return branching(ctx, br.line, text(br.line).replace(/^(ELSE\s*IF|ELSEIF|ELIF|IF)\s+/i, '').replace(/\s+THEN$/i, '').replace(/:$/, ''), [ + { label: 'yes', block: then, countLine: firstLine(br.body) }, + { label: 'no', block: rest, countLine: noLine }, + ], null); + }; + return build(0); + } + case 'Case': { + const arms = s.arms.map((a: any) => ({ label: truncate(a.labels.map((l: any) => sourceOf(l)).join(', '), 14), block: blockOf(ctx, a.body), countLine: firstLine(a.body) })); + if (s.otherwise) arms.push({ label: 'otherwise', block: blockOf(ctx, s.otherwise), countLine: firstLine(s.otherwise) }); + return branching(ctx, s.line, text(s.line), arms, null); + } + case 'For': case 'ForEach': case 'While': { + const body = blockOf(ctx, s.body); + return loop(ctx, s.line, text(s.line), body, 'pre', s.body.length ? [s.line + 1, Math.max(lastLine(s.body), s.line + 1)] : null); + } + case 'Repeat': { + const body = blockOf(ctx, s.body); + const untilLine = s.endLine ?? lastLine(s.body) + 1; + return loop(ctx, untilLine, text(untilLine) || `UNTIL ${s.cond ? sourceOf(s.cond) : '…'}`, body, 'post', s.body.length ? [s.line + 1, untilLine - 1] : null); + } + default: return box(ctx, s.line, text(s.line) || s.kind); + } +} + +function firstLine(body: any[]): number | null { for (const s of body) if (s.kind !== 'Declare' && s.kind !== 'BlankStmt') return s.line; return body[0]?.line ?? null; } +function lastLine(body: any[]): number { + let m = 0; + const w = (s: any) => { + if (!s) return; + if (s.line > m) m = s.line; + if (s.endLine > m) m = s.endLine; + if (Array.isArray(s.body)) s.body.forEach(w); + if (Array.isArray(s.branches)) for (const b of s.branches) b.body?.forEach(w); + if (Array.isArray(s.elseBody)) s.elseBody.forEach(w); + if (Array.isArray(s.arms)) for (const a of s.arms) a.body?.forEach(w); + if (Array.isArray(s.otherwise)) s.otherwise.forEach(w); + }; + body.forEach(w); + return m; +} +function blockOf(ctx: FlowCtx, body: any[]): Block { return sequence(body.map((s) => flowOf(ctx, s)).filter((b): b is Block => !!b)); } + +export function flowView(session: Session, root: HTMLElement, hooks?: PanelHooks): () => void { + let follow = true; // shade by the run so far, and mark where the stepper is + let scroll: HTMLElement | null = null; + const render = () => { + const keep = scroll ? { x: scroll.scrollLeft, y: scroll.scrollTop } : null; + clear(root); + const r = routineOf(session); + if (!r) { emptyNote(root, session, 'flowchart'); return; } + const trace = session.trace(); + const t = follow ? Math.min(session.state.t ?? (trace?.count ?? 0), trace?.count ?? 0) : (trace?.count ?? 0); + const hits = pseudoHits(trace, t); + const lines = sourceLines(session); + const steps = trace && trace.lang !== 'asm' ? (trace.steps as any[]) : []; + const stepLines = steps.slice(0, t).map((s) => stepLine(s) ?? -1); + const pane = session.state.lang === 'mojo' ? 'mojo' : 'pseudo'; + const ctx: FlowCtx = { + current: follow && trace && t < trace.count ? stepLine(steps[t]) : null, last: follow && trace && t > 0 ? stepLine(steps[t - 1]) : null, + lines, stepLines, hits, maxHits: Math.max(1, ...pseudoHits(trace).values()), hasTrace: !!trace, onLine: hooks ? (ln) => hooks.reveal(pane, ln) : null, loopLines: new Set(), + }; + const start = box(ctx, r.line, r.kind === 'main' ? 'start' : lineText(lines, r.line).replace(/\s+RETURNS\s+.*$/, ''), 'pill'); + start.entryLine = r.line; + const body = blockOf(ctx, r.body); + const end: Block = { ...box(ctx, -1, r.kind === 'Function' ? 'end' : 'end', 'pill'), entryLine: null }; + const parts = [start, body]; + if (body.exits) parts.push(end); + const all = sequence(parts); + const pad = 16; + const el_ = svg('svg', { class: 'flow-svg', width: all.w + pad * 2, height: all.h + pad * 2, viewBox: `0 0 ${all.w + pad * 2} ${all.h + pad * 2}`, role: 'img', 'aria-label': `Flowchart of ${r.name}` }); + const defs = svg('defs', {}, svg('marker', { id: 'flow-arrow', viewBox: '0 0 10 10', refX: 9, refY: 5, markerWidth: 7, markerHeight: 7, orient: 'auto-start-reverse' }, svg('path', { d: 'M0 0 L10 5 L0 10 Z', class: 'flow-arrowhead' }))); + el_.appendChild(defs); + const g = svg('g', {}); + all.draw(g, pad, pad); + el_.appendChild(g); + const where = trace ? (follow && t < trace.count ? `the path so far: shaded by how often each line has run up to step ${t} of ${trace.count}; the box with the marker runs next` : `shaded by how often each line ran for ${session.state.lang === 'mojo' ? 'this run' : session.callText() || 'this run'}; ×n on an arrow is how many times it was taken`) : 'Run the program and the boxes shade by how often each line ran.'; + const head = el('div', { class: 'viz-head' }, + titleOf(session, r, render), + el('span', { class: 'small muted' }, where), + el('span', { class: 'spacer' }), + el('label', { class: 'tool-label tool-check small', title: 'Shade the chart by the run up to the step you are on, and mark the box that runs next' }, el('input', { type: 'checkbox', checked: follow, onChange: (e: Event) => { follow = (e.target as HTMLInputElement).checked; render(); } }), ' follow the stepper'), + button('Download SVG', () => downloadSvg(el_, `${r.name.toLowerCase()}-flow.svg`), { class: 'btn btn-small btn-quiet' })); + scroll = el('div', { class: 'viz-scroll' }, el_); + add(root, head, scroll); + if (keep) { scroll.scrollLeft = keep.x; scroll.scrollTop = keep.y; } + else if (follow) revealIn(scroll, el_.querySelector('.flow-current')); + }; + render(); + const off = session.onChange(render); + const offStep = session.onStep(() => { if (follow) render(); }); + return () => { off(); offStep(); }; +} + +function downloadSvg(node: SVGSVGElement, name: string): void { + // inline the colors so the file stands alone + const clone = node.cloneNode(true) as SVGSVGElement; + const style = document.createElementNS(NS, 'style'); + style.textContent = `text{font:12px ui-monospace,Menlo,Consolas,monospace;fill:#16191f}.flow-shape{stroke:#5c6370;stroke-width:1.2}.flow-edge{fill:none;stroke:#5c6370;stroke-width:1.4}.flow-back{stroke-dasharray:4 3}.flow-arrowhead{fill:#5c6370}.flow-badge{fill:#eef0f4;stroke:#dde1e8}.flow-badge-text,.flow-edge-label{font-size:10.5px;fill:#5c6370}.flow-edge-label-bg{fill:#fff}.flow-never .flow-shape{stroke-dasharray:3 3}.flow-never text{fill:#8a919c}.df-node{stroke:#5c6370;stroke-width:1.2;fill:#fff}.df-node-in{fill:#eaf1ff}.df-node-out{fill:#e8f6ee}.df-edge{fill:none;stroke:#5c6370;stroke-width:1.4}.df-edge-ctrl{stroke-dasharray:4 3;stroke:#8a919c}.df-type{font-size:10px;fill:#8a919c}.df-label{font-size:10px;fill:#5c6370}.df-label-bg{fill:#fff}`; + clone.insertBefore(style, clone.firstChild); + for (const e of clone.querySelectorAll('[fill^="color-mix"]')) e.setAttribute('fill', '#dbe4ff'); + for (const e of clone.querySelectorAll('[fill^="var("]')) e.setAttribute('fill', '#ffffff'); + const blob = new Blob([new XMLSerializer().serializeToString(clone)], { type: 'image/svg+xml' }); + const url = URL.createObjectURL(blob); + const a = el('a', { href: url, download: name }); + document.body.appendChild(a); a.click(); a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 1000); +} + +/* ------------------------------------------------------------------ */ +/* Data flow */ +/* ------------------------------------------------------------------ */ + +interface DNode { id: string; label: string; type: string; kind: 'in' | 'var' | 'out' | 'loop'; rank: number; x: number; y: number; w: number; lines: Set } +interface DEdge { from: string; to: string; lines: Set; ctrl: boolean; texts: string[] } + +export function dataFlowOf(session: Session, r: Routine): { nodes: DNode[]; edges: DEdge[] } { + const lines = sourceLines(session); + const nodes = new Map(); + const edges = new Map(); + const typeOf = (p: any) => (p?.type ? typeNameOf(p.type) : ''); + const node = (id: string, kind: DNode['kind'], type = ''): DNode => { + let n = nodes.get(id); + if (!n) { n = { id, label: id, type, kind, rank: 0, x: 0, y: 0, w: 0, lines: new Set() }; nodes.set(id, n); } + else if (type && !n.type) n.type = type; + return n; + }; + const edge = (from: string, to: string, ln: number, ctrl: boolean) => { + if (from === to && ctrl) return; + const key = `${from}→${to}:${ctrl ? 'c' : 'd'}`; + let e = edges.get(key); + if (!e) { e = { from, to, lines: new Set(), ctrl, texts: [] }; edges.set(key, e); } + e.lines.add(ln); + const t = lineText(lines, ln); if (t && !e.texts.includes(t)) e.texts.push(t); + }; + for (const p of r.params) node(p.name, 'in', typeOf(p)); + const declared = new Map(); + for (const sym of r.symbols) if (sym?.name && sym.type) declared.set(sym.name, typeNameOf(sym.type)); + const ensure = (name: string): DNode => nodes.get(name) ?? node(name, 'var', declared.get(name) || ''); + const walk = (body: any[], ctrl: string[]) => { + for (const s of body) { + switch (s.kind) { + case 'Assign': { + const t = rootName(s.target); if (!t) break; + const tn = ensure(t); tn.lines.add(s.line); + const srcs = [...namesIn(s.value), ...(s.target.kind === 'Index' ? namesIn(s.target.indices) : [])]; + for (const n of srcs) { ensure(n); edge(n, t, s.line, false); } + for (const c of ctrl) if (!srcs.includes(c)) edge(c, t, s.line, true); + break; + } + case 'Input': { const t = rootName(s.target); if (t) { node('INPUT', 'in', 'keyboard'); ensure(t).lines.add(s.line); edge('INPUT', t, s.line, false); } break; } + case 'Output': { node('OUTPUT', 'out', 'screen'); for (const n of namesIn(s.values)) { ensure(n); edge(n, 'OUTPUT', s.line, false); } break; } + case 'Return': { if (s.value) { node('RETURN', 'out', r.returns ? typeNameOf(r.returns) : ''); for (const n of namesIn(s.value)) { ensure(n); edge(n, 'RETURN', s.line, false); } for (const c of ctrl) edge(c, 'RETURN', s.line, true); } break; } + case 'BuiltinCall': { + // APPEND(L, V), INSERT(L, I, V), ADD(S, V), SORT(L), …: the first argument is what changes + const t = s.args[0] ? rootName(s.args[0]) : null; + if (t) { ensure(t).lines.add(s.line); for (const n of namesIn(s.args.slice(1))) { ensure(n); edge(n, t, s.line, false); } if (!s.args.slice(1).length) edge(t, t, s.line, false); for (const c of ctrl) edge(c, t, s.line, true); } + break; + } + case 'MojoCall': { + // the arguments passed to mut parameters change; everything the call reads flows into them + const outs = (s.outs as any[]).map((o) => rootName(o)).filter((x): x is string => !!x); + const ins = namesIn(s.args); + for (const t of outs) { ensure(t).lines.add(s.line); for (const n of ins) if (n !== t) { ensure(n); edge(n, t, s.line, false); } for (const c of ctrl) edge(c, t, s.line, true); } + break; + } + case 'Call': { + const sub = session.parsedPseudo()?.program?.program?.subs?.get(String(s.name).toUpperCase()); + const outs: string[] = []; + (sub?.node?.params || sub?.params || []).forEach((p: any, i: number) => { if (p.mode === 'BYREF' && s.args[i]) { const t = rootName(s.args[i]); if (t) outs.push(t); } }); + const ins = namesIn(s.args); + for (const t of outs) { ensure(t).lines.add(s.line); for (const n of ins) if (n !== t) { ensure(n); edge(n, t, s.line, false); } } + break; + } + case 'For': { + const v = ensure(s.var); v.kind = v.kind === 'in' ? 'in' : 'loop'; v.type = v.type || 'INTEGER'; v.lines.add(s.line); + for (const n of namesIn([s.start, s.stop, s.step])) { ensure(n); edge(n, s.var, s.line, false); } + walk(s.body, ctrl); break; + } + case 'ForEach': { + const v = ensure(s.var); v.kind = 'loop'; v.lines.add(s.line); + for (const n of namesIn(s.iterable)) { ensure(n); edge(n, s.var, s.line, false); } + walk(s.body, ctrl); break; + } + case 'While': walk(s.body, [...ctrl, ...namesIn(s.cond)]); break; + case 'Repeat': walk(s.body, [...ctrl, ...namesIn(s.cond)]); break; + case 'If': for (const b of s.branches) walk(b.body, [...ctrl, ...namesIn(b.cond)]); if (s.elseBody) walk(s.elseBody, [...ctrl, ...s.branches.flatMap((b: any) => namesIn(b.cond))]); break; + case 'Case': { const c = [...ctrl, ...namesIn(s.subject)]; for (const a of s.arms) walk(a.body, c); if (s.otherwise) walk(s.otherwise, c); break; } + default: break; + } + } + }; + walk(r.body, []); + // ranks: longest path from the inputs over forward edges; a DFS decides which edges are forward + const ns = [...nodes.values()]; + const out = new Map(); + for (const e of edges.values()) { if (!out.has(e.from)) out.set(e.from, []); out.get(e.from)!.push(e); } + const state = new Map(); + const forward = new Set(); + const dfs = (id: string) => { + state.set(id, 'on'); + for (const e of out.get(id) || []) { + if (e.from === e.to) continue; + const st = state.get(e.to); + if (st === 'on') continue; // a back edge: a loop + forward.add(e); + if (!st) dfs(e.to); + } + state.set(id, 'done'); + }; + for (const n of ns) if (n.kind === 'in') dfs(n.id); + for (const n of ns) if (!state.has(n.id)) dfs(n.id); + const indeg = new Map(ns.map((n) => [n.id, 0])); + for (const e of forward) indeg.set(e.to, (indeg.get(e.to) || 0) + 1); + const queue = ns.filter((n) => !indeg.get(n.id)).map((n) => n.id); + const rank = new Map(ns.map((n) => [n.id, n.kind === 'in' ? 0 : 1])); + while (queue.length) { + const id = queue.shift()!; + for (const e of forward) if (e.from === id) { rank.set(e.to, Math.max(rank.get(e.to)!, rank.get(id)! + 1)); indeg.set(e.to, indeg.get(e.to)! - 1); if (!indeg.get(e.to)) queue.push(e.to); } + } + const maxRank = Math.max(1, ...[...rank.entries()].filter(([id]) => nodes.get(id)!.kind !== 'out').map(([, v]) => v)); + for (const n of ns) n.rank = n.kind === 'out' ? maxRank + 1 : n.kind === 'in' ? 0 : Math.max(1, rank.get(n.id)!); + return { nodes: ns, edges: [...edges.values()] }; +} + +function typeNameOf(t: any): string { + if (!t) return ''; + if (typeof t === 'string') return t; + if (t.k) { try { return typeName(t); } catch { return t.k; } } + if (t.tk === 'scalar' || t.tk === 'named') return t.name; + if (t.tk === 'list' || t.tk === 'set') return `${t.tk.toUpperCase()} OF ${typeNameOf(t.of)}`; + return ''; +} + +export function dataFlowView(session: Session, root: HTMLElement, hooks?: PanelHooks): () => void { + let live: SVGSVGElement | null = null; + /** Light up what the stepper is doing: the names the next step reads, the name the last step wrote, and the edge of the line that just ran. */ + const mark = (t: number) => { + const trace = session.trace(); + if (!live || !trace || trace.lang === 'asm') return; + const steps = trace.steps as any[]; + const next = t < trace.count ? steps[t] : null, last = t > 0 ? steps[t - 1] : null; + const reads = new Set((next?.reads || []).map((r: any) => r.name)); + const writes = new Set((last?.writes || []).map((w: any) => w.name)); + for (const g of live.querySelectorAll('.df-nodeg')) { const n = g.dataset.name || ''; g.classList.toggle('df-reads', reads.has(n)); g.classList.toggle('df-wrote', writes.has(n)); } + const ln = stepLine(last); + for (const e of live.querySelectorAll('.df-edge')) e.classList.toggle('df-edge-active', ln != null && (e.dataset.lines || '').split(' ').includes(String(ln))); + }; + const render = () => { + clear(root); + const r = routineOf(session); + if (!r) { emptyNote(root, session, 'data-flow graph'); return; } + const { nodes, edges } = dataFlowOf(session, r); + if (!nodes.length) { add(root, el('p', { class: 'muted' }, 'This routine moves no values between names yet.')); return; } + const COLW = 190, ROWH = 62, NH = 38; + const cols = new Map(); + for (const n of nodes) { if (!cols.has(n.rank)) cols.set(n.rank, []); cols.get(n.rank)!.push(n); } + const ranks = [...cols.keys()].sort((a, b) => a - b); + const tallest = Math.max(...[...cols.values()].map((c) => c.length)); + const H = tallest * ROWH + 40, W = ranks.length * COLW + 40; + ranks.forEach((rk, ci) => { + const col = cols.get(rk)!; + col.sort((a, b) => (a.kind === 'in' && b.kind !== 'in' ? -1 : 0) || Math.min(...a.lines, 1e9) - Math.min(...b.lines, 1e9)); + const top = (H - col.length * ROWH) / 2; + col.forEach((n, i) => { n.w = Math.max(72, Math.max(n.label.length, Math.min(n.type.length, 18)) * 7.3 + 24); n.x = 20 + ci * COLW + (COLW - n.w) / 2; n.y = top + i * ROWH + (ROWH - NH) / 2; }); + }); + const el_ = svg('svg', { class: 'flow-svg df-svg', width: W, height: H, viewBox: `0 0 ${W} ${H}`, role: 'img', 'aria-label': `Data flow of ${r.name}` }); + el_.appendChild(svg('defs', {}, svg('marker', { id: 'df-arrow', viewBox: '0 0 10 10', refX: 9, refY: 5, markerWidth: 7, markerHeight: 7, orient: 'auto-start-reverse' }, svg('path', { d: 'M0 0 L10 5 L0 10 Z', class: 'flow-arrowhead' })))); + const byId = new Map(nodes.map((n) => [n.id, n])); + const gE = svg('g', {}), gN = svg('g', {}); + const bez = (p0: number[], p1: number[], p2: number[], p3: number[], t: number): [number, number] => { const u = 1 - t; return [u * u * u * p0[0] + 3 * u * u * t * p1[0] + 3 * u * t * t * p2[0] + t * t * t * p3[0], u * u * u * p0[1] + 3 * u * u * t * p1[1] + 3 * u * t * t * p2[1] + t * t * t * p3[1]]; }; + const intoCount = new Map(); + for (const e of edges) { + const a = byId.get(e.from)!, b = byId.get(e.to)!; + const lbl = [...e.lines].sort((x, y) => x - y).map((l) => `L${l}`).join(' '); + // labels on the edges into one node are spread along their curves so they do not pile up + const k = intoCount.get(b.id) || 0; intoCount.set(b.id, k + 1); + const tt = [0.5, 0.3, 0.7, 0.4, 0.6, 0.2, 0.8][k % 7]; + let d: string; let lx: number; let ly: number; + if (a === b) { + const x = a.x + a.w / 2, y = a.y; + d = `M${x - 14} ${y} C ${x - 24} ${y - 34}, ${x + 24} ${y - 34}, ${x + 14} ${y}`; + lx = x; ly = y - 30; + } else if (b.rank > a.rank) { + const p0 = [a.x + a.w, a.y + NH / 2], p3 = [b.x, b.y + NH / 2]; + const m = (p0[0] + p3[0]) / 2; + const p1 = [m, p0[1]], p2 = [m, p3[1]]; + d = `M${p0[0]} ${p0[1]} C ${p1[0]} ${p1[1]}, ${p2[0]} ${p2[1]}, ${p3[0]} ${p3[1]}`; + [lx, ly] = bez(p0, p1, p2, p3, tt); + ly += (k % 2 ? 7 : -7); + } else { + // a back edge: leave from the bottom, come in at the bottom + const p0 = [a.x + a.w / 2, a.y + NH], p3 = [b.x + b.w / 2, b.y + NH]; + const dip = Math.max(p0[1], p3[1]) + 26 + Math.abs(a.rank - b.rank) * 6; + const p1 = [p0[0], dip], p2 = [p3[0], dip]; + d = `M${p0[0]} ${p0[1]} C ${p1[0]} ${p1[1]}, ${p2[0]} ${p2[1]}, ${p3[0]} ${p3[1]}`; + [lx, ly] = bez(p0, p1, p2, p3, 0.5); + } + const path = svg('path', { d, class: 'df-edge' + (e.ctrl ? ' df-edge-ctrl' : ''), 'marker-end': 'url(#df-arrow)', 'data-lines': [...e.lines].join(' ') }); + path.appendChild(svg('title', {}, (e.ctrl ? 'decides: ' : '') + e.texts.join('\n'))); + gE.appendChild(path); + const w = lbl.length * 6.2 + 8; + gE.appendChild(svg('rect', { x: lx - w / 2, y: ly - 8, width: w, height: 15, rx: 3, class: 'df-label-bg' })); + gE.appendChild(svg('text', { x: lx, y: ly, class: 'df-label', 'text-anchor': 'middle', 'dominant-baseline': 'central' }, lbl)); + } + for (const n of nodes) { + const g = svg('g', { class: `df-nodeg df-kind-${n.kind}` + (hooks && n.lines.size ? ' flow-clickable' : ''), 'data-name': n.label }); + g.appendChild(svg('rect', { x: n.x, y: n.y, width: n.w, height: NH, rx: n.kind === 'in' || n.kind === 'out' ? NH / 2 : 6, class: `df-node df-node-${n.kind}` })); + g.appendChild(svg('text', { x: n.x + n.w / 2, y: n.y + (n.type ? 13 : NH / 2), class: 'flow-text', 'text-anchor': 'middle', 'dominant-baseline': 'central' }, n.label)); + if (n.type) g.appendChild(svg('text', { x: n.x + n.w / 2, y: n.y + 27, class: 'df-type', 'text-anchor': 'middle', 'dominant-baseline': 'central' }, truncate(n.type, 18))); + g.appendChild(svg('title', {}, n.kind === 'in' ? `${n.label}: an input` : n.kind === 'out' ? `${n.label}: what leaves the routine` : `${n.label}: set on line${n.lines.size === 1 ? '' : 's'} ${[...n.lines].sort((a, b) => a - b).join(', ')}`)); + if (hooks && n.lines.size) g.addEventListener('click', () => hooks.reveal(session.state.lang === 'mojo' ? 'mojo' : 'pseudo', Math.min(...n.lines))); + gN.appendChild(g); + } + el_.appendChild(gE); el_.appendChild(gN); + live = el_; + const head = el('div', { class: 'viz-head' }, + titleOf(session, r, render), + el('span', { class: 'small muted' }, 'inputs on the left, what leaves on the right; an arrow is an assignment that reads the one and writes the other, dashed when a condition only decides whether it happens.', el('span', { class: 'viz-step-note' }, ' As you step, the names the next line reads and the name the last line wrote light up.')), + el('span', { class: 'spacer' }), + button('Download SVG', () => downloadSvg(el_, `${r.name.toLowerCase()}-dataflow.svg`), { class: 'btn btn-small btn-quiet' })); + add(root, head, el('div', { class: 'viz-scroll' }, el_)); + mark(Math.min(session.state.t ?? 0, session.trace()?.count ?? 0)); + }; + render(); + const off = session.onChange(render); + const offStep = session.onStep(mark); + return () => { off(); offStep(); }; +} + +/* ------------------------------------------------------------------ */ +/* Trace table */ +/* ------------------------------------------------------------------ */ + +const MAX_COLS = 120; + +export function traceTableView(session: Session, root: HTMLElement, opts: { goto?: (t: number) => void } = {}): () => void { + let showAll = false; + /** The column of the step that just ran gets the marker; the table scrolls to keep it in view. */ + const mark = (t: number) => { + for (const c of root.querySelectorAll('.vals-now')) c.classList.remove('vals-now'); + if (t <= 0) return; + // the column of the last step that changed something at or before t + let best = 0; + for (const th of root.querySelectorAll('th.vals-step')) { const n = Number(th.dataset.step); if (n <= t && n > best) best = n; } + if (!best) return; + const cells = root.querySelectorAll(`[data-step="${best}"]`); + cells.forEach((c) => c.classList.add('vals-now')); + revealIn(root.querySelector('.vals-scroll'), cells[0] ?? null); + }; + const render = () => { + clear(root); + const trace = session.trace(); + if (!trace) { emptyNote(root, session, 'table of values'); if (session.runError) add(root, el('p', { class: 'small err' }, session.runError)); return; } + if (trace.lang === 'asm') { add(root, el('p', { class: 'muted' }, 'The table of values is for pseudo, lingo, matho and Mojo runs; the machine view shows the registers.')); return; } + const steps = trace.steps as any[]; + const states = trace.states as any[]; + // the columns: steps that wrote something (or printed) + const cols: number[] = []; + for (let i = 0; i < trace.count; i++) { + const s = steps[i]; + const printed = (states[i + 1]?.outputLength ?? 0) > (states[i]?.outputLength ?? 0); + if ((s.writes && s.writes.length) || printed || s.kind === 'return' || s.kind === 'error') cols.push(i); + } + const shown = cols.slice(0, MAX_COLS); + // the rows: every variable, by frame, in order of first appearance across the shown steps + type Row = { key: string; frame: string; name: string; label: string; type: any }; + const rows: Row[] = []; + const seen = new Set(); + const frameNames = new Set(); + for (const st of states) for (const f of st?.frames || []) frameNames.add(f.name || 'main'); + const valueAt = (i: number, row: Row): { text: string; unset: boolean } | null => { + const st = states[i]; + if (!st) return null; + const frames = (st.frames || []).filter((f: any) => (f.name || 'main') === row.frame); + const f = frames[frames.length - 1]; + if (!f || !(row.name in f.vars)) return null; + const v = f.vars[row.name]; + const text = typeof v.text === 'string' ? v.text : formatValue(v.value, v.type, { max: 48, unset: '' }); + return { text, unset: text === '' }; + }; + for (const i of shown) { + const st = states[i + 1]; + for (const f of st?.frames || []) { + for (const [name, v] of Object.entries(f.vars)) { + const key = `${f.name || 'main'}.${name}`; + if (seen.has(key)) continue; + seen.add(key); rows.push({ key, frame: f.name || 'main', name, label: v.name || name, type: v.type }); + } + } + } + const rowFrames = new Set(rows.map((r) => r.frame)); + const prefix = rowFrames.size > 1; + const lines = sourceLines(session); + const srcFor = (s: any) => { const ln = s.pseudoLine ?? s.line; return ln != null ? lineText(lines, ln) : ''; }; + const table = el('table', { class: 'tbl vals-tbl' }); + const thead = el('thead'); + const hr1 = el('tr', {}, el('th', { class: 'vals-corner' }, 'step')); + const hr2 = el('tr', {}, el('th', { class: 'vals-corner' }, 'line')); + for (const i of shown) { + const s = steps[i]; + const th = el('th', { class: 'vals-step' + (opts.goto ? ' linkish' : ''), 'data-step': String(i + 1), title: `step ${i + 1}: ${srcFor(s)}`, onClick: opts.goto ? () => opts.goto!(i + 1) : undefined }, String(i + 1)); + add(hr1, th); + add(hr2, el('th', { class: 'vals-line', 'data-step': String(i + 1), title: srcFor(s) }, s.pseudoLine ?? s.line ?? '')); + } + add(thead, hr1, hr2); + const tbody = el('tbody'); + for (const row of rows) { + const tr = el('tr', {}, el('th', { class: 'vals-var', title: row.type ? typeNameOf(row.type) : '' }, prefix ? el('span', { class: 'muted small' }, `${row.frame}.`) : null, row.label)); + let prev: string | null = null; + for (const i of shown) { + const after = valueAt(i + 1, row); + const wrote = (steps[i].writes || []).some((w: any) => w.name === row.name); + const changed = after && after.text !== prev; + let cell: HTMLElement; + if (!after) cell = el('td', { class: 'vals-cell vals-absent' }); + else if (changed || wrote) cell = el('td', { class: 'vals-cell vals-changed' + (after.unset ? ' vals-unset' : '') }, after.unset ? '—' : after.text); + else cell = el('td', { class: 'vals-cell vals-same' + (showAll ? '' : ' vals-blank') }, showAll ? after.text : ''); + cell.dataset.step = String(i + 1); + add(tr, cell); + if (after) prev = after.text; + } + add(tbody, tr); + } + // the output row + if (trace.output.length) { + const tr = el('tr', { class: 'vals-output-row' }, el('th', { class: 'vals-var' }, 'output')); + shown.forEach((i, k) => { + const before = states[i]?.outputLength ?? 0; + let after = states[i + 1]?.outputLength ?? before; + if (k === shown.length - 1 && shown.length === cols.length) after = trace.output.length; // what the last step printed or returned + add(tr, el('td', { class: 'vals-cell' + (after > before ? ' vals-changed vals-out' : '') }, after > before ? trace.output.slice(before, after).join(' ⏎ ') : '')); + }); + add(tbody, tr); + } + add(table, thead, tbody); + const head = el('div', { class: 'viz-head' }, + el('span', { class: 'viz-title' }, 'table of values'), + el('span', { class: 'small muted' }, `${shown.length} of ${trace.count} steps changed something${cols.length > MAX_COLS ? `; the first ${MAX_COLS} are shown` : ''}. A filled cell is a new value; a blank cell means "unchanged".`), + el('span', { class: 'spacer' }), + el('label', { class: 'tool-label tool-check small' }, el('input', { type: 'checkbox', checked: showAll, onChange: (e: Event) => { showAll = (e.target as HTMLInputElement).checked; render(); } }), ' show unchanged values too'), + button('Copy as text', async (e) => { await copyTable(table); (e.target as HTMLButtonElement).textContent = 'Copied'; setTimeout(() => ((e.target as HTMLButtonElement).textContent = 'Copy as text'), 1200); }, { class: 'btn btn-small btn-quiet' })); + add(root, head, el('div', { class: 'viz-scroll vals-scroll' }, table)); + if (trace.error) add(root, el('p', { class: 'small err' }, `The run stopped: ${trace.error.message}`)); + mark(Math.min(session.state.t ?? 0, trace.count)); + }; + render(); + const off = session.onChange(render); + const offStep = session.onStep(mark); + return () => { off(); offStep(); }; +} + +async function copyTable(table: HTMLTableElement): Promise { + const rows = [...table.querySelectorAll('tr')].map((tr) => [...tr.children].map((c) => (c.textContent || '').trim())); + try { await navigator.clipboard.writeText(toTsv(rows)); } catch { /* ignore */ } +} diff --git a/src/vendor/CODEMIRROR-LICENSE b/src/vendor/CODEMIRROR-LICENSE new file mode 100644 index 0000000..9a91f48 --- /dev/null +++ b/src/vendor/CODEMIRROR-LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (C) 2018-2021 by Marijn Haverbeke 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/src/vendor/cm-types/commands/src/commands.d.ts b/src/vendor/cm-types/commands/src/commands.d.ts new file mode 100644 index 0000000..80c593c --- /dev/null +++ b/src/vendor/cm-types/commands/src/commands.d.ts @@ -0,0 +1,98 @@ +import { StateCommand } from "../../state/src/index.js"; +import { Command, KeyBinding } from "../../view/src/index.js"; +export { CommentTokens, toggleComment, toggleLineComment, lineComment, lineUncomment, toggleBlockComment, blockComment, blockUncomment, toggleBlockCommentByLine } from "./comment"; +export { history, historyKeymap, historyField, undo, redo, undoSelection, redoSelection, undoDepth, redoDepth, isolateHistory, invertedEffects } from "./history"; +export declare const cursorCharLeft: Command; +export declare const cursorCharRight: Command; +export declare const cursorCharForward: Command; +export declare const cursorCharBackward: Command; +export declare const cursorCharForwardLogical: StateCommand; +export declare const cursorCharBackwardLogical: StateCommand; +export declare const cursorGroupLeft: Command; +export declare const cursorGroupRight: Command; +export declare const cursorGroupForward: Command; +export declare const cursorGroupBackward: Command; +export declare const cursorGroupForwardWin: Command; +export declare const cursorSubwordForward: Command; +export declare const cursorSubwordBackward: Command; +export declare const cursorSyntaxLeft: Command; +export declare const cursorSyntaxRight: Command; +export declare const cursorLineUp: Command; +export declare const cursorLineDown: Command; +export declare const cursorPageUp: Command; +export declare const cursorPageDown: Command; +export declare const cursorLineBoundaryForward: Command; +export declare const cursorLineBoundaryBackward: Command; +export declare const cursorLineBoundaryLeft: Command; +export declare const cursorLineBoundaryRight: Command; +export declare const cursorLineStart: Command; +export declare const cursorLineEnd: Command; +export declare const cursorMatchingBracket: StateCommand; +export declare const selectMatchingBracket: StateCommand; +export declare const selectCharLeft: Command; +export declare const selectCharRight: Command; +export declare const selectCharForward: Command; +export declare const selectCharBackward: Command; +export declare const selectCharForwardLogical: StateCommand; +export declare const selectCharBackwardLogical: StateCommand; +export declare const selectGroupLeft: Command; +export declare const selectGroupRight: Command; +export declare const selectGroupForward: Command; +export declare const selectGroupBackward: Command; +export declare const selectGroupForwardWin: Command; +export declare const selectSubwordForward: Command; +export declare const selectSubwordBackward: Command; +export declare const selectSyntaxLeft: Command; +export declare const selectSyntaxRight: Command; +export declare const selectLineUp: Command; +export declare const selectLineDown: Command; +export declare const selectPageUp: Command; +export declare const selectPageDown: Command; +export declare const selectLineBoundaryForward: Command; +export declare const selectLineBoundaryBackward: Command; +export declare const selectLineBoundaryLeft: Command; +export declare const selectLineBoundaryRight: Command; +export declare const selectLineStart: Command; +export declare const selectLineEnd: Command; +export declare const cursorDocStart: StateCommand; +export declare const cursorDocEnd: StateCommand; +export declare const selectDocStart: StateCommand; +export declare const selectDocEnd: StateCommand; +export declare const selectAll: StateCommand; +export declare const selectLine: StateCommand; +export declare const selectParentSyntax: StateCommand; +export declare const addCursorAbove: Command; +export declare const addCursorBelow: Command; +export declare const simplifySelection: StateCommand; +export declare const deleteCharBackward: Command; +export declare const deleteCharBackwardStrict: Command; +export declare const deleteCharForward: Command; +export declare const deleteGroupBackward: StateCommand; +export declare const deleteGroupForward: StateCommand; +export declare const deleteGroupForwardWin: Command; +export declare const deleteToLineEnd: Command; +export declare const deleteToLineStart: Command; +export declare const deleteLineBoundaryBackward: Command; +export declare const deleteLineBoundaryForward: Command; +export declare const deleteTrailingWhitespace: StateCommand; +export declare const splitLine: StateCommand; +export declare const transposeChars: StateCommand; +export declare const moveLineUp: StateCommand; +export declare const moveLineDown: StateCommand; +export declare const copyLineUp: StateCommand; +export declare const copyLineDown: StateCommand; +export declare const deleteLine: Command; +export declare const insertNewline: StateCommand; +export declare const insertNewlineKeepIndent: StateCommand; +export declare const insertNewlineAndIndent: StateCommand; +export declare const insertBlankLine: StateCommand; +export declare const indentSelection: StateCommand; +export declare const indentMore: StateCommand; +export declare const indentLess: StateCommand; +export declare const toggleTabFocusMode: Command; +export declare const temporarilySetTabFocusMode: Command; +export declare const insertTab: StateCommand; +export declare const emacsStyleKeymap: readonly KeyBinding[]; +export declare const standardKeymap: readonly KeyBinding[]; +export declare const defaultKeymap: readonly KeyBinding[]; +export declare const indentWithTab: KeyBinding; diff --git a/src/vendor/cm-types/commands/src/comment.d.ts b/src/vendor/cm-types/commands/src/comment.d.ts new file mode 100644 index 0000000..3b450c9 --- /dev/null +++ b/src/vendor/cm-types/commands/src/comment.d.ts @@ -0,0 +1,16 @@ +import { StateCommand } from "../../state/src/index.js"; +export interface CommentTokens { + block?: { + open: string; + close: string; + }; + line?: string; +} +export declare const toggleComment: StateCommand; +export declare const toggleLineComment: StateCommand; +export declare const lineComment: StateCommand; +export declare const lineUncomment: StateCommand; +export declare const toggleBlockComment: StateCommand; +export declare const blockComment: StateCommand; +export declare const blockUncomment: StateCommand; +export declare const toggleBlockCommentByLine: StateCommand; diff --git a/src/vendor/cm-types/commands/src/history.d.ts b/src/vendor/cm-types/commands/src/history.d.ts new file mode 100644 index 0000000..ba5cdef --- /dev/null +++ b/src/vendor/cm-types/commands/src/history.d.ts @@ -0,0 +1,19 @@ +import { EditorState, Transaction, StateField, StateCommand, StateEffect, Facet, Extension } from "../../state/src/index.js"; +import { KeyBinding } from "../../view/src/index.js"; +export declare const isolateHistory: import("entry").AnnotationType<"before" | "after" | "full">; +export declare const invertedEffects: Facet<(tr: Transaction) => readonly StateEffect[], readonly ((tr: Transaction) => readonly StateEffect[])[]>; +interface HistoryConfig { + minDepth?: number; + newGroupDelay?: number; + joinToEvent?: (tr: Transaction, isAdjacent: boolean) => boolean; +} +export declare function history(config?: HistoryConfig): Extension; +export declare const historyField: StateField; +export declare const undo: StateCommand; +export declare const redo: StateCommand; +export declare const undoSelection: StateCommand; +export declare const redoSelection: StateCommand; +export declare const undoDepth: (state: EditorState) => number; +export declare const redoDepth: (state: EditorState) => number; +export declare const historyKeymap: readonly KeyBinding[]; +export {}; diff --git a/src/vendor/cm-types/commands/src/index.d.ts b/src/vendor/cm-types/commands/src/index.d.ts new file mode 100644 index 0000000..9a62daa --- /dev/null +++ b/src/vendor/cm-types/commands/src/index.d.ts @@ -0,0 +1,3 @@ +export * from "./commands"; +export * from "./history"; +export * from "./comment"; diff --git a/src/vendor/cm-types/common/src/index.d.ts b/src/vendor/cm-types/common/src/index.d.ts new file mode 100644 index 0000000..b687834 --- /dev/null +++ b/src/vendor/cm-types/common/src/index.d.ts @@ -0,0 +1,3 @@ +export { DefaultBufferLength, NodeProp, MountedTree, NodePropSource, NodeType, NodeSet, Tree, TreeBuffer, SyntaxNode, SyntaxNodeRef, TreeCursor, BufferCursor, NodeWeakMap, IterMode, NodeIterator } from "./tree"; +export { ChangedRange, TreeFragment, PartialParse, Parser, Input, ParseWrapper } from "./parse"; +export { NestedParse, parseMixed } from "./mix"; diff --git a/src/vendor/cm-types/common/src/mix.d.ts b/src/vendor/cm-types/common/src/mix.d.ts new file mode 100644 index 0000000..42c7ca5 --- /dev/null +++ b/src/vendor/cm-types/common/src/mix.d.ts @@ -0,0 +1,14 @@ +import { SyntaxNodeRef } from "./tree"; +import { Input, Parser, ParseWrapper } from "./parse"; +export interface NestedParse { + parser: Parser; + overlay?: readonly { + from: number; + to: number; + }[] | ((node: SyntaxNodeRef) => { + from: number; + to: number; + } | boolean); + bracketed?: boolean; +} +export declare function parseMixed(nest: (node: SyntaxNodeRef, input: Input) => NestedParse | null): ParseWrapper; diff --git a/src/vendor/cm-types/common/src/parse.d.ts b/src/vendor/cm-types/common/src/parse.d.ts new file mode 100644 index 0000000..4386426 --- /dev/null +++ b/src/vendor/cm-types/common/src/parse.d.ts @@ -0,0 +1,48 @@ +import { Tree } from "./tree"; +export interface ChangedRange { + fromA: number; + toA: number; + fromB: number; + toB: number; +} +export declare class TreeFragment { + readonly from: number; + readonly to: number; + readonly tree: Tree; + readonly offset: number; + constructor(from: number, to: number, tree: Tree, offset: number, openStart?: boolean, openEnd?: boolean); + get openStart(): boolean; + get openEnd(): boolean; + static addTree(tree: Tree, fragments?: readonly TreeFragment[], partial?: boolean): readonly TreeFragment[]; + static applyChanges(fragments: readonly TreeFragment[], changes: readonly ChangedRange[], minGap?: number): readonly TreeFragment[]; +} +export interface PartialParse { + advance(): Tree | null; + readonly parsedPos: number; + stopAt(pos: number): void; + readonly stoppedAt: number | null; +} +export declare abstract class Parser { + abstract createParse(input: Input, fragments: readonly TreeFragment[], ranges: readonly { + from: number; + to: number; + }[]): PartialParse; + startParse(input: Input | string, fragments?: readonly TreeFragment[], ranges?: readonly { + from: number; + to: number; + }[]): PartialParse; + parse(input: Input | string, fragments?: readonly TreeFragment[], ranges?: readonly { + from: number; + to: number; + }[]): Tree; +} +export interface Input { + readonly length: number; + chunk(from: number): string; + readonly lineChunks: boolean; + read(from: number, to: number): string; +} +export type ParseWrapper = (inner: PartialParse, input: Input, fragments: readonly TreeFragment[], ranges: readonly { + from: number; + to: number; +}[]) => PartialParse; diff --git a/src/vendor/cm-types/common/src/tree.d.ts b/src/vendor/cm-types/common/src/tree.d.ts new file mode 100644 index 0000000..c19e6ad --- /dev/null +++ b/src/vendor/cm-types/common/src/tree.d.ts @@ -0,0 +1,282 @@ +import { Parser } from "./parse"; +export declare const DefaultBufferLength = 1024; +export declare class Range { + readonly from: number; + readonly to: number; + constructor(from: number, to: number); +} +export declare class NodeProp { + perNode: boolean; + deserialize: (str: string) => T; + constructor(config?: { + deserialize?: (str: string) => T; + combine?: (a: T, b: T) => T; + perNode?: boolean; + }); + add(match: { + [selector: string]: T; + } | ((type: NodeType) => T | undefined)): NodePropSource; + static closedBy: NodeProp; + static openedBy: NodeProp; + static group: NodeProp; + static isolate: NodeProp<"rtl" | "auto" | "ltr">; + static contextHash: NodeProp; + static lookAhead: NodeProp; + static mounted: NodeProp; +} +export declare class MountedTree { + readonly tree: Tree; + readonly overlay: readonly { + from: number; + to: number; + }[] | null; + readonly parser: Parser; + readonly bracketed: boolean; + constructor(tree: Tree, overlay: readonly { + from: number; + to: number; + }[] | null, parser: Parser, bracketed?: boolean); +} +export type NodePropSource = (type: NodeType) => null | [NodeProp, any]; +export declare class NodeType { + readonly name: string; + readonly id: number; + static define(spec: { + id: number; + name?: string; + props?: readonly ([NodeProp, any] | NodePropSource)[]; + top?: boolean; + error?: boolean; + skipped?: boolean; + }): NodeType; + prop(prop: NodeProp): T | undefined; + get isTop(): boolean; + get isSkipped(): boolean; + get isError(): boolean; + get isAnonymous(): boolean; + is(name: string | number): boolean; + static none: NodeType; + static match(map: { + [selector: string]: T; + }): (node: NodeType) => T | undefined; +} +export declare class NodeSet { + readonly types: readonly NodeType[]; + constructor(types: readonly NodeType[]); + extend(...props: NodePropSource[]): NodeSet; +} +export declare enum IterMode { + ExcludeBuffers = 1, + IncludeAnonymous = 2, + IgnoreMounts = 4, + IgnoreOverlays = 8, + EnterBracketed = 16 +} +export declare class Tree { + readonly type: NodeType; + readonly children: readonly (Tree | TreeBuffer)[]; + readonly positions: readonly number[]; + readonly length: number; + constructor(type: NodeType, children: readonly (Tree | TreeBuffer)[], positions: readonly number[], length: number, props?: readonly [NodeProp | number, any][]); + static empty: Tree; + cursor(mode?: IterMode): TreeCursor; + cursorAt(pos: number, side?: -1 | 0 | 1, mode?: IterMode): TreeCursor; + get topNode(): SyntaxNode; + resolve(pos: number, side?: -1 | 0 | 1): SyntaxNode; + resolveInner(pos: number, side?: -1 | 0 | 1): SyntaxNode; + resolveStack(pos: number, side?: -1 | 0 | 1): NodeIterator; + iterate(spec: { + enter(node: SyntaxNodeRef): boolean | void; + leave?(node: SyntaxNodeRef): void; + from?: number; + to?: number; + mode?: IterMode; + }): void; + prop(prop: NodeProp): T | undefined; + get propValues(): readonly [NodeProp | number, any][]; + balance(config?: { + makeTree?: (children: readonly (Tree | TreeBuffer)[], positions: readonly number[], length: number) => Tree; + }): Tree; + static build(data: BuildData): Tree; +} +export type NodeIterator = { + node: SyntaxNode; + next: NodeIterator | null; +}; +type BuildData = { + buffer: BufferCursor | readonly number[]; + nodeSet: NodeSet; + topID: number; + start?: number; + bufferStart?: number; + length?: number; + maxBufferLength?: number; + reused?: readonly Tree[]; + minRepeatType?: number; +}; +export interface BufferCursor { + pos: number; + id: number; + start: number; + end: number; + size: number; + next(): void; + fork(): BufferCursor; +} +export declare class TreeBuffer { + readonly buffer: Uint16Array; + readonly length: number; + readonly set: NodeSet; + constructor(buffer: Uint16Array, length: number, set: NodeSet); +} +export interface SyntaxNodeRef { + readonly from: number; + readonly to: number; + readonly type: NodeType; + readonly name: string; + readonly tree: Tree | null; + readonly node: SyntaxNode; + matchContext(context: readonly string[]): boolean; +} +export interface SyntaxNode extends SyntaxNodeRef { + parent: SyntaxNode | null; + firstChild: SyntaxNode | null; + lastChild: SyntaxNode | null; + childAfter(pos: number): SyntaxNode | null; + childBefore(pos: number): SyntaxNode | null; + enter(pos: number, side: -1 | 0 | 1, mode?: IterMode): SyntaxNode | null; + nextSibling: SyntaxNode | null; + prevSibling: SyntaxNode | null; + prop(prop: NodeProp): T | undefined; + cursor(mode?: IterMode): TreeCursor; + resolve(pos: number, side?: -1 | 0 | 1): SyntaxNode; + resolveInner(pos: number, side?: -1 | 0 | 1): SyntaxNode; + enterUnfinishedNodesBefore(pos: number): SyntaxNode; + toTree(): Tree; + getChild(type: string | number, before?: string | number | null, after?: string | number | null): SyntaxNode | null; + getChildren(type: string | number, before?: string | number | null, after?: string | number | null): SyntaxNode[]; +} +declare const enum Side { + Before = -2, + AtOrBefore = -1, + Around = 0, + AtOrAfter = 1, + After = 2, + DontCare = 4 +} +declare abstract class BaseNode implements SyntaxNode { + abstract from: number; + abstract to: number; + abstract type: NodeType; + abstract name: string; + abstract tree: Tree | null; + abstract parent: SyntaxNode | null; + abstract firstChild: SyntaxNode | null; + abstract lastChild: SyntaxNode | null; + abstract childAfter(pos: number): SyntaxNode | null; + abstract childBefore(pos: number): SyntaxNode | null; + abstract enter(pos: number, side: -1 | 0 | 1, mode?: IterMode): SyntaxNode | null; + abstract nextSibling: SyntaxNode | null; + abstract prevSibling: SyntaxNode | null; + abstract toTree(): Tree; + abstract prop(prop: NodeProp): T | undefined; + cursor(mode?: IterMode): TreeCursor; + getChild(type: string | number, before?: string | number | null, after?: string | number | null): SyntaxNode; + getChildren(type: string | number, before?: string | number | null, after?: string | number | null): SyntaxNode[]; + resolve(pos: number, side?: -1 | 0 | 1): SyntaxNode; + resolveInner(pos: number, side?: -1 | 0 | 1): SyntaxNode; + matchContext(context: readonly string[]): boolean; + enterUnfinishedNodesBefore(pos: number): SyntaxNode; + get node(): this; + get next(): SyntaxNode; +} +export declare class TreeNode extends BaseNode implements SyntaxNode { + readonly _tree: Tree; + readonly from: number; + readonly index: number; + readonly _parent: TreeNode | null; + constructor(_tree: Tree, from: number, index: number, _parent: TreeNode | null); + get type(): NodeType; + get name(): string; + get to(): number; + nextChild(i: number, dir: 1 | -1, pos: number, side: Side, mode?: IterMode): TreeNode | BufferNode | null; + get firstChild(): TreeNode | BufferNode; + get lastChild(): TreeNode | BufferNode; + childAfter(pos: number): TreeNode | BufferNode; + childBefore(pos: number): TreeNode | BufferNode; + prop(prop: NodeProp): T | undefined; + enter(pos: number, side: -1 | 0 | 1, mode?: number): TreeNode | BufferNode; + nextSignificantParent(): TreeNode; + get parent(): TreeNode | null; + get nextSibling(): SyntaxNode | null; + get prevSibling(): SyntaxNode | null; + get tree(): Tree; + toTree(): Tree; +} +declare class BufferContext { + readonly parent: TreeNode; + readonly buffer: TreeBuffer; + readonly index: number; + readonly start: number; + constructor(parent: TreeNode, buffer: TreeBuffer, index: number, start: number); +} +export declare class BufferNode extends BaseNode { + readonly context: BufferContext; + readonly _parent: BufferNode | null; + readonly index: number; + type: NodeType; + get name(): string; + get from(): number; + get to(): number; + constructor(context: BufferContext, _parent: BufferNode | null, index: number); + child(dir: 1 | -1, pos: number, side: Side): BufferNode | null; + get firstChild(): BufferNode; + get lastChild(): BufferNode; + childAfter(pos: number): BufferNode; + childBefore(pos: number): BufferNode; + prop(prop: NodeProp): T | undefined; + enter(pos: number, side: -1 | 0 | 1, mode?: IterMode): BufferNode; + get parent(): SyntaxNode | null; + externalSibling(dir: 1 | -1): TreeNode | BufferNode; + get nextSibling(): SyntaxNode | null; + get prevSibling(): SyntaxNode | null; + get tree(): any; + toTree(): Tree; +} +export declare class TreeCursor implements SyntaxNodeRef { + type: NodeType; + get name(): string; + from: number; + to: number; + private stack; + private bufferNode; + private yieldNode; + private yieldBuf; + firstChild(): boolean; + lastChild(): boolean; + childAfter(pos: number): boolean; + childBefore(pos: number): boolean; + enter(pos: number, side: -1 | 0 | 1, mode?: IterMode): boolean; + parent(): boolean; + nextSibling(): boolean; + prevSibling(): boolean; + private atLastNode; + private move; + next(enter?: boolean): boolean; + prev(enter?: boolean): boolean; + moveTo(pos: number, side?: -1 | 0 | 1): this; + get node(): SyntaxNode; + get tree(): Tree | null; + iterate(enter: (node: SyntaxNodeRef) => boolean | void, leave?: (node: SyntaxNodeRef) => void): void; + matchContext(context: readonly string[]): boolean; +} +export declare class NodeWeakMap { + private map; + private setBuffer; + private getBuffer; + set(node: SyntaxNode, value: T): void; + get(node: SyntaxNode): T | undefined; + cursorSet(cursor: TreeCursor, value: T): void; + cursorGet(cursor: TreeCursor): T | undefined; +} +export {}; diff --git a/src/vendor/cm-types/crelt/index.d.ts b/src/vendor/cm-types/crelt/index.d.ts new file mode 100644 index 0000000..6d9aa89 --- /dev/null +++ b/src/vendor/cm-types/crelt/index.d.ts @@ -0,0 +1,4 @@ +type Child = string | Node | null | undefined | readonly Child[] + +export default function crelt(elt: string | HTMLElement, attrs: {[attr: string]: any}, ...children: Child[]): HTMLElement +export default function crelt(elt: string | HTMLElement, ...children: Child[]): HTMLElement diff --git a/src/vendor/cm-types/find-cluster-break/src/index.d.ts b/src/vendor/cm-types/find-cluster-break/src/index.d.ts new file mode 100644 index 0000000..b96d8b7 --- /dev/null +++ b/src/vendor/cm-types/find-cluster-break/src/index.d.ts @@ -0,0 +1,15 @@ +/** + Query whether the given character has a `Grapheme_Cluster_Break` + value of `Extend` in Unicode. +*/ +export declare function isExtendingChar(code: number): boolean + +/** + Returns a next grapheme cluster break _after_ (not equal to) `pos`, + if `forward` is true, or before otherwise. Returns `pos` itself if no + further cluster break is available in the string. Moves across + surrogate pairs, extending characters (when `includeExtending` is + true, which is the default), characters joined with zero-width joiners, + and flag emoji. +*/ +export declare function findClusterBreak(str: string, pos: number, forward?: boolean, includeExtending?: boolean): number diff --git a/src/vendor/cm-types/highlight/src/highlight.d.ts b/src/vendor/cm-types/highlight/src/highlight.d.ts new file mode 100644 index 0000000..8cd19a2 --- /dev/null +++ b/src/vendor/cm-types/highlight/src/highlight.d.ts @@ -0,0 +1,116 @@ +import { Tree, NodeType, SyntaxNodeRef } from "../../common/src/index.js"; +export declare class Tag { + readonly set: Tag[]; + toString(): string; + static define(name?: string, parent?: Tag): Tag; + static define(parent?: Tag): Tag; + static defineModifier(name?: string): (tag: Tag) => Tag; +} +export declare function styleTags(spec: { + [selector: string]: Tag | readonly Tag[]; +}): import("@lezer/common").NodePropSource; +export interface Highlighter { + style(tags: readonly Tag[]): string | null; + scope?(node: NodeType): boolean; +} +export declare function tagHighlighter(tags: readonly { + tag: Tag | readonly Tag[]; + class: string; +}[], options?: { + scope?: (node: NodeType) => boolean; + all?: string; +}): Highlighter; +export declare function highlightTree(tree: Tree, highlighter: Highlighter | readonly Highlighter[], putStyle: (from: number, to: number, classes: string) => void, from?: number, to?: number): void; +export declare function highlightCode(code: string, tree: Tree, highlighter: Highlighter | readonly Highlighter[], putText: (code: string, classes: string) => void, putBreak: () => void, from?: number, to?: number): void; +export declare function getStyleTags(node: SyntaxNodeRef): { + tags: readonly Tag[]; + opaque: boolean; + inherit: boolean; +} | null; +export declare const tags: { + comment: Tag; + lineComment: Tag; + blockComment: Tag; + docComment: Tag; + name: Tag; + variableName: Tag; + typeName: Tag; + tagName: Tag; + propertyName: Tag; + attributeName: Tag; + className: Tag; + labelName: Tag; + namespace: Tag; + macroName: Tag; + literal: Tag; + string: Tag; + docString: Tag; + character: Tag; + attributeValue: Tag; + number: Tag; + integer: Tag; + float: Tag; + bool: Tag; + regexp: Tag; + escape: Tag; + color: Tag; + url: Tag; + keyword: Tag; + self: Tag; + null: Tag; + atom: Tag; + unit: Tag; + modifier: Tag; + operatorKeyword: Tag; + controlKeyword: Tag; + definitionKeyword: Tag; + moduleKeyword: Tag; + operator: Tag; + derefOperator: Tag; + arithmeticOperator: Tag; + logicOperator: Tag; + bitwiseOperator: Tag; + compareOperator: Tag; + updateOperator: Tag; + definitionOperator: Tag; + typeOperator: Tag; + controlOperator: Tag; + punctuation: Tag; + separator: Tag; + bracket: Tag; + angleBracket: Tag; + squareBracket: Tag; + paren: Tag; + brace: Tag; + content: Tag; + heading: Tag; + heading1: Tag; + heading2: Tag; + heading3: Tag; + heading4: Tag; + heading5: Tag; + heading6: Tag; + contentSeparator: Tag; + list: Tag; + quote: Tag; + emphasis: Tag; + strong: Tag; + link: Tag; + monospace: Tag; + strikethrough: Tag; + inserted: Tag; + deleted: Tag; + changed: Tag; + invalid: Tag; + meta: Tag; + documentMeta: Tag; + annotation: Tag; + processingInstruction: Tag; + definition: (tag: Tag) => Tag; + constant: (tag: Tag) => Tag; + function: (tag: Tag) => Tag; + standard: (tag: Tag) => Tag; + local: (tag: Tag) => Tag; + special: (tag: Tag) => Tag; +}; +export declare const classHighlighter: Highlighter; diff --git a/src/vendor/cm-types/language/src/fold.d.ts b/src/vendor/cm-types/language/src/fold.d.ts new file mode 100644 index 0000000..2b8e559 --- /dev/null +++ b/src/vendor/cm-types/language/src/fold.d.ts @@ -0,0 +1,57 @@ +import { NodeProp, SyntaxNode } from "../../common/src/index.js"; +import { EditorState, Facet, StateField, Extension } from "../../state/src/index.js"; +import { EditorView, BlockInfo, Command, DecorationSet, KeyBinding, ViewUpdate } from "../../view/src/index.js"; +export declare const foldService: Facet<(state: EditorState, lineStart: number, lineEnd: number) => ({ + from: number; + to: number; +} | null), readonly ((state: EditorState, lineStart: number, lineEnd: number) => ({ + from: number; + to: number; +} | null))[]>; +export declare const foldNodeProp: NodeProp<(node: SyntaxNode, state: EditorState) => ({ + from: number; + to: number; +} | null)>; +export declare function foldInside(node: SyntaxNode): { + from: number; + to: number; +} | null; +export declare function foldable(state: EditorState, lineStart: number, lineEnd: number): { + from: number; + to: number; +}; +type DocRange = { + from: number; + to: number; +}; +export declare const foldEffect: import("entry").StateEffectType; +export declare const unfoldEffect: import("entry").StateEffectType; +export declare const foldState: StateField; +export declare function foldedRanges(state: EditorState): DecorationSet; +export declare const foldCode: Command; +export declare const unfoldCode: Command; +export declare const foldAll: Command; +export declare const unfoldAll: Command; +export declare const toggleFold: Command; +export declare const foldKeymap: readonly KeyBinding[]; +interface FoldConfig { + placeholderDOM?: ((view: EditorView, onclick: (event: Event) => void, prepared: any) => HTMLElement) | null; + placeholderText?: string; + preparePlaceholder?: (state: EditorState, range: { + from: number; + to: number; + }) => any; +} +export declare function codeFolding(config?: FoldConfig): Extension; +type Handlers = { + [event: string]: (view: EditorView, line: BlockInfo, event: Event) => boolean; +}; +interface FoldGutterConfig { + markerDOM?: ((open: boolean) => HTMLElement) | null; + openText?: string; + closedText?: string; + domEventHandlers?: Handlers; + foldingChanged?: (update: ViewUpdate) => boolean; +} +export declare function foldGutter(config?: FoldGutterConfig): Extension; +export {}; diff --git a/src/vendor/cm-types/language/src/highlight.d.ts b/src/vendor/cm-types/language/src/highlight.d.ts new file mode 100644 index 0000000..4d25efd --- /dev/null +++ b/src/vendor/cm-types/language/src/highlight.d.ts @@ -0,0 +1,27 @@ +import { NodeType } from "../../common/src/index.js"; +import { Tag, Highlighter } from "../../highlight/src/highlight.js"; +import { StyleSpec, StyleModule } from "../../style-mod/src/style-mod.js"; +import { EditorState, Extension } from "../../state/src/index.js"; +import { Language } from "./language"; +export declare class HighlightStyle implements Highlighter { + readonly specs: readonly TagStyle[]; + readonly module: StyleModule | null; + readonly style: (tags: readonly Tag[]) => string | null; + readonly scope?: (type: NodeType) => boolean; + private constructor(); + static define(specs: readonly TagStyle[], options?: { + scope?: Language | NodeType; + all?: string | StyleSpec; + themeType?: "dark" | "light"; + }): HighlightStyle; +} +export declare function syntaxHighlighting(highlighter: Highlighter, options?: { + fallback: boolean; +}): Extension; +export declare function highlightingFor(state: EditorState, tags: readonly Tag[], scope?: NodeType): string | null; +export interface TagStyle { + tag: Tag | readonly Tag[]; + class?: string; + [styleProperty: string]: any; +} +export declare const defaultHighlightStyle: HighlightStyle; diff --git a/src/vendor/cm-types/language/src/indent.d.ts b/src/vendor/cm-types/language/src/indent.d.ts new file mode 100644 index 0000000..653bd8e --- /dev/null +++ b/src/vendor/cm-types/language/src/indent.d.ts @@ -0,0 +1,48 @@ +import { NodeProp, SyntaxNode } from "../../common/src/index.js"; +import { EditorState, Extension, Facet } from "../../state/src/index.js"; +export declare const indentService: Facet<(context: IndentContext, pos: number) => number | null | undefined, readonly ((context: IndentContext, pos: number) => number | null | undefined)[]>; +export declare const indentUnit: Facet; +export declare function getIndentUnit(state: EditorState): number; +export declare function indentString(state: EditorState, cols: number): string; +export declare function getIndentation(context: IndentContext | EditorState, pos: number): number | null; +export declare function indentRange(state: EditorState, from: number, to: number): import("entry").ChangeSet; +export declare class IndentContext { + readonly state: EditorState; + unit: number; + constructor(state: EditorState, options?: { + overrideIndentation?: (pos: number) => number; + simulateBreak?: number; + simulateDoubleBreak?: boolean; + }); + lineAt(pos: number, bias?: -1 | 1): { + text: string; + from: number; + }; + textAfterPos(pos: number, bias?: -1 | 1): string; + column(pos: number, bias?: -1 | 1): number; + countColumn(line: string, pos?: number): number; + lineIndent(pos: number, bias?: -1 | 1): number; + get simulatedBreak(): number | null; +} +export declare const indentNodeProp: NodeProp<(context: TreeIndentContext) => number | null>; +export declare class TreeIndentContext extends IndentContext { + private base; + readonly pos: number; + private constructor(); + get node(): SyntaxNode; + get textAfter(): string; + get baseIndent(): number; + baseIndentFor(node: SyntaxNode): number; + continue(): number; +} +export declare function delimitedIndent({ closing, align, units }: { + closing: string; + align?: boolean; + units?: number; +}): (context: TreeIndentContext) => number; +export declare const flatIndent: (context: TreeIndentContext) => number; +export declare function continuedIndent({ except, units }?: { + except?: RegExp; + units?: number; +}): (context: TreeIndentContext) => number; +export declare function indentOnInput(): Extension; diff --git a/src/vendor/cm-types/language/src/index.d.ts b/src/vendor/cm-types/language/src/index.d.ts new file mode 100644 index 0000000..9752681 --- /dev/null +++ b/src/vendor/cm-types/language/src/index.d.ts @@ -0,0 +1,8 @@ +export { language, Language, LRLanguage, Sublanguage, sublanguageProp, defineLanguageFacet, syntaxTree, ensureSyntaxTree, languageDataProp, ParseContext, LanguageSupport, LanguageDescription, syntaxTreeAvailable, syntaxParserRunning, forceParsing, DocInput } from "./language"; +export { IndentContext, getIndentUnit, indentString, indentOnInput, indentService, getIndentation, indentRange, indentUnit, TreeIndentContext, indentNodeProp, delimitedIndent, continuedIndent, flatIndent } from "./indent"; +export { foldService, foldNodeProp, foldInside, foldable, foldCode, unfoldCode, toggleFold, foldAll, unfoldAll, foldKeymap, codeFolding, foldGutter, foldedRanges, foldEffect, unfoldEffect, foldState } from "./fold"; +export { HighlightStyle, syntaxHighlighting, highlightingFor, TagStyle, defaultHighlightStyle } from "./highlight"; +export { bracketMatching, Config, matchBrackets, MatchResult, bracketMatchingHandle } from "./matchbrackets"; +export { StreamLanguage, StreamParser } from "./stream-parser"; +export { StringStream } from "./stringstream"; +export { bidiIsolates } from "./isolate"; diff --git a/src/vendor/cm-types/language/src/isolate.d.ts b/src/vendor/cm-types/language/src/isolate.d.ts new file mode 100644 index 0000000..ea0b5c4 --- /dev/null +++ b/src/vendor/cm-types/language/src/isolate.d.ts @@ -0,0 +1,4 @@ +import { Extension } from "../../state/src/index.js"; +export declare function bidiIsolates(options?: { + alwaysIsolate?: boolean; +}): Extension; diff --git a/src/vendor/cm-types/language/src/language.d.ts b/src/vendor/cm-types/language/src/language.d.ts new file mode 100644 index 0000000..ffa824d --- /dev/null +++ b/src/vendor/cm-types/language/src/language.d.ts @@ -0,0 +1,116 @@ +import { Tree, SyntaxNode, TreeFragment, NodeProp, Input, Parser } from "../../common/src/index.js"; +import type { LRParser, ParserConfig } from "../../lr/src/index.js"; +import { EditorState, Extension, Facet, Text } from "../../state/src/index.js"; +import { EditorView } from "../../view/src/index.js"; +export declare const languageDataProp: NodeProp>; +export declare function defineLanguageFacet(baseData?: { + [name: string]: any; +}): Facet<{ + [name: string]: any; +}, readonly { + [name: string]: any; +}[]>; +export interface Sublanguage { + type?: "replace" | "extend"; + test: (node: SyntaxNode, state: EditorState) => boolean; + facet: Facet<{ + [name: string]: any; + }>; +} +export declare const sublanguageProp: NodeProp; +export declare class Language { + readonly data: Facet<{ + [name: string]: any; + }>; + readonly name: string; + readonly extension: Extension; + parser: Parser; + constructor(data: Facet<{ + [name: string]: any; + }>, parser: Parser, extraExtensions?: Extension[], name?: string); + isActiveAt(state: EditorState, pos: number, side?: -1 | 0 | 1): boolean; + findRegions(state: EditorState): { + from: number; + to: number; + }[]; + get allowsNesting(): boolean; +} +export declare class LRLanguage extends Language { + readonly parser: LRParser; + private constructor(); + static define(spec: { + name?: string; + parser: LRParser; + languageData?: { + [name: string]: any; + }; + }): LRLanguage; + configure(options: ParserConfig, name?: string): LRLanguage; + get allowsNesting(): boolean; +} +export declare function syntaxTree(state: EditorState): Tree; +export declare function ensureSyntaxTree(state: EditorState, upto: number, timeout?: number): Tree | null; +export declare function syntaxTreeAvailable(state: EditorState, upto?: number): boolean; +export declare function forceParsing(view: EditorView, upto?: number, timeout?: number): boolean; +export declare function syntaxParserRunning(view: EditorView): boolean; +export declare class DocInput implements Input { + readonly doc: Text; + private cursor; + private cursorPos; + private string; + constructor(doc: Text); + get length(): number; + private syncTo; + chunk(pos: number): string; + get lineChunks(): boolean; + read(from: number, to: number): string; +} +export declare class ParseContext { + private parser; + readonly state: EditorState; + fragments: readonly TreeFragment[]; + viewport: { + from: number; + to: number; + }; + private parse; + private constructor(); + private startParse; + private withContext; + private withoutTempSkipped; + skipUntilInView(from: number, to: number): void; + static getSkippingParser(until?: Promise): Parser; + static get(): ParseContext; +} +export declare const language: Facet; +export declare class LanguageSupport { + readonly language: Language; + readonly support: Extension; + extension: Extension; + constructor(language: Language, support?: Extension); +} +export declare class LanguageDescription { + readonly name: string; + readonly alias: readonly string[]; + readonly extensions: readonly string[]; + readonly filename: RegExp | undefined; + private loadFunc; + support: LanguageSupport | undefined; + private loading; + private constructor(); + load(): Promise; + static of(spec: { + name: string; + alias?: readonly string[]; + extensions?: readonly string[]; + filename?: RegExp; + load?: () => Promise; + support?: LanguageSupport; + }): LanguageDescription; + static matchFilename(descs: readonly LanguageDescription[], filename: string): LanguageDescription; + static matchLanguageName(descs: readonly LanguageDescription[], name: string, fuzzy?: boolean): LanguageDescription; +} diff --git a/src/vendor/cm-types/language/src/matchbrackets.d.ts b/src/vendor/cm-types/language/src/matchbrackets.d.ts new file mode 100644 index 0000000..860f25e --- /dev/null +++ b/src/vendor/cm-types/language/src/matchbrackets.d.ts @@ -0,0 +1,23 @@ +import { EditorState, Extension, Range } from "../../state/src/index.js"; +import { Decoration } from "../../view/src/index.js"; +import { SyntaxNode, NodeProp } from "../../common/src/index.js"; +export interface Config { + afterCursor?: boolean; + brackets?: string; + maxScanDistance?: number; + renderMatch?: (match: MatchResult, state: EditorState) => readonly Range[]; +} +export declare function bracketMatching(config?: Config): Extension; +export declare const bracketMatchingHandle: NodeProp<(node: SyntaxNode) => SyntaxNode | null>; +export interface MatchResult { + start: { + from: number; + to: number; + }; + end?: { + from: number; + to: number; + }; + matched: boolean; +} +export declare function matchBrackets(state: EditorState, pos: number, dir: -1 | 1, config?: Config): MatchResult | null; diff --git a/src/vendor/cm-types/language/src/stream-parser.d.ts b/src/vendor/cm-types/language/src/stream-parser.d.ts new file mode 100644 index 0000000..80f6573 --- /dev/null +++ b/src/vendor/cm-types/language/src/stream-parser.d.ts @@ -0,0 +1,25 @@ +import { Tag } from "../../highlight/src/highlight.js"; +import { Language } from "./language"; +import { IndentContext } from "./indent"; +import { StringStream } from "./stringstream"; +export { StringStream }; +export interface StreamParser { + name?: string; + startState?(indentUnit: number): State; + token(stream: StringStream, state: State): string | null; + blankLine?(state: State, indentUnit: number): void; + copyState?(state: State): State; + indent?(state: State, textAfter: string, context: IndentContext): number | null; + languageData?: { + [name: string]: any; + }; + tokenTable?: { + [name: string]: Tag | readonly Tag[]; + }; + mergeTokens?: boolean; +} +export declare class StreamLanguage extends Language { + private constructor(); + static define(spec: StreamParser): StreamLanguage; + get allowsNesting(): boolean; +} diff --git a/src/vendor/cm-types/language/src/stringstream.d.ts b/src/vendor/cm-types/language/src/stringstream.d.ts new file mode 100644 index 0000000..91cae01 --- /dev/null +++ b/src/vendor/cm-types/language/src/stringstream.d.ts @@ -0,0 +1,25 @@ +export declare class StringStream { + string: string; + private tabSize; + indentUnit: number; + private overrideIndent?; + pos: number; + start: number; + private lastColumnPos; + private lastColumnValue; + constructor(string: string, tabSize: number, indentUnit: number, overrideIndent?: number); + eol(): boolean; + sol(): boolean; + peek(): string; + next(): string | void; + eat(match: string | RegExp | ((ch: string) => boolean)): string | void; + eatWhile(match: string | RegExp | ((ch: string) => boolean)): boolean; + eatSpace(): boolean; + skipToEnd(): void; + skipTo(ch: string): boolean | void; + backUp(n: number): void; + column(): number; + indentation(): number; + match(pattern: string | RegExp, consume?: boolean, caseInsensitive?: boolean): boolean | RegExpMatchArray | null; + current(): string; +} diff --git a/src/vendor/cm-types/lr/src/constants.d.ts b/src/vendor/cm-types/lr/src/constants.d.ts new file mode 100644 index 0000000..1657d56 --- /dev/null +++ b/src/vendor/cm-types/lr/src/constants.d.ts @@ -0,0 +1,45 @@ +export declare const enum Action { + ReduceFlag = 65536, + ValueMask = 65535, + ReduceDepthShift = 19, + RepeatFlag = 131072, + GotoFlag = 131072, + StayFlag = 262144 +} +export declare const enum StateFlag { + Skipped = 1, + Accepting = 2 +} +export declare const enum Specialize { + Specialize = 0, + Extend = 1 +} +export declare const enum Term { + Err = 0 +} +export declare const enum Seq { + End = 65535, + Done = 0, + Next = 1, + Other = 2 +} +export declare const enum ParseState { + Flags = 0, + Actions = 1, + Skip = 2, + TokenizerMask = 3, + DefaultReduce = 4, + ForcedReduce = 5, + Size = 6 +} +export declare const enum Encode { + BigValCode = 126, + BigVal = 65535, + Start = 32, + Gap1 = 34,// '"' + Gap2 = 92,// '\\; + Base = 46 +} +export declare const enum File { + Version = 14 +} diff --git a/src/vendor/cm-types/lr/src/decode.d.ts b/src/vendor/cm-types/lr/src/decode.d.ts new file mode 100644 index 0000000..5e34536 --- /dev/null +++ b/src/vendor/cm-types/lr/src/decode.d.ts @@ -0,0 +1,5 @@ +export declare function decodeArray(input: string | T, Type?: { + new (n: number): T; +}): T; diff --git a/src/vendor/cm-types/lr/src/index.d.ts b/src/vendor/cm-types/lr/src/index.d.ts new file mode 100644 index 0000000..5763a26 --- /dev/null +++ b/src/vendor/cm-types/lr/src/index.d.ts @@ -0,0 +1,3 @@ +export { LRParser, ParserConfig, ContextTracker } from "./parse"; +export { InputStream, ExternalTokenizer, LocalTokenGroup } from "./token"; +export { Stack } from "./stack"; diff --git a/src/vendor/cm-types/lr/src/parse.d.ts b/src/vendor/cm-types/lr/src/parse.d.ts new file mode 100644 index 0000000..8a3990c --- /dev/null +++ b/src/vendor/cm-types/lr/src/parse.d.ts @@ -0,0 +1,110 @@ +import { Tree, TreeFragment, NodeSet, NodeType, NodePropSource, Input, PartialParse, Parser, ParseWrapper } from "../../common/src/index.js"; +import { Stack } from "./stack"; +import { Tokenizer, ExternalTokenizer, CachedToken, InputStream } from "./token"; +declare class FragmentCursor { + readonly fragments: readonly TreeFragment[]; + readonly nodeSet: NodeSet; + i: number; + fragment: TreeFragment | null; + safeFrom: number; + safeTo: number; + trees: Tree[]; + start: number[]; + index: number[]; + nextStart: number; + constructor(fragments: readonly TreeFragment[], nodeSet: NodeSet); + nextFragment(): void; + nodeAt(pos: number): Tree | null; +} +declare class TokenCache { + readonly stream: InputStream; + tokens: CachedToken[]; + mainToken: CachedToken | null; + actions: number[]; + constructor(parser: LRParser, stream: InputStream); + getActions(stack: Stack): number[]; + getMainToken(stack: Stack): CachedToken; + updateCachedToken(token: CachedToken, tokenizer: Tokenizer, stack: Stack): void; + putAction(action: number, token: number, end: number, index: number): number; + addActions(stack: Stack, token: number, end: number, index: number): number; +} +export declare class Parse implements PartialParse { + readonly parser: LRParser; + readonly input: Input; + readonly ranges: readonly { + from: number; + to: number; + }[]; + stacks: Stack[]; + recovering: number; + fragments: FragmentCursor | null; + nextStackID: number; + minStackPos: number; + reused: Tree[]; + stream: InputStream; + tokens: TokenCache; + topTerm: number; + stoppedAt: null | number; + lastBigReductionStart: number; + lastBigReductionSize: number; + bigReductionCount: number; + constructor(parser: LRParser, input: Input, fragments: readonly TreeFragment[], ranges: readonly { + from: number; + to: number; + }[]); + get parsedPos(): number; + advance(): Tree; + stopAt(pos: number): void; + private advanceStack; + private advanceFully; + private runRecovery; + stackToTree(stack: Stack): Tree; + private stackID; +} +export declare class Dialect { + readonly source: string | undefined; + readonly flags: readonly boolean[]; + readonly disabled: null | Uint8Array; + constructor(source: string | undefined, flags: readonly boolean[], disabled: null | Uint8Array); + allows(term: number): boolean; +} +export declare class ContextTracker { + constructor(spec: { + start: T; + shift?(context: T, term: number, stack: Stack, input: InputStream): T; + reduce?(context: T, term: number, stack: Stack, input: InputStream): T; + reuse?(context: T, node: Tree, stack: Stack, input: InputStream): T; + hash?(context: T): number; + strict?: boolean; + }); +} +export interface ParserConfig { + props?: readonly NodePropSource[]; + top?: string; + dialect?: string; + tokenizers?: { + from: ExternalTokenizer; + to: ExternalTokenizer; + }[]; + specializers?: { + from: (value: string, stack: Stack) => number; + to: (value: string, stack: Stack) => number; + }[]; + contextTracker?: ContextTracker; + strict?: boolean; + wrap?: ParseWrapper; + bufferLength?: number; +} +export declare class LRParser extends Parser { + readonly nodeSet: NodeSet; + createParse(input: Input, fragments: readonly TreeFragment[], ranges: readonly { + from: number; + to: number; + }[]): PartialParse; + configure(config: ParserConfig): LRParser; + hasWrappers(): boolean; + getName(term: number): string; + get topNode(): NodeType; + static deserialize(spec: any): LRParser; +} +export {}; diff --git a/src/vendor/cm-types/lr/src/stack.d.ts b/src/vendor/cm-types/lr/src/stack.d.ts new file mode 100644 index 0000000..8fe3dfc --- /dev/null +++ b/src/vendor/cm-types/lr/src/stack.d.ts @@ -0,0 +1,38 @@ +import { BufferCursor } from "../../common/src/index.js"; +export declare const enum Lookahead { + Margin = 25 +} +export declare class Stack { + pos: number; + get context(): any; + canShift(term: number): boolean; + get parser(): import("./parse").LRParser; + dialectEnabled(dialectID: number): boolean; + private shiftContext; + private reduceContext; + private updateContext; +} +export declare const enum Recover { + Insert = 200, + Delete = 190, + Reduce = 100, + MaxNext = 4, + MaxInsertStackDepth = 300, + DampenInsertStackDepth = 120, + MinBigReduction = 2000 +} +export declare class StackBufferCursor implements BufferCursor { + stack: Stack; + pos: number; + index: number; + buffer: number[]; + constructor(stack: Stack, pos: number, index: number); + static create(stack: Stack, pos?: number): StackBufferCursor; + maybeNext(): void; + get id(): number; + get start(): number; + get end(): number; + get size(): number; + next(): void; + fork(): StackBufferCursor; +} diff --git a/src/vendor/cm-types/lr/src/token.d.ts b/src/vendor/cm-types/lr/src/token.d.ts new file mode 100644 index 0000000..7d77824 --- /dev/null +++ b/src/vendor/cm-types/lr/src/token.d.ts @@ -0,0 +1,46 @@ +import { Stack } from "./stack"; +export declare class CachedToken { + start: number; + value: number; + end: number; + extended: number; + lookAhead: number; + mask: number; + context: number; +} +export declare class InputStream { + private chunk2; + private chunk2Pos; + next: number; + pos: number; + private rangeIndex; + private range; + peek(offset: number): any; + acceptToken(token: number, endOffset?: number): void; + acceptTokenTo(token: number, endPos: number): void; + private getChunk; + private readNext; + advance(n?: number): number; + private setDone; +} +export interface Tokenizer { +} +export declare class LocalTokenGroup implements Tokenizer { + readonly precTable: number; + readonly elseToken?: number; + contextual: boolean; + fallback: boolean; + extend: boolean; + readonly data: Readonly; + constructor(data: Readonly | string, precTable: number, elseToken?: number); + token(input: InputStream, stack: Stack): void; +} +interface ExternalOptions { + contextual?: boolean; + fallback?: boolean; + extend?: boolean; +} +export declare class ExternalTokenizer { + constructor(token: (input: InputStream, stack: Stack) => void, options?: ExternalOptions); +} +export {}; diff --git a/src/vendor/cm-types/search/src/cursor.d.ts b/src/vendor/cm-types/search/src/cursor.d.ts new file mode 100644 index 0000000..5f1bd64 --- /dev/null +++ b/src/vendor/cm-types/search/src/cursor.d.ts @@ -0,0 +1,28 @@ +import { Text } from "../../state/src/index.js"; +export declare class SearchCursor implements Iterator<{ + from: number; + to: number; +}> { + private test?; + private iter; + value: { + from: number; + to: number; + }; + done: boolean; + private matches; + private buffer; + private bufferPos; + private bufferStart; + private normalize; + private query; + constructor(text: Text, query: string, from?: number, to?: number, normalize?: (string: string) => string, test?: (from: number, to: number, buffer: string, bufferPos: number) => boolean); + private peek; + next(): this; + nextOverlapping(): this; + private match; + [Symbol.iterator]: () => Iterator<{ + from: number; + to: number; + }>; +} diff --git a/src/vendor/cm-types/search/src/goto-line.d.ts b/src/vendor/cm-types/search/src/goto-line.d.ts new file mode 100644 index 0000000..2a525d3 --- /dev/null +++ b/src/vendor/cm-types/search/src/goto-line.d.ts @@ -0,0 +1,2 @@ +import { Command } from "../../view/src/index.js"; +export declare const gotoLine: Command; diff --git a/src/vendor/cm-types/search/src/index.d.ts b/src/vendor/cm-types/search/src/index.d.ts new file mode 100644 index 0000000..24d3fb5 --- /dev/null +++ b/src/vendor/cm-types/search/src/index.d.ts @@ -0,0 +1,5 @@ +export * from "./search"; +export * from "./cursor"; +export * from "./regexp"; +export * from "./goto-line"; +export * from "./selection-match"; diff --git a/src/vendor/cm-types/search/src/regexp.d.ts b/src/vendor/cm-types/search/src/regexp.d.ts new file mode 100644 index 0000000..d05c08c --- /dev/null +++ b/src/vendor/cm-types/search/src/regexp.d.ts @@ -0,0 +1,35 @@ +import { Text } from "../../state/src/index.js"; +export interface RegExpCursorOptions { + ignoreCase?: boolean; + test?: (from: number, to: number, match: RegExpExecArray) => boolean; +} +export declare class RegExpCursor implements Iterator<{ + from: number; + to: number; + match: RegExpExecArray; +}> { + private text; + private to; + private iter; + private re; + private test?; + private curLine; + private curLineStart; + private matchPos; + done: boolean; + value: { + from: number; + to: number; + match: RegExpExecArray; + }; + constructor(text: Text, query: string, options?: RegExpCursorOptions, from?: number, to?: number); + private getLine; + private nextLine; + next(): this; + [Symbol.iterator]: () => Iterator<{ + from: number; + to: number; + match: RegExpExecArray; + }>; +} +export declare function validRegExp(source: string): boolean; diff --git a/src/vendor/cm-types/search/src/search.d.ts b/src/vendor/cm-types/search/src/search.d.ts new file mode 100644 index 0000000..4ebc6ab --- /dev/null +++ b/src/vendor/cm-types/search/src/search.d.ts @@ -0,0 +1,54 @@ +import { EditorView, Command, KeyBinding, Panel } from "../../view/src/index.js"; +import { EditorState, StateEffect, SelectionRange, StateCommand, Extension, Text } from "../../state/src/index.js"; +import { SearchCursor } from "./cursor"; +import { RegExpCursor } from "./regexp"; +import { gotoLine } from "./goto-line"; +import { selectNextOccurrence } from "./selection-match"; +export { highlightSelectionMatches } from "./selection-match"; +export { SearchCursor, RegExpCursor, gotoLine, selectNextOccurrence }; +interface SearchConfig { + top?: boolean; + caseSensitive?: boolean; + literal?: boolean; + wholeWord?: boolean; + regexp?: boolean; + createPanel?: (view: EditorView) => Panel; + scrollToMatch?: (range: SelectionRange, view: EditorView) => StateEffect; +} +export declare function search(config?: SearchConfig): Extension; +export declare class SearchQuery { + readonly search: string; + readonly caseSensitive: boolean; + readonly literal: boolean; + readonly regexp: boolean; + readonly replace: string; + readonly valid: boolean; + readonly wholeWord: boolean; + readonly test: ((match: string, state: EditorState, from: number, to: number) => boolean) | undefined; + constructor(config: { + search: string; + caseSensitive?: boolean; + literal?: boolean; + regexp?: boolean; + replace?: string; + wholeWord?: boolean; + test?: (match: string, state: EditorState, from: number, to: number) => boolean; + }); + eq(other: SearchQuery): boolean; + getCursor(state: EditorState | Text, from?: number, to?: number): Iterator<{ + from: number; + to: number; + }>; +} +export declare const setSearchQuery: import("entry").StateEffectType; +export declare function getSearchQuery(state: EditorState): SearchQuery; +export declare function searchPanelOpen(state: EditorState): boolean; +export declare const findNext: Command; +export declare const findPrevious: Command; +export declare const selectMatches: Command; +export declare const selectSelectionMatches: StateCommand; +export declare const replaceNext: Command; +export declare const replaceAll: Command; +export declare const openSearchPanel: Command; +export declare const closeSearchPanel: Command; +export declare const searchKeymap: readonly KeyBinding[]; diff --git a/src/vendor/cm-types/search/src/selection-match.d.ts b/src/vendor/cm-types/search/src/selection-match.d.ts new file mode 100644 index 0000000..ff0c76e --- /dev/null +++ b/src/vendor/cm-types/search/src/selection-match.d.ts @@ -0,0 +1,10 @@ +import { Extension, StateCommand } from "../../state/src/index.js"; +type HighlightOptions = { + highlightWordAroundCursor?: boolean; + minSelectionLength?: number; + maxMatches?: number; + wholeWords?: boolean; +}; +export declare function highlightSelectionMatches(options?: HighlightOptions): Extension; +export declare const selectNextOccurrence: StateCommand; +export {}; diff --git a/src/vendor/cm-types/state/src/change.d.ts b/src/vendor/cm-types/state/src/change.d.ts new file mode 100644 index 0000000..abebc97 --- /dev/null +++ b/src/vendor/cm-types/state/src/change.d.ts @@ -0,0 +1,42 @@ +import { Text } from "./text"; +export declare const DefaultSplit: RegExp; +export declare enum MapMode { + Simple = 0, + TrackDel = 1, + TrackBefore = 2, + TrackAfter = 3 +} +export declare class ChangeDesc { + get length(): number; + get newLength(): number; + get empty(): boolean; + iterGaps(f: (posA: number, posB: number, length: number) => void): void; + iterChangedRanges(f: (fromA: number, toA: number, fromB: number, toB: number) => void, individual?: boolean): void; + get invertedDesc(): ChangeDesc; + composeDesc(other: ChangeDesc): ChangeDesc; + mapDesc(other: ChangeDesc, before?: boolean): ChangeDesc; + mapPos(pos: number, assoc?: number): number; + mapPos(pos: number, assoc: number, mode: MapMode): number | null; + touchesRange(from: number, to?: number): boolean | "cover"; + toJSON(): readonly number[]; + static fromJSON(json: any): ChangeDesc; +} +export type ChangeSpec = { + from: number; + to?: number; + insert?: string | Text; +} | ChangeSet | readonly ChangeSpec[]; +export declare class ChangeSet extends ChangeDesc { + private constructor(); + apply(doc: Text): Text; + mapDesc(other: ChangeDesc, before?: boolean): ChangeDesc; + invert(doc: Text): ChangeSet; + compose(other: ChangeSet): ChangeSet; + map(other: ChangeDesc, before?: boolean): ChangeSet; + iterChanges(f: (fromA: number, toA: number, fromB: number, toB: number, inserted: Text) => void, individual?: boolean): void; + get desc(): ChangeDesc; + toJSON(): any; + static of(changes: ChangeSpec, length: number, lineSep?: string): ChangeSet; + static empty(length: number): ChangeSet; + static fromJSON(json: any): ChangeSet; +} diff --git a/src/vendor/cm-types/state/src/char.d.ts b/src/vendor/cm-types/state/src/char.d.ts new file mode 100644 index 0000000..c01ee83 --- /dev/null +++ b/src/vendor/cm-types/state/src/char.d.ts @@ -0,0 +1,4 @@ +export declare function findClusterBreak(str: string, pos: number, forward?: boolean, includeExtending?: boolean): number; +export declare function codePointAt(str: string, pos: number): number; +export declare function fromCodePoint(code: number): string; +export declare function codePointSize(code: number): 1 | 2; diff --git a/src/vendor/cm-types/state/src/charcategory.d.ts b/src/vendor/cm-types/state/src/charcategory.d.ts new file mode 100644 index 0000000..4339cda --- /dev/null +++ b/src/vendor/cm-types/state/src/charcategory.d.ts @@ -0,0 +1,6 @@ +export declare enum CharCategory { + Word = 0, + Space = 1, + Other = 2 +} +export declare function makeCategorizer(wordChars: string): (char: string) => CharCategory; diff --git a/src/vendor/cm-types/state/src/column.d.ts b/src/vendor/cm-types/state/src/column.d.ts new file mode 100644 index 0000000..76eff07 --- /dev/null +++ b/src/vendor/cm-types/state/src/column.d.ts @@ -0,0 +1,2 @@ +export declare function countColumn(string: string, tabSize: number, to?: number): number; +export declare function findColumn(string: string, col: number, tabSize: number, strict?: boolean): number; diff --git a/src/vendor/cm-types/state/src/config.d.ts b/src/vendor/cm-types/state/src/config.d.ts new file mode 100644 index 0000000..a0d0216 --- /dev/null +++ b/src/vendor/cm-types/state/src/config.d.ts @@ -0,0 +1,4 @@ +export declare function combineConfig(configs: readonly Partial[], defaults: Partial, // Should hold only the optional properties of Config, but I haven't managed to express that +combine?: { + [P in keyof Config]?: (first: Config[P], second: Config[P]) => Config[P]; +}): Config; diff --git a/src/vendor/cm-types/state/src/extension.d.ts b/src/vendor/cm-types/state/src/extension.d.ts new file mode 100644 index 0000000..8713b4c --- /dev/null +++ b/src/vendor/cm-types/state/src/extension.d.ts @@ -0,0 +1,18 @@ +import { EditorState } from "./state"; +import { Transaction, TransactionSpec } from "./transaction"; +import { Facet } from "./facet"; +export declare const languageData: Facet<(state: EditorState, pos: number, side: -1 | 0 | 1) => readonly { + [name: string]: any; +}[], readonly ((state: EditorState, pos: number, side: -1 | 0 | 1) => readonly { + [name: string]: any; +}[])[]>; +export type StateCommand = (target: { + state: EditorState; + dispatch: (transaction: Transaction) => void; +}) => boolean; +export declare const allowMultipleSelections: Facet; +export declare const lineSeparator: Facet; +export declare const changeFilter: Facet<(tr: Transaction) => boolean | readonly number[], readonly ((tr: Transaction) => boolean | readonly number[])[]>; +export declare const transactionFilter: Facet<(tr: Transaction) => TransactionSpec | readonly TransactionSpec[], readonly ((tr: Transaction) => TransactionSpec | readonly TransactionSpec[])[]>; +export declare const transactionExtender: Facet<(tr: Transaction) => Pick | null, readonly ((tr: Transaction) => Pick | null)[]>; +export declare const readOnly: Facet; diff --git a/src/vendor/cm-types/state/src/facet.d.ts b/src/vendor/cm-types/state/src/facet.d.ts new file mode 100644 index 0000000..ea72179 --- /dev/null +++ b/src/vendor/cm-types/state/src/facet.d.ts @@ -0,0 +1,115 @@ +import { Transaction, StateEffect } from "./transaction"; +import { EditorState } from "./state"; +type FacetConfig = { + combine?: (value: readonly Input[]) => Output; + compare?: (a: Output, b: Output) => boolean; + compareInput?: (a: Input, b: Input) => boolean; + static?: boolean; + enables?: Extension | ((self: Facet) => Extension); +}; +export declare class Facet implements FacetReader { + private isStatic; + private constructor(); + get reader(): FacetReader; + static define(config?: FacetConfig): Facet; + of(value: Input): Extension; + compute(deps: readonly Slot[], get: (state: EditorState) => Input): Extension; + computeN(deps: readonly Slot[], get: (state: EditorState) => readonly Input[]): Extension; + from(field: StateField): Extension; + from(field: StateField, get: (value: T) => Input): Extension; + tag: Output; +} +export type FacetReader = { + tag: Output; +}; +type Slot = FacetReader | StateField | "doc" | "selection"; +declare const enum Provider { + Static = 0, + Single = 1, + Multi = 2 +} +declare class FacetProvider { + readonly dependencies: readonly Slot[]; + readonly facet: Facet; + readonly type: Provider; + readonly value: ((state: EditorState) => Input) | ((state: EditorState) => readonly Input[]) | Input; + readonly id: number; + extension: Extension; + constructor(dependencies: readonly Slot[], facet: Facet, type: Provider, value: ((state: EditorState) => Input) | ((state: EditorState) => readonly Input[]) | Input); + dynamicSlot(addresses: { + [id: number]: number; + }): DynamicSlot; +} +type StateFieldSpec = { + create: (state: EditorState) => Value; + update: (value: Value, transaction: Transaction) => Value; + compare?: (a: Value, b: Value) => boolean; + provide?: (field: StateField) => Extension; + toJSON?: (value: Value, state: EditorState) => any; + fromJSON?: (json: any, state: EditorState) => Value; +}; +export declare class StateField { + private createF; + private updateF; + private compareF; + private constructor(); + static define(config: StateFieldSpec): StateField; + private create; + init(create: (state: EditorState) => Value): Extension; + get extension(): Extension; +} +export type Extension = { + extension: Extension; +} | readonly Extension[]; +export declare const Prec: { + highest: (ext: Extension) => Extension; + high: (ext: Extension) => Extension; + default: (ext: Extension) => Extension; + low: (ext: Extension) => Extension; + lowest: (ext: Extension) => Extension; +}; +export declare class Compartment { + of(ext: Extension): Extension; + reconfigure(content: Extension): StateEffect; + get(state: EditorState): Extension | undefined; +} +export declare class CompartmentInstance { + readonly compartment: Compartment; + readonly inner: Extension; + constructor(compartment: Compartment, inner: Extension); + extension: Extension; +} +export interface DynamicSlot { + create(state: EditorState): SlotStatus; + update(state: EditorState, tr: Transaction): SlotStatus; + reconfigure(state: EditorState, oldState: EditorState): SlotStatus; +} +export declare class Configuration { + readonly base: Extension; + readonly compartments: Map; + readonly dynamicSlots: DynamicSlot[]; + readonly address: { + [id: number]: number; + }; + readonly staticValues: readonly any[]; + readonly facets: { + [id: number]: readonly FacetProvider[]; + }; + readonly statusTemplate: SlotStatus[]; + constructor(base: Extension, compartments: Map, dynamicSlots: DynamicSlot[], address: { + [id: number]: number; + }, staticValues: readonly any[], facets: { + [id: number]: readonly FacetProvider[]; + }); + staticFacet(facet: Facet): any; + static resolve(base: Extension, compartments: Map, oldState?: EditorState): Configuration; +} +export declare const enum SlotStatus { + Unresolved = 0, + Changed = 1, + Computed = 2, + Computing = 4 +} +export declare function ensureAddr(state: EditorState, addr: number): number; +export declare function getAddr(state: EditorState, addr: number): any; +export {}; diff --git a/src/vendor/cm-types/state/src/index.d.ts b/src/vendor/cm-types/state/src/index.d.ts new file mode 100644 index 0000000..d7ca635 --- /dev/null +++ b/src/vendor/cm-types/state/src/index.d.ts @@ -0,0 +1,12 @@ +export { EditorStateConfig, EditorState } from "./state"; +export { StateCommand } from "./extension"; +export { Facet, FacetReader, StateField, Extension, Prec, Compartment } from "./facet"; +export { EditorSelection, SelectionRange } from "./selection"; +export { Transaction, TransactionSpec, Annotation, AnnotationType, StateEffect, StateEffectType } from "./transaction"; +export { combineConfig } from "./config"; +export { ChangeSpec, ChangeSet, ChangeDesc, MapMode } from "./change"; +export { CharCategory } from "./charcategory"; +export { RangeValue, Range, RangeSet, RangeCursor, RangeSetBuilder, RangeComparator, SpanIterator } from "./rangeset"; +export { findClusterBreak, codePointAt, fromCodePoint, codePointSize } from "./char"; +export { countColumn, findColumn } from "./column"; +export { Line, TextIterator, Text } from "./text"; diff --git a/src/vendor/cm-types/state/src/rangeset.d.ts b/src/vendor/cm-types/state/src/rangeset.d.ts new file mode 100644 index 0000000..b8bcc64 --- /dev/null +++ b/src/vendor/cm-types/state/src/rangeset.d.ts @@ -0,0 +1,73 @@ +import { ChangeDesc, MapMode } from "./change"; +export declare abstract class RangeValue { + eq(other: RangeValue): boolean; + startSide: number; + endSide: number; + mapMode: MapMode; + point: boolean; + range(from: number, to?: number): Range; +} +export declare class Range { + readonly from: number; + readonly to: number; + readonly value: T; + private constructor(); +} +export interface RangeComparator { + compareRange(from: number, to: number, activeA: T[], activeB: T[]): void; + comparePoint(from: number, to: number, pointA: T | null, pointB: T | null): void; + boundChange?(pos: number): void; +} +export interface SpanIterator { + span(from: number, to: number, active: readonly T[], openStart: number): void; + point(from: number, to: number, value: T, active: readonly T[], openStart: number, index: number): void; +} +export interface RangeCursor { + next(): void; + goto(pos: number): void; + value: T | null; + from: number; + to: number; + rank: number; +} +type RangeSetUpdate = { + add?: readonly Range[]; + sort?: boolean; + filter?: (from: number, to: number, value: T) => boolean; + filterFrom?: number; + filterTo?: number; +}; +export declare class RangeSet { + private constructor(); + get size(): number; + update(updateSpec: RangeSetUpdate): RangeSet; + map(changes: ChangeDesc): RangeSet; + between(from: number, to: number, f: (from: number, to: number, value: T) => void | false): void; + iter(from?: number): RangeCursor; + static iter(sets: readonly RangeSet[], from?: number): RangeCursor; + static compare(oldSets: readonly RangeSet[], newSets: readonly RangeSet[], textDiff: ChangeDesc, comparator: RangeComparator, minPointSize?: number): void; + static eq(oldSets: readonly RangeSet[], newSets: readonly RangeSet[], from?: number, to?: number): boolean; + static spans(sets: readonly RangeSet[], from: number, to: number, iterator: SpanIterator, minPointSize?: number): number; + static of(ranges: readonly Range[] | Range, sort?: boolean): RangeSet; + static join(sets: readonly RangeSet[]): RangeSet; + static empty: RangeSet; +} +export declare class RangeSetBuilder { + private chunks; + private chunkPos; + private chunkStart; + private last; + private lastFrom; + private lastTo; + private from; + private to; + private value; + private maxPoint; + private setMaxPoint; + private nextLayer; + private finishChunk; + constructor(); + add(from: number, to: number, value: T): void; + finish(): RangeSet; +} +export {}; diff --git a/src/vendor/cm-types/state/src/selection.d.ts b/src/vendor/cm-types/state/src/selection.d.ts new file mode 100644 index 0000000..9841b56 --- /dev/null +++ b/src/vendor/cm-types/state/src/selection.d.ts @@ -0,0 +1,36 @@ +import { ChangeDesc } from "./change"; +export declare class SelectionRange { + readonly from: number; + readonly to: number; + private flags; + private constructor(); + get anchor(): number; + get head(): number; + get empty(): boolean; + get assoc(): -1 | 0 | 1; + get bidiLevel(): number | null; + get goalColumn(): number; + map(change: ChangeDesc, assoc?: number): SelectionRange; + extend(from: number, to?: number, assoc?: number): SelectionRange; + eq(other: SelectionRange, includeAssoc?: boolean): boolean; + toJSON(): any; + static fromJSON(json: any): SelectionRange; +} +export declare class EditorSelection { + readonly ranges: readonly SelectionRange[]; + readonly mainIndex: number; + private constructor(); + map(change: ChangeDesc, assoc?: number): EditorSelection; + eq(other: EditorSelection, includeAssoc?: boolean): boolean; + get main(): SelectionRange; + asSingle(): EditorSelection; + addRange(range: SelectionRange, main?: boolean): EditorSelection; + replaceRange(range: SelectionRange, which?: number): EditorSelection; + toJSON(): any; + static fromJSON(json: any): EditorSelection; + static single(anchor: number, head?: number): EditorSelection; + static create(ranges: readonly SelectionRange[], mainIndex?: number): EditorSelection; + static cursor(pos: number, assoc?: number, bidiLevel?: number, goalColumn?: number): SelectionRange; + static range(anchor: number, head: number, goalColumn?: number, bidiLevel?: number, assoc?: number): SelectionRange; +} +export declare function checkSelection(selection: EditorSelection, docLength: number): void; diff --git a/src/vendor/cm-types/state/src/state.d.ts b/src/vendor/cm-types/state/src/state.d.ts new file mode 100644 index 0000000..9e1d31b --- /dev/null +++ b/src/vendor/cm-types/state/src/state.d.ts @@ -0,0 +1,67 @@ +import { Text } from "./text"; +import { ChangeSet, ChangeSpec } from "./change"; +import { EditorSelection, SelectionRange } from "./selection"; +import { Transaction, TransactionSpec, StateEffect } from "./transaction"; +import { Facet, FacetReader, Extension, StateField } from "./facet"; +import { CharCategory } from "./charcategory"; +export interface EditorStateConfig { + doc?: string | Text; + selection?: EditorSelection | { + anchor: number; + head?: number; + }; + extensions?: Extension; +} +export declare class EditorState { + readonly doc: Text; + readonly selection: EditorSelection; + private constructor(); + field(field: StateField): T; + field(field: StateField, require: false): T | undefined; + update(...specs: readonly TransactionSpec[]): Transaction; + replaceSelection(text: string | Text): TransactionSpec; + changeByRange(f: (range: SelectionRange) => { + range: SelectionRange; + changes?: ChangeSpec; + effects?: StateEffect | readonly StateEffect[]; + }): { + changes: ChangeSet; + selection: EditorSelection; + effects: readonly StateEffect[]; + }; + changes(spec?: ChangeSpec): ChangeSet; + toText(string: string): Text; + sliceDoc(from?: number, to?: number): string; + facet(facet: FacetReader): Output; + toJSON(fields?: { + [prop: string]: StateField; + }): any; + static fromJSON(json: any, config?: EditorStateConfig, fields?: { + [prop: string]: StateField; + }): EditorState; + static create(config?: EditorStateConfig): EditorState; + static allowMultipleSelections: Facet; + static tabSize: Facet; + get tabSize(): number; + static lineSeparator: Facet; + get lineBreak(): string; + static readOnly: Facet; + get readOnly(): boolean; + static phrases: Facet<{ + [key: string]: string; + }, readonly { + [key: string]: string; + }[]>; + phrase(phrase: string, ...insert: any[]): string; + static languageData: Facet<(state: EditorState, pos: number, side: -1 | 0 | 1) => readonly { + [name: string]: any; + }[], readonly ((state: EditorState, pos: number, side: -1 | 0 | 1) => readonly { + [name: string]: any; + }[])[]>; + languageDataAt(name: string, pos: number, side?: -1 | 0 | 1): readonly T[]; + charCategorizer(at: number): (char: string) => CharCategory; + wordAt(pos: number): SelectionRange | null; + static changeFilter: Facet<(tr: Transaction) => boolean | readonly number[], readonly ((tr: Transaction) => boolean | readonly number[])[]>; + static transactionFilter: Facet<(tr: Transaction) => TransactionSpec | readonly TransactionSpec[], readonly ((tr: Transaction) => TransactionSpec | readonly TransactionSpec[])[]>; + static transactionExtender: Facet<(tr: Transaction) => Pick | null, readonly ((tr: Transaction) => Pick | null)[]>; +} diff --git a/src/vendor/cm-types/state/src/text.d.ts b/src/vendor/cm-types/state/src/text.d.ts new file mode 100644 index 0000000..059f1bd --- /dev/null +++ b/src/vendor/cm-types/state/src/text.d.ts @@ -0,0 +1,33 @@ +export interface TextIterator extends Iterator, Iterable { + next(skip?: number): this; + value: string; + done: boolean; + lineBreak: boolean; +} +export declare abstract class Text implements Iterable { + abstract readonly length: number; + abstract readonly lines: number; + lineAt(pos: number): Line; + line(n: number): Line; + replace(from: number, to: number, text: Text): Text; + append(other: Text): Text; + slice(from: number, to?: number): Text; + abstract sliceString(from: number, to?: number, lineSep?: string): string; + eq(other: Text): boolean; + iter(dir?: 1 | -1): TextIterator; + iterRange(from: number, to?: number): TextIterator; + iterLines(from?: number, to?: number): TextIterator; + toString(): string; + toJSON(): string[]; + abstract readonly children: readonly Text[] | null; + [Symbol.iterator]: () => Iterator; + static of(text: readonly string[]): Text; + static empty: Text; +} +export declare class Line { + readonly from: number; + readonly to: number; + readonly number: number; + readonly text: string; + get length(): number; +} diff --git a/src/vendor/cm-types/state/src/transaction.d.ts b/src/vendor/cm-types/state/src/transaction.d.ts new file mode 100644 index 0000000..3af0e44 --- /dev/null +++ b/src/vendor/cm-types/state/src/transaction.d.ts @@ -0,0 +1,65 @@ +import { ChangeSet, ChangeDesc, ChangeSpec } from "./change"; +import { EditorState } from "./state"; +import { EditorSelection } from "./selection"; +import { Extension } from "./facet"; +import { Text } from "./text"; +export declare class Annotation { + readonly type: AnnotationType; + readonly value: T; + static define(): AnnotationType; + private _isAnnotation; +} +export declare class AnnotationType { + of(value: T): Annotation; +} +interface StateEffectSpec { + map?: (value: Value, mapping: ChangeDesc) => Value | undefined; +} +export declare class StateEffectType { + readonly map: (value: any, mapping: ChangeDesc) => any | undefined; + of(value: Value): StateEffect; +} +export declare class StateEffect { + readonly value: Value; + map(mapping: ChangeDesc): StateEffect | undefined; + is(type: StateEffectType): this is StateEffect; + static define(spec?: StateEffectSpec): StateEffectType; + static mapEffects(effects: readonly StateEffect[], mapping: ChangeDesc): any[] | readonly StateEffect[]; + static reconfigure: StateEffectType; + static appendConfig: StateEffectType; +} +export interface TransactionSpec { + changes?: ChangeSpec; + selection?: EditorSelection | { + anchor: number; + head?: number; + } | undefined; + effects?: StateEffect | readonly StateEffect[]; + annotations?: Annotation | readonly Annotation[]; + userEvent?: string; + scrollIntoView?: boolean; + filter?: boolean; + sequential?: boolean; +} +export declare class Transaction { + readonly startState: EditorState; + readonly changes: ChangeSet; + readonly selection: EditorSelection | undefined; + readonly effects: readonly StateEffect[]; + readonly scrollIntoView: boolean; + private constructor(); + get newDoc(): Text; + get newSelection(): EditorSelection; + get state(): EditorState; + annotation(type: AnnotationType): T | undefined; + get docChanged(): boolean; + get reconfigured(): boolean; + isUserEvent(event: string): boolean; + static time: AnnotationType; + static userEvent: AnnotationType; + static addToHistory: AnnotationType; + static remote: AnnotationType; +} +export declare function resolveTransaction(state: EditorState, specs: readonly TransactionSpec[], filter: boolean): Transaction; +export declare function asArray(value: undefined | T | readonly T[]): readonly T[]; +export {}; diff --git a/src/vendor/cm-types/style-mod/src/style-mod.d.ts b/src/vendor/cm-types/style-mod/src/style-mod.d.ts new file mode 100644 index 0000000..081f0f2 --- /dev/null +++ b/src/vendor/cm-types/style-mod/src/style-mod.d.ts @@ -0,0 +1,16 @@ +export class StyleModule { + constructor(spec: {[selector: string]: StyleSpec}, options?: { + finish?(sel: string): string + }) + getRules(): string + static mount( + root: Document | ShadowRoot | DocumentOrShadowRoot, + module: StyleModule | ReadonlyArray, + options?: {nonce?: string} + ): void + static newName(): string +} + +export type StyleSpec = { + [propOrSelector: string]: string | number | StyleSpec | null +} diff --git a/src/vendor/cm-types/view/src/active-line.d.ts b/src/vendor/cm-types/view/src/active-line.d.ts new file mode 100644 index 0000000..0513c79 --- /dev/null +++ b/src/vendor/cm-types/view/src/active-line.d.ts @@ -0,0 +1,2 @@ +import { Extension } from "../../state/src/index.js"; +export declare function highlightActiveLine(): Extension; diff --git a/src/vendor/cm-types/view/src/attributes.d.ts b/src/vendor/cm-types/view/src/attributes.d.ts new file mode 100644 index 0000000..e362da8 --- /dev/null +++ b/src/vendor/cm-types/view/src/attributes.d.ts @@ -0,0 +1,9 @@ +export type Attrs = { + [name: string]: string; +}; +export declare function combineAttrs(source: Attrs, target: Attrs): Attrs; +export declare const noAttrs: any; +export declare function attrsEq(a: Attrs | null, b: Attrs | null, ignore?: string): boolean; +export declare function setAttrs(dom: HTMLElement, attrs: Attrs): void; +export declare function updateAttrs(dom: HTMLElement, prev: Attrs | null, attrs: Attrs | null): boolean; +export declare function getAttrs(dom: HTMLElement): any; diff --git a/src/vendor/cm-types/view/src/bidi.d.ts b/src/vendor/cm-types/view/src/bidi.d.ts new file mode 100644 index 0000000..61279b2 --- /dev/null +++ b/src/vendor/cm-types/view/src/bidi.d.ts @@ -0,0 +1,23 @@ +import { SelectionRange, Line } from "../../state/src/index.js"; +export declare enum Direction { + LTR = 0, + RTL = 1 +} +export declare class BidiSpan { + readonly from: number; + readonly to: number; + readonly level: number; + get dir(): Direction; +} +export type Isolate = { + from: number; + to: number; + direction: Direction; + inner: readonly Isolate[]; +}; +export declare function isolatesEq(a: readonly Isolate[], b: readonly Isolate[]): boolean; +export declare function computeOrder(line: string, direction: Direction, isolates: readonly Isolate[]): BidiSpan[]; +export declare function trivialOrder(length: number): BidiSpan[]; +export declare let movedOver: string; +export declare function moveVisually(line: Line, order: readonly BidiSpan[], dir: Direction, start: SelectionRange, forward: boolean): SelectionRange; +export declare function autoDirection(text: string, from: number, to: number): Direction; diff --git a/src/vendor/cm-types/view/src/browser.d.ts b/src/vendor/cm-types/view/src/browser.d.ts new file mode 100644 index 0000000..ecb6929 --- /dev/null +++ b/src/vendor/cm-types/view/src/browser.d.ts @@ -0,0 +1,19 @@ +declare const _default: { + mac: boolean; + windows: boolean; + linux: boolean; + ie: boolean; + ie_version: any; + gecko: boolean; + gecko_version: number; + chrome: boolean; + chrome_version: number; + ios: boolean; + android: boolean; + webkit: boolean; + webkit_version: number; + safari: boolean; + safari_version: number; + tabSize: string; +}; +export default _default; diff --git a/src/vendor/cm-types/view/src/buildtile.d.ts b/src/vendor/cm-types/view/src/buildtile.d.ts new file mode 100644 index 0000000..faa474e --- /dev/null +++ b/src/vendor/cm-types/view/src/buildtile.d.ts @@ -0,0 +1,95 @@ +import { Tile, CompositeTile, DocTile, LineTile, MarkTile, WidgetTile, WidgetBufferTile, TextTile, TileFlag, TilePointer, TileWalker } from "./tile"; +import { ChangedRange } from "./extension"; +import { Attrs } from "./attributes"; +import { DecorationSet, MarkDecoration, WidgetType, BlockWrapper } from "./decoration"; +import { RangeSet, TextIterator, Text as DocText, RangeCursor } from "../../state/src/index.js"; +import { EditorView } from "./editorview"; +import { Composition } from "./docview"; +export declare const enum Reused { + Full = 1, + DOM = 2 +} +declare class OpenWrapper { + readonly from: number; + readonly to: number; + readonly wrapper: BlockWrapper; + readonly rank: number; + constructor(from: number, to: number, wrapper: BlockWrapper, rank: number); +} +declare class TileBuilder { + readonly cache: TileCache; + readonly root: DocTile; + readonly blockWrappers: RangeCursor; + curLine: LineTile | null; + lastBlock: LineTile | WidgetTile | null; + afterWidget: WidgetTile | null; + pos: number; + wrappers: OpenWrapper[]; + wrapperPos: number; + constructor(cache: TileCache, root: DocTile, blockWrappers: RangeCursor); + addText(text: string, marks: MarkDecoration[], openStart: number, tile?: TextTile): void; + addComposition(composition: Composition, context: { + marks: MarkTile[]; + line: LineTile; + }): void; + addInlineWidget(widget: WidgetTile, marks: MarkDecoration[], openStart: number): void; + addMark(tile: MarkTile, marks: MarkDecoration[], openStart: number): void; + addBlockWidget(widget: WidgetTile): void; + continueWidget(length: number): void; + addLineStart(attrs: Attrs | null, dom?: HTMLElement): void; + addLine(tile: LineTile): void; + addBreak(): void; + addLineStartIfNotCovered(attrs: Attrs | null): void; + ensureLine(attrs: Attrs | null): void; + ensureMarks(marks: MarkDecoration[], openStart: number): CompositeTile; + endLine(): void; + updateBlockWrappers(): void; + getBlockPos(): CompositeTile; + blockPosCovered(): boolean; + getBuffer(side: -1 | 1): WidgetBufferTile; + flushBuffer(): void; +} +declare class TextStream { + cursor: TextIterator; + skipCount: number; + text: string; + textOff: number; + constructor(doc: DocText); + skip(len: number): void; + next(maxLen: number): null | string; +} +declare class TileCache { + readonly view: EditorView; + buckets: Tile[][]; + index: number[]; + reused: Map; + constructor(view: EditorView); + add(tile: Tile): void; + find(cls: new (...args: any) => Cls, test?: (a: Cls) => boolean, type?: Reused): Cls | null; + findWidget(widget: WidgetType, length: number, flags: TileFlag): WidgetTile; + reuse(tile: T): T; + maybeReuse(tile: T, type?: Reused): T["dom"] | undefined; + clear(): void; +} +export declare class TileUpdate { + readonly view: EditorView; + readonly decorations: readonly DecorationSet[]; + readonly disallowBlockEffectsFor: boolean[]; + text: TextStream; + builder: TileBuilder; + old: TilePointer; + openWidget: boolean; + openMarks: number; + cache: TileCache; + reuseWalker: TileWalker; + constructor(view: EditorView, old: DocTile, blockWrappers: readonly RangeSet[], decorations: readonly DecorationSet[], disallowBlockEffectsFor: boolean[]); + run(changes: readonly ChangedRange[], composition: Composition | null): DocTile; + preserve(length: number, incStart: boolean, incEnd: boolean): void; + emit(from: number, to: number): void; + forward(from: number, to: number, side?: -1 | 1): void; + getCompositionContext(text: Text): { + line: LineTile; + marks: MarkTile[]; + }; +} +export {}; diff --git a/src/vendor/cm-types/view/src/cursor.d.ts b/src/vendor/cm-types/view/src/cursor.d.ts new file mode 100644 index 0000000..c22ece4 --- /dev/null +++ b/src/vendor/cm-types/view/src/cursor.d.ts @@ -0,0 +1,26 @@ +import { EditorState, EditorSelection, SelectionRange, RangeSet } from "../../state/src/index.js"; +import { EditorView } from "./editorview"; +import { BlockInfo } from "./heightmap"; +declare global { + interface Selection { + modify(action: string, direction: string, granularity: string): void; + } +} +export declare function groupAt(state: EditorState, pos: number, bias?: 1 | -1): SelectionRange; +export declare function blockAt(view: EditorView, pos: number, side: -1 | 1): BlockInfo; +export declare function moveToLineBoundary(view: EditorView, start: SelectionRange, forward: boolean, includeWrap: boolean): SelectionRange; +export declare function moveByChar(view: EditorView, start: SelectionRange, forward: boolean, by?: (initial: string) => (next: string) => boolean): SelectionRange; +export declare function byGroup(view: EditorView, pos: number, start: string): (next: string) => boolean; +export declare function moveVertically(view: EditorView, start: SelectionRange, forward: boolean, distance?: number): SelectionRange; +export declare function skipAtomicRanges(atoms: readonly RangeSet[], pos: number, bias: -1 | 0 | 1): number; +export declare function skipAtomsForSelection(atoms: readonly RangeSet[], sel: EditorSelection): EditorSelection; +export declare function skipAtoms(view: EditorView, oldPos: SelectionRange, pos: SelectionRange): SelectionRange; +export declare class PosAssoc { + readonly pos: number; + readonly assoc: -1 | 1; + constructor(pos: number, assoc: -1 | 1); +} +export declare function posAtCoords(view: EditorView, coords: { + x: number; + y: number; +}, precise: boolean, scanY?: 1 | -1): PosAssoc | null; diff --git a/src/vendor/cm-types/view/src/decoration.d.ts b/src/vendor/cm-types/view/src/decoration.d.ts new file mode 100644 index 0000000..900966c --- /dev/null +++ b/src/vendor/cm-types/view/src/decoration.d.ts @@ -0,0 +1,104 @@ +import { RangeValue, Range, RangeSet } from "../../state/src/index.js"; +import { Direction } from "./bidi"; +import { Attrs } from "./attributes"; +import { EditorView } from "./editorview"; +import { Rect } from "./dom"; +interface MarkDecorationSpec { + inclusive?: boolean; + inclusiveStart?: boolean; + inclusiveEnd?: boolean; + attributes?: { + [key: string]: string; + }; + class?: string; + tagName?: string; + bidiIsolate?: Direction | null; + [other: string]: any; +} +interface WidgetDecorationSpec { + widget: WidgetType; + side?: number; + inlineOrder?: boolean; + block?: boolean; + [other: string]: any; +} +interface ReplaceDecorationSpec { + widget?: WidgetType; + inclusive?: boolean; + inclusiveStart?: boolean; + inclusiveEnd?: boolean; + block?: boolean; + [other: string]: any; +} +interface LineDecorationSpec { + attributes?: { + [key: string]: string; + }; + class?: string; + [other: string]: any; +} +export declare abstract class WidgetType { + abstract toDOM(view: EditorView): HTMLElement; + eq(widget: WidgetType): boolean; + updateDOM(dom: HTMLElement, view: EditorView, from: this): boolean; + get estimatedHeight(): number; + get lineBreaks(): number; + ignoreEvent(event: Event): boolean; + coordsAt(dom: HTMLElement, pos: number, side: number): Rect | null; + destroy(dom: HTMLElement): void; +} +export type DecorationSet = RangeSet; +export declare enum BlockType { + Text = 0, + WidgetBefore = 1, + WidgetAfter = 2, + WidgetRange = 3 +} +export declare abstract class Decoration extends RangeValue { + readonly spec: any; + protected constructor(startSide: number, endSide: number, widget: WidgetType | null, spec: any); + abstract eq(other: Decoration): boolean; + static mark(spec: MarkDecorationSpec): Decoration; + static widget(spec: WidgetDecorationSpec): Decoration; + static replace(spec: ReplaceDecorationSpec): Decoration; + static line(spec: LineDecorationSpec): Decoration; + static set(of: Range | readonly Range[], sort?: boolean): DecorationSet; + static none: DecorationSet; +} +export declare class MarkDecoration extends Decoration { + tagName: string; + attrs: Attrs; + constructor(spec: MarkDecorationSpec); + eq(other: Decoration): boolean; + range(from: number, to?: number): Range; +} +export declare class LineDecoration extends Decoration { + constructor(spec: LineDecorationSpec); + eq(other: Decoration): boolean; + range(from: number, to?: number): Range; +} +export declare class PointDecoration extends Decoration { + block: boolean; + readonly isReplace: boolean; + constructor(spec: any, startSide: number, endSide: number, block: boolean, widget: WidgetType | null, isReplace: boolean); + get type(): BlockType.WidgetBefore | BlockType.WidgetAfter | BlockType.WidgetRange; + get heightRelevant(): boolean; + eq(other: Decoration): boolean; + range(from: number, to?: number): Range; +} +export declare function addRange(from: number, to: number, ranges: number[], margin?: number): void; +interface BlockWrapperSpec { + tagName: string; + attributes?: { + [key: string]: string; + }; +} +export declare class BlockWrapper extends RangeValue { + readonly tagName: string; + readonly attributes: Attrs; + private constructor(); + eq(other: RangeValue): boolean; + static create(spec: BlockWrapperSpec): BlockWrapper; + static set(of: Range | readonly Range[], sort?: boolean): RangeSet; +} +export {}; diff --git a/src/vendor/cm-types/view/src/dialog.d.ts b/src/vendor/cm-types/view/src/dialog.d.ts new file mode 100644 index 0000000..d52ea40 --- /dev/null +++ b/src/vendor/cm-types/view/src/dialog.d.ts @@ -0,0 +1,20 @@ +import { StateEffect } from "../../state/src/index.js"; +import { Panel } from "./panel"; +import { EditorView } from "./editorview"; +type DialogConfig = { + content?: (view: EditorView, close: () => void) => HTMLElement; + label?: string; + input?: { + [attr: string]: string; + }; + submitLabel?: string; + class?: string; + focus?: string | boolean; + top?: boolean; +}; +export declare function showDialog(view: EditorView, config: DialogConfig): { + close: StateEffect; + result: Promise; +}; +export declare function getDialog(view: EditorView, className: string): Panel; +export {}; diff --git a/src/vendor/cm-types/view/src/docview.d.ts b/src/vendor/cm-types/view/src/docview.d.ts new file mode 100644 index 0000000..cf387f2 --- /dev/null +++ b/src/vendor/cm-types/view/src/docview.d.ts @@ -0,0 +1,67 @@ +import { RangeSet, SelectionRange } from "../../state/src/index.js"; +import { DecorationSet, BlockWrapper } from "./decoration"; +import { Rect, DOMSelectionState, DOMPos } from "./dom"; +import { ViewUpdate, ChangedRange, ScrollTarget } from "./extension"; +import { EditorView } from "./editorview"; +import { Direction } from "./bidi"; +import { LineTile, DocTile } from "./tile"; +export type Composition = { + range: ChangedRange; + text: Text; +}; +export declare class DocView { + readonly view: EditorView; + tile: DocTile; + decorations: readonly DecorationSet[]; + blockWrappers: readonly RangeSet[]; + dynamicDecorationMap: boolean[]; + domChanged: { + newSel: SelectionRange | null; + } | null; + hasComposition: { + from: number; + to: number; + } | null; + editContextFormatting: DecorationSet; + lastCompositionAfterCursor: boolean; + minWidth: number; + minWidthFrom: number; + minWidthTo: number; + impreciseAnchor: DOMPos | null; + impreciseHead: DOMPos | null; + forceSelection: boolean; + lastUpdate: number; + constructor(view: EditorView); + update(update: ViewUpdate): boolean; + private updateInner; + private updateEditContextFormatting; + updateSelection(mustRead?: boolean, fromPointer?: boolean): void; + suppressWidgetCursorChange(sel: DOMSelectionState, cursor: SelectionRange): boolean; + enforceCursorAssoc(): void; + posFromDOM(node: Node, offset: number): number; + domAtPos(pos: number, side: number): DOMPos; + inlineDOMNearPos(pos: number, side: number): DOMPos; + coordsAt(pos: number, side: number): Rect | null; + lineAt(pos: number, side: number): LineTile; + coordsForChar(pos: number): DOMRect; + measureVisibleLineHeights(viewport: { + from: number; + to: number; + }): number[]; + textDirectionAt(pos: number): Direction; + measureTextSize(): { + lineHeight: number; + charWidth: number; + textHeight: number; + }; + computeBlockGapDeco(): DecorationSet; + updateDeco(): void; + scrollIntoView(target: ScrollTarget): boolean; + lineHasWidget(pos: number): boolean; + destroy(): void; +} +export declare function findCompositionNode(view: EditorView, headPos: number): { + from: number; + to: number; + node: Text; +} | null; diff --git a/src/vendor/cm-types/view/src/dom.d.ts b/src/vendor/cm-types/view/src/dom.d.ts new file mode 100644 index 0000000..fce002e --- /dev/null +++ b/src/vendor/cm-types/view/src/dom.d.ts @@ -0,0 +1,68 @@ +export declare function getSelection(root: DocumentOrShadowRoot): Selection | null; +export declare function contains(dom: Node, node: Node | null): boolean; +export declare function hasSelection(dom: HTMLElement, selection: SelectionRange): boolean; +export declare function clientRectsFor(dom: Node): DOMRectList; +export declare function isEquivalentPosition(node: Node, off: number, targetNode: Node | null, targetOff: number): boolean; +export declare function domIndex(node: Node): number; +export declare function isBlockElement(node: Node): boolean; +export declare function maxOffset(node: Node): number; +export interface Rect { + readonly left: number; + readonly right: number; + readonly top: number; + readonly bottom: number; +} +export declare function flattenRect(rect: Rect, left: boolean): { + left: number; + right: number; + top: number; + bottom: number; +}; +export type ScrollStrategy = "nearest" | "start" | "end" | "center"; +export declare function getScale(elt: HTMLElement, rect: DOMRect): { + scaleX: number; + scaleY: number; +}; +export declare function scrollRectIntoView(dom: HTMLElement, rect: Rect, side: -1 | 1, x: ScrollStrategy, y: ScrollStrategy, xMargin: number, yMargin: number, ltr: boolean): void; +export declare function scrollableParents(dom: HTMLElement, getX?: boolean): { + x: HTMLElement; + y: HTMLElement; +}; +export interface SelectionRange { + focusNode: Node | null; + focusOffset: number; + anchorNode: Node | null; + anchorOffset: number; +} +export declare class DOMSelectionState implements SelectionRange { + anchorNode: Node | null; + anchorOffset: number; + focusNode: Node | null; + focusOffset: number; + eq(domSel: SelectionRange): boolean; + setRange(range: SelectionRange): void; + set(anchorNode: Node | null, anchorOffset: number, focusNode: Node | null, focusOffset: number): void; +} +export declare function focusPreventScroll(dom: HTMLElement): any; +export declare function textRange(node: Text, from: number, to?: number): Range; +export declare function dispatchKey(elt: HTMLElement, name: string, code: number, mods?: KeyboardEvent): boolean; +export declare function getRoot(node: Node | null | undefined): DocumentOrShadowRoot | null; +export declare function clearAttributes(node: HTMLElement): void; +export declare function atElementStart(doc: HTMLElement, selection: SelectionRange): boolean; +export declare function isScrolledToBottom(elt: HTMLElement | Window): boolean; +export declare function textNodeBefore(startNode: Node, startOffset: number): { + node: Text; + offset: number; +} | null; +export declare function textNodeAfter(startNode: Node, startOffset: number): { + node: Text; + offset: number; +} | null; +export declare class DOMPos { + readonly node: Node; + readonly offset: number; + readonly precise: boolean; + constructor(node: Node, offset: number, precise?: boolean); + static before(dom: Node, precise?: boolean): DOMPos; + static after(dom: Node, precise?: boolean): DOMPos; +} diff --git a/src/vendor/cm-types/view/src/domchange.d.ts b/src/vendor/cm-types/view/src/domchange.d.ts new file mode 100644 index 0000000..387862d --- /dev/null +++ b/src/vendor/cm-types/view/src/domchange.d.ts @@ -0,0 +1,27 @@ +import { EditorView } from "./editorview"; +import { EditorSelection, SelectionRange, Text } from "../../state/src/index.js"; +export declare class DOMChange { + readonly typeOver: boolean; + bounds: { + startDOM: Node | null; + endDOM: Node | null; + from: number; + to: number; + } | null; + text: string; + newSel: EditorSelection | null; + domChanged: boolean; + constructor(view: EditorView, start: number, end: number, typeOver: boolean); +} +export declare function applyDOMChange(view: EditorView, domChange: DOMChange): boolean; +export declare function applyDOMChangeInner(view: EditorView, change: { + from: number; + to: number; + insert: Text; +}, newSel: EditorSelection | null, lastKey?: number): boolean; +export declare function findDiff(a: string, b: string, preferredPos: number, preferredSide: string | null): { + from: number; + toA: number; + toB: number; +} | null; +export declare function sameSelPos(selection: EditorSelection, range: SelectionRange): boolean; diff --git a/src/vendor/cm-types/view/src/domobserver.d.ts b/src/vendor/cm-types/view/src/domobserver.d.ts new file mode 100644 index 0000000..29bffc1 --- /dev/null +++ b/src/vendor/cm-types/view/src/domobserver.d.ts @@ -0,0 +1,109 @@ +import { EditorView } from "./editorview"; +import { ViewUpdate, MeasureRequest } from "./extension"; +import { DOMSelectionState } from "./dom"; +import { DOMChange } from "./domchange"; +import type { EditContext } from "./editcontext"; +import { Text, EditorState } from "../../state/src/index.js"; +export declare class DOMObserver { + private view; + dom: HTMLElement; + win: Window; + observer: MutationObserver; + active: boolean; + editContext: EditContextManager | null; + selectionRange: DOMSelectionState; + selectionChanged: boolean; + delayedFlush: number; + resizeTimeout: number; + queue: MutationRecord[]; + delayedAndroidKey: { + key: string; + keyCode: number; + force: boolean; + } | null; + flushingAndroidKey: number; + lastChange: number; + onCharData: any; + scrollTargets: HTMLElement[]; + intersection: IntersectionObserver | null; + resizeScroll: ResizeObserver | null; + intersecting: boolean; + gapIntersection: IntersectionObserver | null; + gaps: readonly HTMLElement[]; + printQuery: MediaQueryList | null; + parentCheck: number; + constructor(view: EditorView); + onScrollChanged(e: Event): void; + onScroll(e: Event): void; + onResize(): void; + onPrint(event: Event): void; + updateGaps(gaps: readonly HTMLElement[]): void; + onSelectionChange(event: Event): void; + readSelectionRange(): boolean; + setSelectionRange(anchor: { + node: Node; + offset: number; + }, head: { + node: Node; + offset: number; + }): void; + clearSelectionRange(): void; + listenForScroll(): void; + ignore(f: () => T): T; + start(): void; + stop(): void; + clear(): void; + delayAndroidKey(key: string, keyCode: number): void; + clearDelayedAndroidKey(): void; + flushSoon(): void; + forceFlush(): void; + pendingRecords(): MutationRecord[]; + processRecords(): { + from: number; + to: number; + typeOver: boolean; + }; + readChange(): DOMChange; + flush(readSelection?: boolean): boolean; + readMutation(rec: MutationRecord): { + from: number; + to: number; + typeOver: boolean; + } | null; + setWindow(win: Window): void; + addWindowListeners(win: Window): void; + removeWindowListeners(win: Window): void; + update(update: ViewUpdate): void; + destroy(): void; +} +declare class EditContextManager { + editContext: EditContext; + measureReq: MeasureRequest; + from: number; + to: number; + pendingContextChange: { + from: number; + to: number; + insert: Text; + } | null; + handlers: { + [name: string]: (e: any) => void; + }; + composing: { + contextBase: number; + editorBase: number; + drifted: boolean; + } | null; + constructor(view: EditorView); + applyEdits(update: ViewUpdate): boolean; + update(update: ViewUpdate): void; + resetRange(state: EditorState): void; + reset(state: EditorState): void; + revertPending(state: EditorState): void; + setSelection(state: EditorState): void; + rangeIsValid(state: EditorState): boolean; + toEditorPos(contextPos: number, clipLen?: number): number; + toContextPos(editorPos: number): number; + destroy(): void; +} +export {}; diff --git a/src/vendor/cm-types/view/src/domreader.d.ts b/src/vendor/cm-types/view/src/domreader.d.ts new file mode 100644 index 0000000..662056b --- /dev/null +++ b/src/vendor/cm-types/view/src/domreader.d.ts @@ -0,0 +1,22 @@ +import { EditorView } from "./editorview"; +export declare const LineBreakPlaceholder = "\uFFFF"; +export declare class DOMReader { + private points; + private view; + text: string; + lineSeparator: string | undefined; + constructor(points: DOMPoint[], view: EditorView); + append(text: string): void; + lineBreak(): void; + readRange(start: Node | null, end: Node | null): this; + readTextNode(node: Text): void; + readNode(node: Node): void; + findPointBefore(node: Node, next: Node | null): void; + findPointInside(node: Node, length: number): void; +} +export declare class DOMPoint { + readonly node: Node; + readonly offset: number; + pos: number; + constructor(node: Node, offset: number); +} diff --git a/src/vendor/cm-types/view/src/draw-selection.d.ts b/src/vendor/cm-types/view/src/draw-selection.d.ts new file mode 100644 index 0000000..65c816a --- /dev/null +++ b/src/vendor/cm-types/view/src/draw-selection.d.ts @@ -0,0 +1,9 @@ +import { Extension, EditorState } from "../../state/src/index.js"; +type SelectionConfig = { + cursorBlinkRate?: number; + drawRangeCursor?: boolean; + iosSelectionHandles?: boolean; +}; +export declare function drawSelection(config?: SelectionConfig): Extension; +export declare function getDrawSelectionConfig(state: EditorState): SelectionConfig; +export {}; diff --git a/src/vendor/cm-types/view/src/dropcursor.d.ts b/src/vendor/cm-types/view/src/dropcursor.d.ts new file mode 100644 index 0000000..761ff5f --- /dev/null +++ b/src/vendor/cm-types/view/src/dropcursor.d.ts @@ -0,0 +1,2 @@ +import { Extension } from "../../state/src/index.js"; +export declare function dropCursor(): Extension; diff --git a/src/vendor/cm-types/view/src/editorview.d.ts b/src/vendor/cm-types/view/src/editorview.d.ts new file mode 100644 index 0000000..41bb33e --- /dev/null +++ b/src/vendor/cm-types/view/src/editorview.d.ts @@ -0,0 +1,185 @@ +import { EditorState, Transaction, TransactionSpec, Extension, SelectionRange, StateEffect, Facet, Line, EditorStateConfig } from "../../state/src/index.js"; +import { StyleModule, StyleSpec } from "../../style-mod/src/style-mod.js"; +import { Rect, ScrollStrategy } from "./dom"; +import { BlockInfo } from "./heightmap"; +import { ViewUpdate, AttrSource, ViewPlugin, PluginValue, MeasureRequest, ScrollTarget } from "./extension"; +import { BidiSpan, Direction } from "./bidi"; +export interface EditorViewConfig extends EditorStateConfig { + state?: EditorState; + parent?: Element | DocumentFragment; + root?: Document | ShadowRoot; + scrollTo?: StateEffect; + dispatchTransactions?: (trs: readonly Transaction[], view: EditorView) => void; + dispatch?: (tr: Transaction, view: EditorView) => void; +} +export declare const enum UpdateState { + Idle = 0,// Not updating + Measuring = 1,// In the layout-reading phase of a layout check + Updating = 2 +} +export declare class EditorView { + get state(): EditorState; + get viewport(): { + from: number; + to: number; + }; + get visibleRanges(): readonly { + from: number; + to: number; + }[]; + get inView(): boolean; + get composing(): boolean; + get compositionStarted(): boolean; + private dispatchTransactions; + private _root; + get root(): DocumentOrShadowRoot; + readonly dom: HTMLElement; + readonly scrollDOM: HTMLElement; + readonly contentDOM: HTMLElement; + private announceDOM; + private plugins; + private pluginMap; + private editorAttrs; + private contentAttrs; + private styleModules; + private bidiCache; + private destroyed; + constructor(config?: EditorViewConfig); + dispatch(tr: Transaction): void; + dispatch(trs: readonly Transaction[]): void; + dispatch(...specs: TransactionSpec[]): void; + update(transactions: readonly Transaction[]): void; + setState(newState: EditorState): void; + private updatePlugins; + private docViewUpdate; + get themeClasses(): string; + private updateAttrs; + private showAnnouncements; + private mountStyles; + private readMeasured; + requestMeasure(request?: MeasureRequest): void; + plugin(plugin: ViewPlugin): T | null; + get documentTop(): number; + get documentPadding(): { + top: number; + bottom: number; + }; + get scaleX(): number; + get scaleY(): number; + elementAtHeight(height: number): BlockInfo; + lineBlockAtHeight(height: number): BlockInfo; + get viewportLineBlocks(): BlockInfo[]; + lineBlockAt(pos: number): BlockInfo; + get contentHeight(): number; + moveByChar(start: SelectionRange, forward: boolean, by?: (initial: string) => (next: string) => boolean): SelectionRange; + moveByGroup(start: SelectionRange, forward: boolean): SelectionRange; + visualLineSide(line: Line, end: boolean): SelectionRange; + moveToLineBoundary(start: SelectionRange, forward: boolean, includeWrap?: boolean): SelectionRange; + moveVertically(start: SelectionRange, forward: boolean, distance?: number): SelectionRange; + domAtPos(pos: number, side?: -1 | 1): { + node: Node; + offset: number; + }; + posAtDOM(node: Node, offset?: number): number; + posAtCoords(coords: { + x: number; + y: number; + }, precise: false): number; + posAtCoords(coords: { + x: number; + y: number; + }): number | null; + posAndSideAtCoords(coords: { + x: number; + y: number; + }, precise: false): { + pos: number; + assoc: -1 | 1; + }; + posAndSideAtCoords(coords: { + x: number; + y: number; + }): { + pos: number; + assoc: -1 | 1; + } | null; + coordsAtPos(pos: number, side?: -1 | 1): Rect | null; + coordsForChar(pos: number): Rect | null; + get defaultCharacterWidth(): number; + get defaultLineHeight(): number; + get textDirection(): Direction; + textDirectionAt(pos: number): Direction; + get lineWrapping(): boolean; + bidiSpans(line: Line): readonly BidiSpan[]; + get hasFocus(): boolean; + focus(): void; + setRoot(root: Document | ShadowRoot): void; + destroy(): void; + static scrollIntoView(pos: number | SelectionRange, options?: { + y?: ScrollStrategy; + x?: ScrollStrategy; + yMargin?: number; + xMargin?: number; + }): StateEffect; + scrollSnapshot(): StateEffect; + setTabFocusMode(to?: boolean | number): void; + static styleModule: Facet; + static domEventHandlers(handlers: DOMEventHandlers): Extension; + static domEventObservers(observers: DOMEventHandlers): Extension; + static inputHandler: Facet<(view: EditorView, from: number, to: number, text: string, insert: () => Transaction) => boolean, readonly ((view: EditorView, from: number, to: number, text: string, insert: () => Transaction) => boolean)[]>; + static clipboardInputFilter: Facet<(text: string, state: EditorState) => string, readonly ((text: string, state: EditorState) => string)[]>; + static clipboardOutputFilter: Facet<(text: string, state: EditorState) => string, readonly ((text: string, state: EditorState) => string)[]>; + static scrollHandler: Facet<(view: EditorView, range: SelectionRange, options: { + x: ScrollStrategy; + y: ScrollStrategy; + xMargin: number; + yMargin: number; + }) => boolean, readonly ((view: EditorView, range: SelectionRange, options: { + x: ScrollStrategy; + y: ScrollStrategy; + xMargin: number; + yMargin: number; + }) => boolean)[]>; + static focusChangeEffect: Facet<(state: EditorState, focusing: boolean) => StateEffect | null, readonly ((state: EditorState, focusing: boolean) => StateEffect | null)[]>; + static perLineTextDirection: Facet; + static exceptionSink: Facet<(exception: any) => void, readonly ((exception: any) => void)[]>; + static updateListener: Facet<(update: ViewUpdate) => void, readonly ((update: ViewUpdate) => void)[]>; + static editable: Facet; + static mouseSelectionStyle: Facet; + static dragMovesSelection: Facet<(event: MouseEvent) => boolean, readonly ((event: MouseEvent) => boolean)[]>; + static clickAddsSelectionRange: Facet<(event: MouseEvent) => boolean, readonly ((event: MouseEvent) => boolean)[]>; + static decorations: Facet import("entry").DecorationSet), readonly (import("entry").DecorationSet | ((view: EditorView) => import("entry").DecorationSet))[]>; + static blockWrappers: Facet | ((view: EditorView) => import("entry").RangeSet), readonly (import("entry").RangeSet | ((view: EditorView) => import("entry").RangeSet))[]>; + static outerDecorations: Facet import("entry").DecorationSet), readonly (import("entry").DecorationSet | ((view: EditorView) => import("entry").DecorationSet))[]>; + static atomicRanges: Facet<(view: EditorView) => import("entry").RangeSet, readonly ((view: EditorView) => import("entry").RangeSet)[]>; + static bidiIsolatedRanges: Facet import("entry").DecorationSet), readonly (import("entry").DecorationSet | ((view: EditorView) => import("entry").DecorationSet))[]>; + static cursorScrollMargin: Facet; + static scrollMargins: Facet<(view: EditorView) => Partial | null, readonly ((view: EditorView) => Partial | null)[]>; + static theme(spec: { + [selector: string]: StyleSpec; + }, options?: { + dark?: boolean; + }): Extension; + static darkTheme: Facet; + static baseTheme(spec: { + [selector: string]: StyleSpec; + }): Extension; + static cspNonce: Facet; + static contentAttributes: Facet; + static editorAttributes: Facet; + static lineWrapping: Extension; + static announce: import("entry").StateEffectType; + static findFromDOM(dom: HTMLElement): EditorView | null; +} +export interface DOMEventMap extends HTMLElementEventMap { + [other: string]: any; +} +export type DOMEventHandlers = { + [event in keyof DOMEventMap]?: (this: This, event: DOMEventMap[event], view: EditorView) => boolean | void; +}; diff --git a/src/vendor/cm-types/view/src/extension.d.ts b/src/vendor/cm-types/view/src/extension.d.ts new file mode 100644 index 0000000..06ab954 --- /dev/null +++ b/src/vendor/cm-types/view/src/extension.d.ts @@ -0,0 +1,137 @@ +import { EditorState, Transaction, ChangeSet, ChangeDesc, Facet, Line, StateEffect, Extension, SelectionRange, RangeSet } from "../../state/src/index.js"; +import { StyleModule } from "../../style-mod/src/style-mod.js"; +import { DecorationSet, BlockWrapper } from "./decoration"; +import { EditorView, DOMEventHandlers } from "./editorview"; +import { Attrs } from "./attributes"; +import { Isolate } from "./bidi"; +import { Rect, ScrollStrategy } from "./dom"; +import { MakeSelectionStyle } from "./input"; +export type Command = (target: EditorView) => boolean; +export declare const clickAddsSelectionRange: Facet<(event: MouseEvent) => boolean, readonly ((event: MouseEvent) => boolean)[]>; +export declare const dragMovesSelection: Facet<(event: MouseEvent) => boolean, readonly ((event: MouseEvent) => boolean)[]>; +export declare const mouseSelectionStyle: Facet; +export declare const exceptionSink: Facet<(exception: any) => void, readonly ((exception: any) => void)[]>; +export declare const updateListener: Facet<(update: ViewUpdate) => void, readonly ((update: ViewUpdate) => void)[]>; +export declare const inputHandler: Facet<(view: EditorView, from: number, to: number, text: string, insert: () => Transaction) => boolean, readonly ((view: EditorView, from: number, to: number, text: string, insert: () => Transaction) => boolean)[]>; +export declare const focusChangeEffect: Facet<(state: EditorState, focusing: boolean) => StateEffect | null, readonly ((state: EditorState, focusing: boolean) => StateEffect | null)[]>; +export declare const clipboardInputFilter: Facet<(text: string, state: EditorState) => string, readonly ((text: string, state: EditorState) => string)[]>; +export declare const clipboardOutputFilter: Facet<(text: string, state: EditorState) => string, readonly ((text: string, state: EditorState) => string)[]>; +export declare const perLineTextDirection: Facet; +export declare const nativeSelectionHidden: Facet; +export declare const scrollHandler: Facet<(view: EditorView, range: SelectionRange, options: { + x: ScrollStrategy; + y: ScrollStrategy; + xMargin: number; + yMargin: number; +}) => boolean, readonly ((view: EditorView, range: SelectionRange, options: { + x: ScrollStrategy; + y: ScrollStrategy; + xMargin: number; + yMargin: number; +}) => boolean)[]>; +export declare class ScrollTarget { + readonly range: SelectionRange; + readonly y: ScrollStrategy; + readonly x: ScrollStrategy; + readonly yMargin: number; + readonly xMargin: number; + readonly isSnapshot: boolean; + constructor(range: SelectionRange, y: ScrollStrategy, x: ScrollStrategy, yMargin: number, xMargin: number, isSnapshot?: boolean); + map(changes: ChangeDesc): ScrollTarget; + clip(state: EditorState): ScrollTarget; +} +export declare const scrollIntoView: import("entry").StateEffectType; +export declare const setEditContextFormatting: import("entry").StateEffectType; +export declare function logException(state: EditorState, exception: any, context?: string): void; +export declare const editable: Facet; +export interface PluginValue extends Object { + update?(update: ViewUpdate): void; + docViewUpdate?(view: EditorView): void; + destroy?(): void; +} +type PluginSource = { + plugin: ViewPlugin; + arg: Arg; +}; +export declare const viewPlugin: Facet, readonly PluginSource[]>; +export interface PluginSpec { + eventHandlers?: DOMEventHandlers; + eventObservers?: DOMEventHandlers; + provide?: (plugin: ViewPlugin) => Extension; + decorations?: (value: V) => DecorationSet; +} +export declare class ViewPlugin { + extension: Arg extends undefined ? Extension : null; + private baseExtensions; + private constructor(); + of(arg: Arg): Extension; + static define(create: (view: EditorView, arg: Arg) => V, spec?: PluginSpec): ViewPlugin; + static fromClass(cls: { + new (view: EditorView, arg: Arg): V; + }, spec?: PluginSpec): ViewPlugin; +} +export declare class PluginInstance { + spec: PluginSource | null; + mustUpdate: ViewUpdate | null; + value: PluginValue | null; + constructor(spec: PluginSource | null); + get plugin(): ViewPlugin; + update(view: EditorView): this; + destroy(view: EditorView): void; + deactivate(): void; +} +export interface MeasureRequest { + read(view: EditorView): T; + write?(measure: T, view: EditorView): void; + key?: any; +} +export type AttrSource = Attrs | ((view: EditorView) => Attrs | null); +export declare const editorAttributes: Facet; +export declare const contentAttributes: Facet; +export declare const decorations: Facet DecorationSet), readonly (DecorationSet | ((view: EditorView) => DecorationSet))[]>; +export declare const blockWrappers: Facet | ((view: EditorView) => RangeSet), readonly (RangeSet | ((view: EditorView) => RangeSet))[]>; +export declare const outerDecorations: Facet DecorationSet), readonly (DecorationSet | ((view: EditorView) => DecorationSet))[]>; +export declare const atomicRanges: Facet<(view: EditorView) => RangeSet, readonly ((view: EditorView) => RangeSet)[]>; +export declare const bidiIsolatedRanges: Facet DecorationSet), readonly (DecorationSet | ((view: EditorView) => DecorationSet))[]>; +export declare function getIsolatedRanges(view: EditorView, line: Line): readonly Isolate[]; +export declare const scrollMargins: Facet<(view: EditorView) => Partial | null, readonly ((view: EditorView) => Partial | null)[]>; +export declare function getScrollMargins(view: EditorView): { + left: number; + right: number; + top: number; + bottom: number; +}; +export declare const styleModule: Facet; +export declare const enum UpdateFlag { + Focus = 1, + Height = 2, + Viewport = 4, + ViewportMoved = 8, + Geometry = 16 +} +export declare class ChangedRange { + readonly fromA: number; + readonly toA: number; + readonly fromB: number; + readonly toB: number; + constructor(fromA: number, toA: number, fromB: number, toB: number); + join(other: ChangedRange): ChangedRange; + addToSet(set: ChangedRange[]): ChangedRange[]; + static extendWithRanges(diff: readonly ChangedRange[], ranges: number[]): readonly ChangedRange[]; +} +export declare class ViewUpdate { + readonly view: EditorView; + readonly state: EditorState; + readonly transactions: readonly Transaction[]; + readonly changes: ChangeSet; + readonly startState: EditorState; + private constructor(); + get viewportChanged(): boolean; + get viewportMoved(): boolean; + get heightChanged(): boolean; + get geometryChanged(): boolean; + get focusChanged(): boolean; + get docChanged(): boolean; + get selectionSet(): boolean; +} +export {}; diff --git a/src/vendor/cm-types/view/src/gutter.d.ts b/src/vendor/cm-types/view/src/gutter.d.ts new file mode 100644 index 0000000..1abd377 --- /dev/null +++ b/src/vendor/cm-types/view/src/gutter.d.ts @@ -0,0 +1,41 @@ +import { Facet, Extension, EditorState, RangeValue, RangeSet } from "../../state/src/index.js"; +import { EditorView } from "./editorview"; +import { ViewUpdate } from "./extension"; +import { WidgetType } from "./decoration"; +import { BlockInfo } from "./heightmap"; +export declare abstract class GutterMarker extends RangeValue { + eq(other: GutterMarker): boolean; + toDOM?(view: EditorView): Node; + elementClass: string; + destroy(dom: Node): void; +} +export declare const gutterLineClass: Facet, readonly RangeSet[]>; +export declare const gutterWidgetClass: Facet<(view: EditorView, widget: WidgetType, block: BlockInfo) => GutterMarker | null, readonly ((view: EditorView, widget: WidgetType, block: BlockInfo) => GutterMarker | null)[]>; +type Handlers = { + [event: string]: (view: EditorView, line: BlockInfo, event: Event) => boolean; +}; +interface GutterConfig { + class?: string; + renderEmptyElements?: boolean; + markers?: (view: EditorView) => (RangeSet | readonly RangeSet[]); + lineMarker?: (view: EditorView, line: BlockInfo, otherMarkers: readonly GutterMarker[]) => GutterMarker | null; + widgetMarker?: (view: EditorView, widget: WidgetType, block: BlockInfo) => GutterMarker | null; + lineMarkerChange?: null | ((update: ViewUpdate) => boolean); + initialSpacer?: null | ((view: EditorView) => GutterMarker); + updateSpacer?: null | ((spacer: GutterMarker, update: ViewUpdate) => GutterMarker); + domEventHandlers?: Handlers; + side?: "before" | "after"; +} +export declare function gutter(config: GutterConfig): Extension; +export declare function gutters(config?: { + fixed?: boolean; +}): Extension; +interface LineNumberConfig { + formatNumber?: (lineNo: number, state: EditorState) => string; + domEventHandlers?: Handlers; +} +export declare const lineNumberMarkers: Facet, readonly RangeSet[]>; +export declare const lineNumberWidgetMarker: Facet<(view: EditorView, widget: WidgetType, block: BlockInfo) => GutterMarker | null, readonly ((view: EditorView, widget: WidgetType, block: BlockInfo) => GutterMarker | null)[]>; +export declare function lineNumbers(config?: LineNumberConfig): Extension; +export declare function highlightActiveLineGutter(): Extension; +export {}; diff --git a/src/vendor/cm-types/view/src/heightmap.d.ts b/src/vendor/cm-types/view/src/heightmap.d.ts new file mode 100644 index 0000000..f445910 --- /dev/null +++ b/src/vendor/cm-types/view/src/heightmap.d.ts @@ -0,0 +1,71 @@ +import { Text, ChangeSet } from "../../state/src/index.js"; +import { DecorationSet, PointDecoration, BlockType, WidgetType } from "./decoration"; +import { ChangedRange } from "./extension"; +export declare let heightChangeFlag: boolean; +export declare function clearHeightChangeFlag(): void; +export declare class HeightOracle { + lineWrapping: boolean; + doc: Text; + heightSamples: { + [key: number]: boolean; + }; + lineHeight: number; + charWidth: number; + textHeight: number; + lineLength: number; + constructor(lineWrapping: boolean); + heightForGap(from: number, to: number): number; + heightForLine(length: number): number; + setDoc(doc: Text): this; + mustRefreshForWrapping(whiteSpace: string): boolean; + mustRefreshForHeights(lineHeights: number[]): boolean; + refresh(whiteSpace: string, lineHeight: number, charWidth: number, textHeight: number, lineLength: number, knownHeights: number[]): boolean; +} +export declare class MeasuredHeights { + readonly from: number; + readonly heights: number[]; + index: number; + constructor(from: number, heights: number[]); + get more(): boolean; +} +export declare class BlockInfo { + readonly from: number; + readonly length: number; + readonly top: number; + readonly height: number; + readonly _content: readonly BlockInfo[] | PointDecoration | number; + get type(): BlockType | readonly BlockInfo[]; + get to(): number; + get bottom(): number; + get widget(): WidgetType | null; + get widgetLineBreaks(): number; +} +export declare enum QueryType { + ByPos = 0, + ByHeight = 1, + ByPosNoHeight = 2 +} +export declare abstract class HeightMap { + length: number; + height: number; + flags: number; + constructor(length: number, // The number of characters covered + height: number, // Height of this part of the document + flags?: number); + size: number; + get outdated(): boolean; + set outdated(value: boolean); + abstract blockAt(height: number, oracle: HeightOracle, top: number, offset: number): BlockInfo; + abstract lineAt(value: number, type: QueryType, oracle: HeightOracle, top: number, offset: number): BlockInfo; + abstract forEachLine(from: number, to: number, oracle: HeightOracle, top: number, offset: number, f: (line: BlockInfo) => void): void; + abstract updateHeight(oracle: HeightOracle, offset?: number, force?: boolean, measured?: MeasuredHeights): HeightMap; + abstract toString(): void; + setHeight(height: number): void; + replace(_from: number, _to: number, nodes: (HeightMap | null)[]): HeightMap; + decomposeLeft(_to: number, result: (HeightMap | null)[]): void; + decomposeRight(_from: number, result: (HeightMap | null)[]): void; + applyChanges(decorations: readonly DecorationSet[], oldDoc: Text, oracle: HeightOracle, changes: readonly ChangedRange[]): HeightMap; + static empty(): HeightMap; + static of(nodes: (HeightMap | null)[]): HeightMap; +} +export declare function heightRelevantDecoChanges(a: readonly DecorationSet[], b: readonly DecorationSet[], diff: ChangeSet): number[]; diff --git a/src/vendor/cm-types/view/src/highlight-space.d.ts b/src/vendor/cm-types/view/src/highlight-space.d.ts new file mode 100644 index 0000000..ef71faa --- /dev/null +++ b/src/vendor/cm-types/view/src/highlight-space.d.ts @@ -0,0 +1,3 @@ +import { Extension } from "../../state/src/index.js"; +export declare function highlightWhitespace(): Extension; +export declare function highlightTrailingWhitespace(): Extension; diff --git a/src/vendor/cm-types/view/src/index.d.ts b/src/vendor/cm-types/view/src/index.d.ts new file mode 100644 index 0000000..3de254d --- /dev/null +++ b/src/vendor/cm-types/view/src/index.d.ts @@ -0,0 +1,22 @@ +export { EditorView, EditorViewConfig, DOMEventMap, DOMEventHandlers } from "./editorview"; +export { Command, ViewPlugin, PluginValue, PluginSpec, ViewUpdate, logException } from "./extension"; +export { Decoration, DecorationSet, WidgetType, BlockType, BlockWrapper } from "./decoration"; +export { BlockInfo } from "./heightmap"; +export { MouseSelectionStyle } from "./input"; +export { BidiSpan, Direction } from "./bidi"; +export { KeyBinding, keymap, runScopeHandlers } from "./keymap"; +export { drawSelection, getDrawSelectionConfig } from "./draw-selection"; +export { dropCursor } from "./dropcursor"; +export { highlightSpecialChars } from "./special-chars"; +export { scrollPastEnd } from "./scrollpastend"; +export { highlightActiveLine } from "./active-line"; +export { placeholder } from "./placeholder"; +export { Rect } from "./dom"; +export { layer, LayerMarker, RectangleMarker } from "./layer"; +export { MatchDecorator } from "./matchdecorator"; +export { rectangularSelection, crosshairCursor } from "./rectangular-selection"; +export { showTooltip, Tooltip, TooltipView, tooltips, getTooltip, hoverTooltip, HoverTooltipSource, hasHoverTooltips, closeHoverTooltips, repositionTooltips } from "./tooltip"; +export { showPanel, PanelConstructor, Panel, getPanel, panels } from "./panel"; +export { showDialog, getDialog } from "./dialog"; +export { lineNumbers, highlightActiveLineGutter, gutter, gutters, GutterMarker, gutterLineClass, gutterWidgetClass, lineNumberMarkers, lineNumberWidgetMarker } from "./gutter"; +export { highlightWhitespace, highlightTrailingWhitespace } from "./highlight-space"; diff --git a/src/vendor/cm-types/view/src/input.d.ts b/src/vendor/cm-types/view/src/input.d.ts new file mode 100644 index 0000000..5fc127f --- /dev/null +++ b/src/vendor/cm-types/view/src/input.d.ts @@ -0,0 +1,94 @@ +import { EditorSelection, EditorState, SelectionRange, RangeSet, Text } from "../../state/src/index.js"; +import { EditorView } from "./editorview"; +import { ViewUpdate, PluginInstance } from "./extension"; +export declare class InputState { + readonly view: EditorView; + lastKeyCode: number; + lastKeyTime: number; + lastTouchTime: number; + lastTouchX: number; + lastTouchY: number; + lastFocusTime: number; + lastScrollTop: number; + lastScrollLeft: number; + lastWheelEvent: number; + pendingIOSKey: undefined | { + key: string; + keyCode: number; + } | KeyboardEvent; + tabFocusMode: number; + lastSelectionOrigin: string | null; + lastSelectionTime: number; + lastContextMenu: number; + scrollHandlers: ((event: Event) => boolean | void)[]; + handlers: { + [event: string]: { + observers: readonly HandlerFunction[]; + handlers: readonly HandlerFunction[]; + }; + }; + composing: number; + compositionFirstChange: boolean | null; + compositionEndedAt: number; + compositionPendingKey: boolean; + compositionPendingChange: boolean; + insertingText: string; + insertingTextAt: number; + mouseSelection: MouseSelection | null; + draggedContent: SelectionRange | null; + notifiedFocused: boolean; + setSelectionOrigin(origin: string): void; + constructor(view: EditorView); + handleEvent(event: Event): void; + runHandlers(type: string, event: Event): void; + ensureHandlers(plugins: readonly PluginInstance[]): void; + keydown(event: KeyboardEvent): boolean; + flushIOSKey(change?: { + from: number; + to: number; + insert: Text; + }): boolean; + ignoreDuringComposition(event: Event): boolean; + startMouseSelection(mouseSelection: MouseSelection): void; + update(update: ViewUpdate): void; + destroy(): void; +} +type HandlerFunction = (view: EditorView, event: Event) => boolean | void; +export declare const modifierCodes: number[]; +export interface MouseSelectionStyle { + get: (curEvent: MouseEvent, extend: boolean, multiple: boolean) => EditorSelection; + update: (update: ViewUpdate) => boolean | void; +} +export type MakeSelectionStyle = (view: EditorView, event: MouseEvent) => MouseSelectionStyle | null; +declare class MouseSelection { + private view; + private startEvent; + private style; + private mustSelect; + dragging: null | boolean; + extend: boolean; + multiple: boolean; + lastEvent: MouseEvent; + scrollParents: { + x: HTMLElement | null; + y: HTMLElement | null; + }; + scrollSpeed: { + x: number; + y: number; + }; + scrolling: number; + atoms: readonly RangeSet[]; + constructor(view: EditorView, startEvent: MouseEvent, style: MouseSelectionStyle, mustSelect: boolean); + start(event: MouseEvent): void; + move(event: MouseEvent): void; + up(event: MouseEvent): void; + destroy(): void; + setScrollSpeed(sx: number, sy: number): void; + scroll(): void; + select(event: MouseEvent): void; + update(update: ViewUpdate): void; +} +export declare const isFocusChange: import("entry").AnnotationType; +export declare function focusChangeTransaction(state: EditorState, focus: boolean): import("entry").Transaction; +export {}; diff --git a/src/vendor/cm-types/view/src/keymap.d.ts b/src/vendor/cm-types/view/src/keymap.d.ts new file mode 100644 index 0000000..b18ee9a --- /dev/null +++ b/src/vendor/cm-types/view/src/keymap.d.ts @@ -0,0 +1,17 @@ +import { EditorView } from "./editorview"; +import { Command } from "./extension"; +import { Facet } from "../../state/src/index.js"; +export interface KeyBinding { + key?: string; + mac?: string; + win?: string; + linux?: string; + run?: Command; + shift?: Command; + any?: (view: EditorView, event: KeyboardEvent) => boolean; + scope?: string; + preventDefault?: boolean; + stopPropagation?: boolean; +} +export declare const keymap: Facet; +export declare function runScopeHandlers(view: EditorView, event: KeyboardEvent, scope: string): boolean; diff --git a/src/vendor/cm-types/view/src/layer.d.ts b/src/vendor/cm-types/view/src/layer.d.ts new file mode 100644 index 0000000..12187ad --- /dev/null +++ b/src/vendor/cm-types/view/src/layer.d.ts @@ -0,0 +1,32 @@ +import { Extension, SelectionRange } from "../../state/src/index.js"; +import { ViewUpdate } from "./extension"; +import { EditorView } from "./editorview"; +export interface LayerMarker { + eq(other: LayerMarker): boolean; + draw(): HTMLElement; + update?(dom: HTMLElement, oldMarker: LayerMarker): boolean; +} +export declare class RectangleMarker implements LayerMarker { + private className; + readonly left: number; + readonly top: number; + readonly width: number | null; + readonly height: number; + constructor(className: string, left: number, top: number, width: number | null, height: number); + draw(): HTMLDivElement; + update(elt: HTMLElement, prev: RectangleMarker): boolean; + private adjust; + eq(p: RectangleMarker): boolean; + static forRange(view: EditorView, className: string, range: SelectionRange): readonly RectangleMarker[]; +} +interface LayerConfig { + above: boolean; + class?: string; + update(update: ViewUpdate, layer: HTMLElement): boolean; + updateOnDocViewUpdate?: boolean; + markers(view: EditorView): readonly LayerMarker[]; + mount?(layer: HTMLElement, view: EditorView): void; + destroy?(layer: HTMLElement, view: EditorView): void; +} +export declare function layer(config: LayerConfig): Extension; +export {}; diff --git a/src/vendor/cm-types/view/src/matchdecorator.d.ts b/src/vendor/cm-types/view/src/matchdecorator.d.ts new file mode 100644 index 0000000..99f2682 --- /dev/null +++ b/src/vendor/cm-types/view/src/matchdecorator.d.ts @@ -0,0 +1,19 @@ +import { EditorView } from "./editorview"; +import { ViewUpdate } from "./extension"; +import { Decoration, DecorationSet } from "./decoration"; +export declare class MatchDecorator { + private regexp; + private addMatch; + private boundary; + private maxLength; + constructor(config: { + regexp: RegExp; + decoration?: Decoration | ((match: RegExpExecArray, view: EditorView, pos: number) => Decoration | null); + decorate?: (add: (from: number, to: number, decoration: Decoration) => void, from: number, to: number, match: RegExpExecArray, view: EditorView) => void; + boundary?: RegExp; + maxLength?: number; + }); + createDeco(view: EditorView): import("entry").RangeSet; + updateDeco(update: ViewUpdate, deco: DecorationSet): DecorationSet; + private updateRange; +} diff --git a/src/vendor/cm-types/view/src/panel.d.ts b/src/vendor/cm-types/view/src/panel.d.ts new file mode 100644 index 0000000..114bc68 --- /dev/null +++ b/src/vendor/cm-types/view/src/panel.d.ts @@ -0,0 +1,19 @@ +import { Facet, Extension } from "../../state/src/index.js"; +import { EditorView } from "./editorview"; +import { ViewUpdate } from "./extension"; +type PanelConfig = { + topContainer?: HTMLElement; + bottomContainer?: HTMLElement; +}; +export declare function panels(config?: PanelConfig): Extension; +export interface Panel { + dom: HTMLElement; + mount?(): void; + update?(update: ViewUpdate): void; + destroy?(): void; + top?: boolean; +} +export declare function getPanel(view: EditorView, panel: PanelConstructor): Panel; +export type PanelConstructor = (view: EditorView) => Panel; +export declare const showPanel: Facet; +export {}; diff --git a/src/vendor/cm-types/view/src/placeholder.d.ts b/src/vendor/cm-types/view/src/placeholder.d.ts new file mode 100644 index 0000000..4d13cda --- /dev/null +++ b/src/vendor/cm-types/view/src/placeholder.d.ts @@ -0,0 +1,3 @@ +import { Extension } from "../../state/src/index.js"; +import { EditorView } from "./editorview"; +export declare function placeholder(content: string | HTMLElement | ((view: EditorView) => HTMLElement)): Extension; diff --git a/src/vendor/cm-types/view/src/rectangular-selection.d.ts b/src/vendor/cm-types/view/src/rectangular-selection.d.ts new file mode 100644 index 0000000..41e2ae8 --- /dev/null +++ b/src/vendor/cm-types/view/src/rectangular-selection.d.ts @@ -0,0 +1,7 @@ +import { Extension } from "../../state/src/index.js"; +export declare function rectangularSelection(options?: { + eventFilter?: (event: MouseEvent) => boolean; +}): Extension; +export declare function crosshairCursor(options?: { + key?: "Alt" | "Control" | "Shift" | "Meta"; +}): Extension; diff --git a/src/vendor/cm-types/view/src/scrollpastend.d.ts b/src/vendor/cm-types/view/src/scrollpastend.d.ts new file mode 100644 index 0000000..bf7ca55 --- /dev/null +++ b/src/vendor/cm-types/view/src/scrollpastend.d.ts @@ -0,0 +1,2 @@ +import { Extension } from "../../state/src/index.js"; +export declare function scrollPastEnd(): Extension; diff --git a/src/vendor/cm-types/view/src/special-chars.d.ts b/src/vendor/cm-types/view/src/special-chars.d.ts new file mode 100644 index 0000000..9060d84 --- /dev/null +++ b/src/vendor/cm-types/view/src/special-chars.d.ts @@ -0,0 +1,8 @@ +import { Extension } from "../../state/src/index.js"; +interface SpecialCharConfig { + render?: ((code: number, description: string | null, placeholder: string) => HTMLElement) | null; + specialChars?: RegExp; + addSpecialChars?: RegExp | null; +} +export declare function highlightSpecialChars(config?: SpecialCharConfig): Extension; +export {}; diff --git a/src/vendor/cm-types/view/src/theme.d.ts b/src/vendor/cm-types/view/src/theme.d.ts new file mode 100644 index 0000000..a353939 --- /dev/null +++ b/src/vendor/cm-types/view/src/theme.d.ts @@ -0,0 +1,15 @@ +import { Facet } from "../../state/src/index.js"; +import { StyleModule, StyleSpec } from "../../style-mod/src/style-mod.js"; +export declare const theme: Facet; +export declare const darkTheme: Facet; +export declare const baseThemeID: string, baseLightID: string, baseDarkID: string; +export declare const lightDarkIDs: { + "&light": string; + "&dark": string; +}; +export declare function buildTheme(main: string, spec: { + [name: string]: StyleSpec; +}, scopes?: { + [name: string]: string; +}): StyleModule; +export declare const baseTheme: StyleModule; diff --git a/src/vendor/cm-types/view/src/tile.d.ts b/src/vendor/cm-types/view/src/tile.d.ts new file mode 100644 index 0000000..e6c3502 --- /dev/null +++ b/src/vendor/cm-types/view/src/tile.d.ts @@ -0,0 +1,161 @@ +import { Text as DocText } from "../../state/src/index.js"; +import { WidgetType, BlockWrapper, MarkDecoration } from "./decoration"; +import { Attrs } from "./attributes"; +import { type EditorView } from "./editorview"; +import { Rect, DOMPos } from "./dom"; +export declare const enum TileFlag { + BreakAfter = 1, + Synced = 2, + AttrsDirty = 4, + Composition = 8, + Before = 16,// Single-point widget before cursor position + After = 32,// Single-point widget after cursor position + PointWidget = 48, + IncStart = 64,// For replace widgets, IncStart/IncEnd encode inclusivity + IncEnd = 128, + Block = 256,// Distinguishes block widgets from non-block widgets + Widget = 496 +} +export declare abstract class Tile { + dom: HTMLElement | Text; + length: number; + flags: TileFlag; + parent: CompositeTile | null; + constructor(dom: HTMLElement | Text, length: number, flags?: TileFlag); + get breakAfter(): 0 | 1; + get children(): readonly Tile[]; + isWidget(): this is WidgetTile; + get isHidden(): boolean; + isComposite(): this is CompositeTile; + isLine(): this is LineTile; + isText(): this is TextTile; + isBlock(): boolean; + get domAttrs(): Attrs | null; + sync(track?: { + node: Node; + written: boolean; + }): void; + toString(): string; + destroy(): void; + setDOM(dom: this["dom"]): void; + get posAtStart(): number; + get posAtEnd(): number; + posBefore(tile: Tile, start?: number): number; + posAfter(tile: Tile): number; + covers(side: -1 | 1): boolean; + coordsIn(pos: number, side: number): Rect | null; + domPosFor(off: number, side: number): DOMPos; + markDirty(attrs: boolean): void; + get overrideDOMText(): DocText | null; + get root(): DocTile | null; + static get(dom: Node): Tile | undefined; +} +export declare abstract class CompositeTile extends Tile { + dom: HTMLElement; + _children: Tile[]; + constructor(dom: HTMLElement); + isComposite(): this is CompositeTile; + get children(): Tile[]; + get lastChild(): Tile; + append(child: Tile): void; + sync(track?: { + node: Node; + written: boolean; + }): void; +} +export declare class DocTile extends CompositeTile { + readonly view: EditorView; + constructor(view: EditorView, dom: HTMLElement); + owns(tile: Tile | null): boolean; + isBlock(): boolean; + nearest(dom: Node | null): Tile | null; + blockTiles(f: (tile: WidgetTile | LineTile, pos: number) => T | undefined): T; + resolveBlock(pos: number, side: number): { + tile: LineTile | WidgetTile; + offset: number; + }; +} +export declare class BlockWrapperTile extends CompositeTile { + readonly wrapper: BlockWrapper; + dom: HTMLElement; + constructor(dom: HTMLElement, wrapper: BlockWrapper); + isBlock(): boolean; + covers(side: -1 | 1): boolean; + get domAttrs(): Attrs; + static of(wrapper: BlockWrapper, dom?: HTMLElement): BlockWrapperTile; +} +export declare class LineTile extends CompositeTile { + attrs: Attrs; + constructor(dom: HTMLElement, attrs: Attrs); + isLine(): this is LineTile; + static start(attrs: Attrs, dom?: HTMLElement, keepAttrs?: boolean): LineTile; + get domAttrs(): Attrs; + resolveInline(pos: number, side: number, forCoords?: boolean): { + tile: TextTile | WidgetTile | WidgetBufferTile; + offset: number; + } | null; + coordsIn(pos: number, side: number): Rect | null; + domIn(pos: number, side: number): DOMPos; +} +export declare class MarkTile extends CompositeTile { + readonly mark: MarkDecoration; + constructor(dom: HTMLElement, mark: MarkDecoration); + get domAttrs(): Attrs; + static of(mark: MarkDecoration, dom?: HTMLElement): MarkTile; +} +export declare class TextTile extends Tile { + readonly text: string; + dom: Text; + constructor(dom: Text, text: string); + sync(track?: { + node: Node; + written: boolean; + }): void; + isText(): this is TextTile; + toString(): string; + coordsIn(pos: number, side: number): { + left: number; + right: number; + top: number; + bottom: number; + } | DOMRect; + static of(text: string, dom?: Text): TextTile; +} +export declare class WidgetTile extends Tile { + readonly widget: WidgetType; + dom: HTMLElement; + constructor(dom: HTMLElement, length: number, widget: WidgetType, flags: TileFlag); + isWidget(): this is WidgetTile; + get isHidden(): boolean; + covers(side: -1 | 1): boolean; + coordsIn(pos: number, side: number): Rect; + coordsInWidget(pos: number, side: number, block: boolean): Rect; + get overrideDOMText(): DocText; + destroy(): void; + static of(widget: WidgetType, view: EditorView, length: number, flags: TileFlag, dom?: HTMLElement | null): WidgetTile; +} +export declare class WidgetBufferTile extends Tile { + dom: HTMLElement; + constructor(flags: TileFlag); + get isHidden(): boolean; + get overrideDOMText(): DocText; + coordsIn(pos: number): Rect | null; +} +export declare class TilePointer { + tile: Tile; + index: number; + beforeBreak: boolean; + readonly parents: { + tile: CompositeTile; + index: number; + }[]; + constructor(top: DocTile); + advance(dist: number, side: -1 | 1, walker?: TileWalker): this; + get root(): DocTile; +} +export interface TileWalker { + enter(tile: CompositeTile): void; + leave(tile: CompositeTile): void; + skip(tile: Tile, from: number, to: number): boolean | void; + break(): void; +} diff --git a/src/vendor/cm-types/view/src/tooltip.d.ts b/src/vendor/cm-types/view/src/tooltip.d.ts new file mode 100644 index 0000000..f896e27 --- /dev/null +++ b/src/vendor/cm-types/view/src/tooltip.d.ts @@ -0,0 +1,45 @@ +import { EditorState, Transaction, StateEffect, Facet, StateField, Extension } from "../../state/src/index.js"; +import { EditorView } from "./editorview"; +import { ViewUpdate } from "./extension"; +import { Rect } from "./dom"; +export declare function tooltips(config?: { + position?: "fixed" | "absolute"; + parent?: HTMLElement; + tooltipSpace?: (view: EditorView) => Rect; +}): Extension; +export interface Tooltip { + pos: number; + end?: number; + create(view: EditorView): TooltipView; + above?: boolean; + strictSide?: boolean; + arrow?: boolean; + clip?: boolean; +} +export interface TooltipView { + dom: HTMLElement; + offset?: { + x: number; + y: number; + }; + getCoords?: (pos: number) => Rect; + overlap?: boolean; + mount?(view: EditorView): void; + update?(update: ViewUpdate): void; + destroy?(): void; + positioned?(space: Rect): void; + resize?: boolean; +} +export declare const showTooltip: Facet; +export type HoverTooltipSource = (view: EditorView, pos: number, side: -1 | 1) => Tooltip | readonly Tooltip[] | null | Promise; +export declare function hoverTooltip(source: HoverTooltipSource, options?: { + hideOn?: (tr: Transaction, tooltip: Tooltip) => boolean; + hideOnChange?: boolean | "touch"; + hoverTime?: number; +}): Extension & { + active: StateField; +}; +export declare function getTooltip(view: EditorView, tooltip: Tooltip): TooltipView | null; +export declare function hasHoverTooltips(state: EditorState): boolean; +export declare const closeHoverTooltips: StateEffect; +export declare function repositionTooltips(view: EditorView): void; diff --git a/src/vendor/cm-types/view/src/viewstate.d.ts b/src/vendor/cm-types/view/src/viewstate.d.ts new file mode 100644 index 0000000..8525412 --- /dev/null +++ b/src/vendor/cm-types/view/src/viewstate.d.ts @@ -0,0 +1,95 @@ +import { EditorState, ChangeSet, ChangeDesc } from "../../state/src/index.js"; +import { Rect } from "./dom"; +import { HeightMap, HeightOracle, BlockInfo } from "./heightmap"; +import { ViewUpdate, UpdateFlag, ScrollTarget } from "./extension"; +import { Decoration, DecorationSet } from "./decoration"; +import { EditorView } from "./editorview"; +import { Direction } from "./bidi"; +export declare class LineGap { + readonly from: number; + readonly to: number; + readonly size: number; + readonly displaySize: number; + constructor(from: number, to: number, size: number, displaySize: number); + static same(a: readonly LineGap[], b: readonly LineGap[]): boolean; + draw(viewState: ViewState, wrapping: boolean): import("entry").Range; +} +export declare class ViewState { + view: EditorView; + state: EditorState; + pixelViewport: Rect; + inView: boolean; + paddingTop: number; + paddingBottom: number; + contentDOMWidth: number; + contentDOMHeight: number; + editorHeight: number; + editorWidth: number; + scaleX: number; + scaleY: number; + scrollParent: HTMLElement | null; + scrollOffset: number; + scrolledToBottom: boolean; + scrollAnchorPos: number; + scrollAnchorHeight: number; + heightOracle: HeightOracle; + heightMap: HeightMap; + scaler: YScaler; + scrollTarget: ScrollTarget | null; + printing: boolean; + mustMeasureContent: boolean | "refresh"; + stateDeco: readonly DecorationSet[]; + viewportLines: BlockInfo[]; + defaultTextDirection: Direction; + viewport: Viewport; + viewports: readonly Viewport[]; + visibleRanges: readonly { + from: number; + to: number; + }[]; + lineGaps: readonly LineGap[]; + lineGapDeco: DecorationSet; + mustEnforceCursorAssoc: boolean; + constructor(view: EditorView, state: EditorState); + updateForViewport(): 0 | UpdateFlag.Height; + updateScaler(): 0 | UpdateFlag.Height; + updateViewportLines(): void; + update(update: ViewUpdate, scrollTarget?: ScrollTarget | null): void; + measure(): number; + get visibleTop(): number; + get visibleBottom(): number; + getViewport(bias: number, scrollTarget: ScrollTarget | null): Viewport; + mapViewport(viewport: Viewport, changes: ChangeDesc): Viewport; + viewportIsAppropriate({ from, to }: Viewport, bias?: number): boolean; + mapLineGaps(gaps: readonly LineGap[], changes: ChangeSet): any[] | readonly LineGap[]; + ensureLineGaps(current: readonly LineGap[], mayMeasure?: EditorView): LineGap[]; + gapSize(line: BlockInfo, from: number, to: number, structure: LineStructure): number; + updateLineGaps(gaps: readonly LineGap[]): void; + computeVisibleRanges(changes?: ChangeDesc): number; + lineBlockAt(pos: number): BlockInfo; + lineBlockAtHeight(height: number): BlockInfo; + getScrollOffset(): number; + scrollAnchorAt(scrollOffset: number): BlockInfo; + elementAtHeight(height: number): BlockInfo; + get docHeight(): number; + get contentHeight(): number; +} +export declare class Viewport { + readonly from: number; + readonly to: number; + constructor(from: number, to: number); +} +type LineStructure = { + total: number; + ranges: { + from: number; + to: number; + }[]; +}; +type YScaler = { + toDOM(n: number): number; + fromDOM(n: number): number; + scale: number; + eq(other: YScaler): boolean; +}; +export {}; diff --git a/src/vendor/cm-types/w3c-keyname/index.d.ts b/src/vendor/cm-types/w3c-keyname/index.d.ts new file mode 100644 index 0000000..1deebe7 --- /dev/null +++ b/src/vendor/cm-types/w3c-keyname/index.d.ts @@ -0,0 +1,5 @@ +export function keyName(event: Event): string; + +export const base: {[keyCode: number]: string}; + +export const shift: {[keyCode: number]: string}; diff --git a/src/vendor/codemirror.d.ts b/src/vendor/codemirror.d.ts new file mode 100644 index 0000000..e924a52 --- /dev/null +++ b/src/vendor/codemirror.d.ts @@ -0,0 +1,5 @@ +export * from "./cm-types/state/src/index.js"; +export * from "./cm-types/view/src/index.js"; +export { history, historyKeymap, undo, redo, defaultKeymap, indentWithTab, insertNewlineAndIndent, toggleComment, selectAll, indentMore, indentLess } from "./cm-types/commands/src/index.js"; +export { search, searchKeymap, highlightSelectionMatches, openSearchPanel, closeSearchPanel, gotoLine } from "./cm-types/search/src/index.js"; +export { indentUnit, bracketMatching, foldGutter, foldKeymap, codeFolding, foldService, indentService, StreamLanguage, LanguageSupport, syntaxHighlighting, HighlightStyle, defaultHighlightStyle } from "./cm-types/language/src/index.js"; diff --git a/src/vendor/codemirror.js b/src/vendor/codemirror.js new file mode 100644 index 0000000..d6569d6 --- /dev/null +++ b/src/vendor/codemirror.js @@ -0,0 +1,68 @@ +/* CodeMirror 6, bundled for Programming+ from the packages' sources (MIT; see CODEMIRROR-LICENSE next to this file). + * @codemirror/state@6.6.0 @codemirror/view@6.41.0 @codemirror/language@6.12.3 @codemirror/commands@6.10.3 @codemirror/search@6.6.0 @lezer/common@1.5.2 @lezer/highlight@1.2.3 @lezer/lr@1.4.8 style-mod@4.1.3 w3c-keyname@2.2.8 crelt@1.0.6 @marijn/find-cluster-break@1.0.2 + * Rebuild with scripts/vendor/codemirror.sh; do not edit by hand. */ +var Text = class _Text { lineAt(pos) { if (pos < 0 || pos > this.length) throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`); return this.lineInner(pos, !1, 1, 0) } line(n) { if (n < 1 || n > this.lines) throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`); return this.lineInner(n, !0, 1, 0) } replace(from, to, text) { [from, to] = clip(this, from, to); let parts = []; return this.decompose(0, from, parts, 2), text.length && text.decompose(0, text.length, parts, 3), this.decompose(to, this.length, parts, 1), TextNode.from(parts, this.length - (to - from) + text.length) } append(other) { return this.replace(this.length, this.length, other) } slice(from, to = this.length) { [from, to] = clip(this, from, to); let parts = []; return this.decompose(from, to, parts, 0), TextNode.from(parts, to - from) } eq(other) { if (other == this) return !0; if (other.length != this.length || other.lines != this.lines) return !1; let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1), a = new RawTextCursor(this), b = new RawTextCursor(other); for (let skip = start, pos = start; ;) { if (a.next(skip), b.next(skip), skip = 0, a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value) return !1; if (pos += a.value.length, a.done || pos >= end) return !0 } } iter(dir = 1) { return new RawTextCursor(this, dir) } iterRange(from, to = this.length) { return new PartialTextCursor(this, from, to) } iterLines(from, to) { let inner; if (from == null) inner = this.iter(); else { to == null && (to = this.lines + 1); let start = this.line(from).from; inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to)) } return new LineCursor(inner) } toString() { return this.sliceString(0) } toJSON() { let lines = []; return this.flatten(lines), lines } constructor() { } static of(text) { if (text.length == 0) throw new RangeError("A document must have at least one line"); return text.length == 1 && !text[0] ? _Text.empty : text.length <= 32 ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, [])) } static empty }, TextLeaf = class _TextLeaf extends Text { + constructor(text, length = textLength(text)) { super(); this.text = text; this.length = length } text; length; get lines() { return this.text.length } get children() { return null } lineInner(target, isLine, line, offset) { for (let i2 = 0; ; i2++) { let string2 = this.text[i2], end = offset + string2.length; if ((isLine ? line : end) >= target) return new Line(offset, end, line, string2); offset = end + 1, line++ } } decompose(from, to, target, open) { let text = from <= 0 && to >= this.length ? this : new _TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from)); if (open & 1) { let prev = target.pop(), joined = appendText(text.text, prev.text.slice(), 0, text.length); if (joined.length <= 32) target.push(new _TextLeaf(joined, prev.length + text.length)); else { let mid = joined.length >> 1; target.push(new _TextLeaf(joined.slice(0, mid)), new _TextLeaf(joined.slice(mid))) } } else target.push(text) } replace(from, to, text) { if (!(text instanceof _TextLeaf)) return super.replace(from, to, text);[from, to] = clip(this, from, to); let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to), newLen = this.length + text.length - (to - from); return lines.length <= 32 ? new _TextLeaf(lines, newLen) : TextNode.from(_TextLeaf.split(lines, []), newLen) } sliceString(from, to = this.length, lineSep = ` +`) { [from, to] = clip(this, from, to); let result = ""; for (let pos = 0, i2 = 0; pos <= to && i2 < this.text.length; i2++) { let line = this.text[i2], end = pos + line.length; pos > from && i2 && (result += lineSep), from < end && to > pos && (result += line.slice(Math.max(0, from - pos), to - pos)), pos = end + 1 } return result } flatten(target) { for (let line of this.text) target.push(line) } scanIdentical() { return 0 } static split(text, target) { let part = [], len = -1; for (let line of text) part.push(line), len += line.length + 1, part.length == 32 && (target.push(new _TextLeaf(part, len)), part = [], len = -1); return len > -1 && target.push(new _TextLeaf(part, len)), target } +}, TextNode = class _TextNode extends Text { + constructor(children, length) { super(); this.children = children; this.length = length; for (let child of children) this.lines += child.lines } children; length; lines = 0; lineInner(target, isLine, line, offset) { for (let i2 = 0; ; i2++) { let child = this.children[i2], end = offset + child.length, endLine = line + child.lines - 1; if ((isLine ? endLine : end) >= target) return child.lineInner(target, isLine, line, offset); offset = end + 1, line = endLine + 1 } } decompose(from, to, target, open) { for (let i2 = 0, pos = 0; pos <= to && i2 < this.children.length; i2++) { let child = this.children[i2], end = pos + child.length; if (from <= end && to >= pos) { let childOpen = open & ((pos <= from ? 1 : 0) | (end >= to ? 2 : 0)); pos >= from && end <= to && !childOpen ? target.push(child) : child.decompose(from - pos, to - pos, target, childOpen) } pos = end + 1 } } replace(from, to, text) { if ([from, to] = clip(this, from, to), text.lines < this.lines) for (let i2 = 0, pos = 0; i2 < this.children.length; i2++) { let child = this.children[i2], end = pos + child.length; if (from >= pos && to <= end) { let updated = child.replace(from - pos, to - pos, text), totalLines = this.lines - child.lines + updated.lines; if (updated.lines < totalLines >> 4 && updated.lines > totalLines >> 6) { let copy = this.children.slice(); return copy[i2] = updated, new _TextNode(copy, this.length - (to - from) + text.length) } return super.replace(pos, end, updated) } pos = end + 1 } return super.replace(from, to, text) } sliceString(from, to = this.length, lineSep = ` +`) { [from, to] = clip(this, from, to); let result = ""; for (let i2 = 0, pos = 0; i2 < this.children.length && pos <= to; i2++) { let child = this.children[i2], end = pos + child.length; pos > from && i2 && (result += lineSep), from < end && to > pos && (result += child.sliceString(from - pos, to - pos, lineSep)), pos = end + 1 } return result } flatten(target) { for (let child of this.children) child.flatten(target) } scanIdentical(other, dir) { if (!(other instanceof _TextNode)) return 0; let length = 0, [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length] : [this.children.length - 1, other.children.length - 1, -1, -1]; for (; ; iA += dir, iB += dir) { if (iA == eA || iB == eB) return length; let chA = this.children[iA], chB = other.children[iB]; if (chA != chB) return length + chA.scanIdentical(chB, dir); length += chA.length + 1 } } static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) { let lines = 0; for (let ch of children) lines += ch.lines; if (lines < 32) { let flat = []; for (let ch of children) ch.flatten(flat); return new TextLeaf(flat, length) } let chunk = Math.max(32, lines >> 5), maxChunk = chunk << 1, minChunk = chunk >> 1, chunked = [], currentLines = 0, currentLen = -1, currentChunk = []; function add2(child) { let last; if (child.lines > maxChunk && child instanceof _TextNode) for (let node of child.children) add2(node); else child.lines > minChunk && (currentLines > minChunk || !currentLines) ? (flush(), chunked.push(child)) : child instanceof TextLeaf && currentLines && (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf && child.lines + last.lines <= 32 ? (currentLines += child.lines, currentLen += child.length + 1, currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length)) : (currentLines + child.lines > chunk && flush(), currentLines += child.lines, currentLen += child.length + 1, currentChunk.push(child)) } function flush() { currentLines != 0 && (chunked.push(currentChunk.length == 1 ? currentChunk[0] : _TextNode.from(currentChunk, currentLen)), currentLen = -1, currentLines = currentChunk.length = 0) } for (let child of children) add2(child); return flush(), chunked.length == 1 ? chunked[0] : new _TextNode(chunked, length) } +}; Text.empty = new TextLeaf([""], 0); function textLength(text) { let length = -1; for (let line of text) length += line.length + 1; return length } function appendText(text, target, from = 0, to = 1e9) { for (let pos = 0, i2 = 0, first = !0; i2 < text.length && pos <= to; i2++) { let line = text[i2], end = pos + line.length; end >= from && (end > to && (line = line.slice(0, to - pos)), pos < from && (line = line.slice(from - pos)), first ? (target[target.length - 1] += line, first = !1) : target.push(line)), pos = end + 1 } return target } function sliceText(text, from, to) { return appendText(text, [""], from, to) } var RawTextCursor = class { + constructor(text, dir = 1) { this.dir = dir; this.nodes = [text], this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children.length) << 1] } dir; done = !1; lineBreak = !1; value = ""; nodes; offsets; nextInner(skip, dir) { + for (this.done = this.lineBreak = !1; ;) { + let last = this.nodes.length - 1, top2 = this.nodes[last], offsetValue = this.offsets[last], offset = offsetValue >> 1, size = top2 instanceof TextLeaf ? top2.text.length : top2.children.length; if (offset == (dir > 0 ? size : 0)) { if (last == 0) return this.done = !0, this.value = "", this; dir > 0 && this.offsets[last - 1]++, this.nodes.pop(), this.offsets.pop() } else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) { + if (this.offsets[last] += dir, skip == 0) return this.lineBreak = !0, this.value = ` +`, this; skip-- + } else if (top2 instanceof TextLeaf) { let next = top2.text[offset + (dir < 0 ? -1 : 0)]; if (this.offsets[last] += dir, next.length > Math.max(0, skip)) return this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip), this; skip -= next.length } else { let next = top2.children[offset + (dir < 0 ? -1 : 0)]; skip > next.length ? (skip -= next.length, this.offsets[last] += dir) : (dir < 0 && this.offsets[last]--, this.nodes.push(next), this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1)) } + } + } next(skip = 0) { return skip < 0 && (this.nextInner(-skip, -this.dir), skip = this.value.length), this.nextInner(skip, this.dir) } +}, PartialTextCursor = class { cursor; value = ""; pos; from; to; done = !1; constructor(text, start, end) { this.cursor = new RawTextCursor(text, start > end ? -1 : 1), this.pos = start > end ? text.length : 0, this.from = Math.min(start, end), this.to = Math.max(start, end) } nextInner(skip, dir) { if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) return this.value = "", this.done = !0, this; skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos); let limit = dir < 0 ? this.pos - this.from : this.to - this.pos; skip > limit && (skip = limit), limit -= skip; let { value } = this.cursor.next(skip); return this.pos += (value.length + skip) * dir, this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit), this.done = !this.value, this } next(skip = 0) { return skip < 0 ? skip = Math.max(skip, this.from - this.pos) : skip > 0 && (skip = Math.min(skip, this.to - this.pos)), this.nextInner(skip, this.cursor.dir) } get lineBreak() { return this.cursor.lineBreak && this.value != "" } }, LineCursor = class { constructor(inner) { this.inner = inner } inner; afterBreak = !0; value = ""; done = !1; next(skip = 0) { let { done, lineBreak, value } = this.inner.next(skip); return done && this.afterBreak ? (this.value = "", this.afterBreak = !1) : done ? (this.done = !0, this.value = "") : lineBreak ? this.afterBreak ? this.value = "" : (this.afterBreak = !0, this.next()) : (this.value = value, this.afterBreak = !1), this } get lineBreak() { return !1 } }; typeof Symbol < "u" && (Text.prototype[Symbol.iterator] = function () { return this.iter() }, RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] = LineCursor.prototype[Symbol.iterator] = function () { return this }); var Line = class { constructor(from, to, number2, text) { this.from = from; this.to = to; this.number = number2; this.text = text } from; to; number; text; get length() { return this.to - this.from } }; function clip(text, from, to) { return from = Math.max(0, Math.min(text.length, from)), [from, Math.max(from, Math.min(text.length, to))] } var rangeFrom = [], rangeTo = []; (() => { let numbers = "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(s => s ? parseInt(s, 36) : 1); for (let i2 = 0, n = 0; i2 < numbers.length; i2++)(i2 % 2 ? rangeTo : rangeFrom).push(n = n + numbers[i2]) })(); function isExtendingChar(code2) { if (code2 < 768) return !1; for (let from = 0, to = rangeFrom.length; ;) { let mid = from + to >> 1; if (code2 < rangeFrom[mid]) to = mid; else if (code2 >= rangeTo[mid]) from = mid + 1; else return !0; if (from == to) return !1 } } function isRegionalIndicator(code2) { return code2 >= 127462 && code2 <= 127487 } var ZWJ = 8205; function findClusterBreak(str, pos, forward = !0, includeExtending = !0) { return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending) } function nextClusterBreak(str, pos, includeExtending) { if (pos == str.length) return pos; pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1)) && pos--; let prev = codePointAt(str, pos); for (pos += codePointSize(prev); pos < str.length;) { let next = codePointAt(str, pos); if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) pos += codePointSize(next), prev = next; else if (isRegionalIndicator(next)) { let countBefore = 0, i2 = pos - 2; for (; i2 >= 0 && isRegionalIndicator(codePointAt(str, i2));)countBefore++, i2 -= 2; if (countBefore % 2 == 0) break; pos += 2 } else break } return pos } function prevClusterBreak(str, pos, includeExtending) { for (; pos > 1;) { let found = nextClusterBreak(str, pos - 2, includeExtending); if (found < pos) return found; pos-- } return 0 } function codePointAt(str, pos) { let code0 = str.charCodeAt(pos); if (!surrogateHigh(code0) || pos + 1 == str.length) return code0; let code1 = str.charCodeAt(pos + 1); return surrogateLow(code1) ? (code0 - 55296 << 10) + (code1 - 56320) + 65536 : code0 } function surrogateLow(ch) { return ch >= 56320 && ch < 57344 } function surrogateHigh(ch) { return ch >= 55296 && ch < 56320 } function codePointSize(code2) { return code2 < 65536 ? 1 : 2 } function findClusterBreak2(str, pos, forward = !0, includeExtending = !0) { return findClusterBreak(str, pos, forward, includeExtending) } function surrogateLow2(ch) { return ch >= 56320 && ch < 57344 } function surrogateHigh2(ch) { return ch >= 55296 && ch < 56320 } function codePointAt2(str, pos) { let code0 = str.charCodeAt(pos); if (!surrogateHigh2(code0) || pos + 1 == str.length) return code0; let code1 = str.charCodeAt(pos + 1); return surrogateLow2(code1) ? (code0 - 55296 << 10) + (code1 - 56320) + 65536 : code0 } function fromCodePoint(code2) { return code2 <= 65535 ? String.fromCharCode(code2) : (code2 -= 65536, String.fromCharCode((code2 >> 10) + 55296, (code2 & 1023) + 56320)) } function codePointSize2(code2) { return code2 < 65536 ? 1 : 2 } var DefaultSplit = /\r\n?|\n/, MapMode = (MapMode2 => (MapMode2[MapMode2.Simple = 0] = "Simple", MapMode2[MapMode2.TrackDel = 1] = "TrackDel", MapMode2[MapMode2.TrackBefore = 2] = "TrackBefore", MapMode2[MapMode2.TrackAfter = 3] = "TrackAfter", MapMode2))(MapMode || {}), ChangeDesc = class _ChangeDesc { constructor(sections) { this.sections = sections } sections; get length() { let result = 0; for (let i2 = 0; i2 < this.sections.length; i2 += 2)result += this.sections[i2]; return result } get newLength() { let result = 0; for (let i2 = 0; i2 < this.sections.length; i2 += 2) { let ins = this.sections[i2 + 1]; result += ins < 0 ? this.sections[i2] : ins } return result } get empty() { return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0 } iterGaps(f) { for (let i2 = 0, posA = 0, posB = 0; i2 < this.sections.length;) { let len = this.sections[i2++], ins = this.sections[i2++]; ins < 0 ? (f(posA, posB, len), posB += len) : posB += ins, posA += len } } iterChangedRanges(f, individual = !1) { iterChanges(this, f, individual) } get invertedDesc() { let sections = []; for (let i2 = 0; i2 < this.sections.length;) { let len = this.sections[i2++], ins = this.sections[i2++]; ins < 0 ? sections.push(len, ins) : sections.push(ins, len) } return new _ChangeDesc(sections) } composeDesc(other) { return this.empty ? other : other.empty ? this : composeSets(this, other) } mapDesc(other, before = !1) { return other.empty ? this : mapSet(this, other, before) } mapPos(pos, assoc = -1, mode = 0) { let posA = 0, posB = 0; for (let i2 = 0; i2 < this.sections.length;) { let len = this.sections[i2++], ins = this.sections[i2++], endA = posA + len; if (ins < 0) { if (endA > pos) return posB + (pos - posA); posB += len } else { if (mode != 0 && endA >= pos && (mode == 1 && posA < pos && endA > pos || mode == 2 && posA < pos || mode == 3 && endA > pos)) return null; if (endA > pos || endA == pos && assoc < 0 && !len) return pos == posA || assoc < 0 ? posB : posB + ins; posB += ins } posA = endA } if (pos > posA) throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`); return posB } touchesRange(from, to = from) { for (let i2 = 0, pos = 0; i2 < this.sections.length && pos <= to;) { let len = this.sections[i2++], ins = this.sections[i2++], end = pos + len; if (ins >= 0 && pos <= to && end >= from) return pos < from && end > to ? "cover" : !0; pos = end } return !1 } toString() { let result = ""; for (let i2 = 0; i2 < this.sections.length;) { let len = this.sections[i2++], ins = this.sections[i2++]; result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : "") } return result } toJSON() { return this.sections } static fromJSON(json) { if (!Array.isArray(json) || json.length % 2 || json.some(a => typeof a != "number")) throw new RangeError("Invalid JSON representation of ChangeDesc"); return new _ChangeDesc(json) } static create(sections) { return new _ChangeDesc(sections) } }, ChangeSet = class _ChangeSet extends ChangeDesc { constructor(sections, inserted) { super(sections); this.inserted = inserted } inserted; apply(doc2) { if (this.length != doc2.length) throw new RangeError("Applying change set to a document with the wrong length"); return iterChanges(this, (fromA, toA, fromB, _toB, text) => doc2 = doc2.replace(fromB, fromB + (toA - fromA), text), !1), doc2 } mapDesc(other, before = !1) { return mapSet(this, other, before, !0) } invert(doc2) { let sections = this.sections.slice(), inserted = []; for (let i2 = 0, pos = 0; i2 < sections.length; i2 += 2) { let len = sections[i2], ins = sections[i2 + 1]; if (ins >= 0) { sections[i2] = ins, sections[i2 + 1] = len; let index = i2 >> 1; for (; inserted.length < index;)inserted.push(Text.empty); inserted.push(len ? doc2.slice(pos, pos + len) : Text.empty) } pos += len } return new _ChangeSet(sections, inserted) } compose(other) { return this.empty ? other : other.empty ? this : composeSets(this, other, !0) } map(other, before = !1) { return other.empty ? this : mapSet(this, other, before, !0) } iterChanges(f, individual = !1) { iterChanges(this, f, individual) } get desc() { return ChangeDesc.create(this.sections) } filter(ranges) { let resultSections = [], resultInserted = [], filteredSections = [], iter = new SectionIter(this); done: for (let i2 = 0, pos = 0; ;) { let next = i2 == ranges.length ? 1e9 : ranges[i2++]; for (; pos < next || pos == next && iter.len == 0;) { if (iter.done) break done; let len = Math.min(iter.len, next - pos); addSection(filteredSections, len, -1); let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0; addSection(resultSections, len, ins), ins > 0 && addInsert(resultInserted, resultSections, iter.text), iter.forward(len), pos += len } let end = ranges[i2++]; for (; pos < end;) { if (iter.done) break done; let len = Math.min(iter.len, end - pos); addSection(resultSections, len, -1), addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0), iter.forward(len), pos += len } } return { changes: new _ChangeSet(resultSections, resultInserted), filtered: ChangeDesc.create(filteredSections) } } toJSON() { let parts = []; for (let i2 = 0; i2 < this.sections.length; i2 += 2) { let len = this.sections[i2], ins = this.sections[i2 + 1]; ins < 0 ? parts.push(len) : ins == 0 ? parts.push([len]) : parts.push([len].concat(this.inserted[i2 >> 1].toJSON())) } return parts } static of(changes, length, lineSep) { let sections = [], inserted = [], pos = 0, total = null; function flush(force = !1) { if (!force && !sections.length) return; pos < length && addSection(sections, length - pos, -1); let set = new _ChangeSet(sections, inserted); total = total ? total.compose(set.map(total)) : set, sections = [], inserted = [], pos = 0 } function process(spec) { if (Array.isArray(spec)) for (let sub of spec) process(sub); else if (spec instanceof _ChangeSet) { if (spec.length != length) throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`); flush(), total = total ? total.compose(spec.map(total)) : spec } else { let { from, to = from, insert: insert2 } = spec; if (from > to || from < 0 || to > length) throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`); let insText = insert2 ? typeof insert2 == "string" ? Text.of(insert2.split(lineSep || DefaultSplit)) : insert2 : Text.empty, insLen = insText.length; if (from == to && insLen == 0) return; from < pos && flush(), from > pos && addSection(sections, from - pos, -1), addSection(sections, to - from, insLen), addInsert(inserted, sections, insText), pos = to } } return process(changes), flush(!total), total } static empty(length) { return new _ChangeSet(length ? [length, -1] : [], []) } static fromJSON(json) { if (!Array.isArray(json)) throw new RangeError("Invalid JSON representation of ChangeSet"); let sections = [], inserted = []; for (let i2 = 0; i2 < json.length; i2++) { let part = json[i2]; if (typeof part == "number") sections.push(part, -1); else { if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i3) => i3 && typeof e != "string")) throw new RangeError("Invalid JSON representation of ChangeSet"); if (part.length == 1) sections.push(part[0], 0); else { for (; inserted.length < i2;)inserted.push(Text.empty); inserted[i2] = Text.of(part.slice(1)), sections.push(part[0], inserted[i2].length) } } } return new _ChangeSet(sections, inserted) } static createSet(sections, inserted) { return new _ChangeSet(sections, inserted) } }; function addSection(sections, len, ins, forceJoin = !1) { if (len == 0 && ins <= 0) return; let last = sections.length - 2; last >= 0 && ins <= 0 && ins == sections[last + 1] ? sections[last] += len : last >= 0 && len == 0 && sections[last] == 0 ? sections[last + 1] += ins : forceJoin ? (sections[last] += len, sections[last + 1] += ins) : sections.push(len, ins) } function addInsert(values, sections, value) { if (value.length == 0) return; let index = sections.length - 2 >> 1; if (index < values.length) values[values.length - 1] = values[values.length - 1].append(value); else { for (; values.length < index;)values.push(Text.empty); values.push(value) } } function iterChanges(desc, f, individual) { let inserted = desc.inserted; for (let posA = 0, posB = 0, i2 = 0; i2 < desc.sections.length;) { let len = desc.sections[i2++], ins = desc.sections[i2++]; if (ins < 0) posA += len, posB += len; else { let endA = posA, endB = posB, text = Text.empty; for (; endA += len, endB += ins, ins && inserted && (text = text.append(inserted[i2 - 2 >> 1])), !(individual || i2 == desc.sections.length || desc.sections[i2 + 1] < 0);)len = desc.sections[i2++], ins = desc.sections[i2++]; f(posA, endA, posB, endB, text), posA = endA, posB = endB } } } function mapSet(setA, setB, before, mkSet = !1) { let sections = [], insert2 = mkSet ? [] : null, a = new SectionIter(setA), b = new SectionIter(setB); for (let inserted = -1; ;) { if (a.done && b.len || b.done && a.len) throw new Error("Mismatched change set lengths"); if (a.ins == -1 && b.ins == -1) { let len = Math.min(a.len, b.len); addSection(sections, len, -1), a.forward(len), b.forward(len) } else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) { let len = b.len; for (addSection(sections, b.ins, -1); len;) { let piece = Math.min(a.len, len); a.ins >= 0 && inserted < a.i && a.len <= piece && (addSection(sections, 0, a.ins), insert2 && addInsert(insert2, sections, a.text), inserted = a.i), a.forward(piece), len -= piece } b.next() } else if (a.ins >= 0) { let len = 0, left = a.len; for (; left;)if (b.ins == -1) { let piece = Math.min(left, b.len); len += piece, left -= piece, b.forward(piece) } else if (b.ins == 0 && b.len < left) left -= b.len, b.next(); else break; addSection(sections, len, inserted < a.i ? a.ins : 0), insert2 && inserted < a.i && addInsert(insert2, sections, a.text), inserted = a.i, a.forward(a.len - left) } else { if (a.done && b.done) return insert2 ? ChangeSet.createSet(sections, insert2) : ChangeDesc.create(sections); throw new Error("Mismatched change set lengths") } } } function composeSets(setA, setB, mkSet = !1) { let sections = [], insert2 = mkSet ? [] : null, a = new SectionIter(setA), b = new SectionIter(setB); for (let open = !1; ;) { if (a.done && b.done) return insert2 ? ChangeSet.createSet(sections, insert2) : ChangeDesc.create(sections); if (a.ins == 0) addSection(sections, a.len, 0, open), a.next(); else if (b.len == 0 && !b.done) addSection(sections, 0, b.ins, open), insert2 && addInsert(insert2, sections, b.text), b.next(); else { if (a.done || b.done) throw new Error("Mismatched change set lengths"); { let len = Math.min(a.len2, b.len), sectionLen = sections.length; if (a.ins == -1) { let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins; addSection(sections, len, insB, open), insert2 && insB && addInsert(insert2, sections, b.text) } else b.ins == -1 ? (addSection(sections, a.off ? 0 : a.len, len, open), insert2 && addInsert(insert2, sections, a.textBit(len))) : (addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open), insert2 && !b.off && addInsert(insert2, sections, b.text)); open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen), a.forward2(len), b.forward(len) } } } } var SectionIter = class { constructor(set) { this.set = set; this.next() } set; i = 0; next() { let { sections } = this.set; this.i < sections.length ? (this.len = sections[this.i++], this.ins = sections[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 } = this.set, index = this.i - 2 >> 1; return index >= inserted.length ? Text.empty : inserted[index] } textBit(len) { let { inserted } = this.set, index = this.i - 2 >> 1; return index >= inserted.length && !len ? Text.empty : inserted[index].slice(this.off, len == null ? void 0 : this.off + len) } forward(len) { len == this.len ? this.next() : (this.len -= len, this.off += len) } forward2(len) { this.ins == -1 ? this.forward(len) : len == this.ins ? this.next() : (this.ins -= len, this.off += len) } }; var SelectionRange = class _SelectionRange { constructor(from, to, flags) { this.from = from; this.to = to; this.flags = flags } from; to; flags; 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 level = this.flags & 7; return level == 7 ? null : level } get goalColumn() { let value = this.flags >> 6; return value == 16777215 ? void 0 : value } map(change, assoc = -1) { let from, to; return this.empty ? from = to = change.mapPos(this.from, assoc) : (from = change.mapPos(this.from, 1), to = change.mapPos(this.to, -1)), from == this.from && to == this.to ? this : new _SelectionRange(from, to, this.flags) } extend(from, to = from, assoc = 0) { if (from <= this.anchor && to >= this.anchor) return EditorSelection.range(from, to, void 0, void 0, assoc); let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to; return EditorSelection.range(this.anchor, head, void 0, void 0, assoc) } eq(other, includeAssoc = !1) { return this.anchor == other.anchor && this.head == other.head && this.goalColumn == other.goalColumn && (!includeAssoc || !this.empty || this.assoc == other.assoc) } toJSON() { return { anchor: this.anchor, head: this.head } } static fromJSON(json) { if (!json || typeof json.anchor != "number" || typeof json.head != "number") throw new RangeError("Invalid JSON representation for SelectionRange"); return EditorSelection.range(json.anchor, json.head) } static create(from, to, flags) { return new _SelectionRange(from, to, flags) } }, EditorSelection = class _EditorSelection { constructor(ranges, mainIndex) { this.ranges = ranges; this.mainIndex = mainIndex } ranges; mainIndex; map(change, assoc = -1) { return change.empty ? this : _EditorSelection.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex) } eq(other, includeAssoc = !1) { if (this.ranges.length != other.ranges.length || this.mainIndex != other.mainIndex) return !1; for (let i2 = 0; i2 < this.ranges.length; i2++)if (!this.ranges[i2].eq(other.ranges[i2], includeAssoc)) return !1; return !0 } get main() { return this.ranges[this.mainIndex] } asSingle() { return this.ranges.length == 1 ? this : new _EditorSelection([this.main], 0) } addRange(range, main = !0) { return _EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1) } replaceRange(range, which = this.mainIndex) { let ranges = this.ranges.slice(); return ranges[which] = range, _EditorSelection.create(ranges, this.mainIndex) } toJSON() { return { ranges: this.ranges.map(r => r.toJSON()), main: this.mainIndex } } static fromJSON(json) { if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length) throw new RangeError("Invalid JSON representation for EditorSelection"); return new _EditorSelection(json.ranges.map(r => SelectionRange.fromJSON(r)), json.main) } static single(anchor, head = anchor) { return new _EditorSelection([_EditorSelection.range(anchor, head)], 0) } static create(ranges, mainIndex = 0) { if (ranges.length == 0) throw new RangeError("A selection needs at least one range"); for (let pos = 0, i2 = 0; i2 < ranges.length; i2++) { let range = ranges[i2]; if (range.empty ? range.from <= pos : range.from < pos) return _EditorSelection.normalized(ranges.slice(), mainIndex); pos = range.to } return new _EditorSelection(ranges, mainIndex) } static cursor(pos, assoc = 0, bidiLevel, goalColumn) { return SelectionRange.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 8 : 16) | (bidiLevel == null ? 7 : Math.min(6, bidiLevel)) | (goalColumn ?? 16777215) << 6) } static range(anchor, head, goalColumn, bidiLevel, assoc) { let flags = (goalColumn ?? 16777215) << 6 | (bidiLevel == null ? 7 : Math.min(6, bidiLevel)); return !assoc && anchor != head && (assoc = head < anchor ? 1 : -1), head < anchor ? SelectionRange.create(head, anchor, 48 | flags) : SelectionRange.create(anchor, head, (assoc ? assoc < 0 ? 8 : 16 : 0) | flags) } static normalized(ranges, mainIndex = 0) { let main = ranges[mainIndex]; ranges.sort((a, b) => a.from - b.from), mainIndex = ranges.indexOf(main); for (let i2 = 1; i2 < ranges.length; i2++) { let range = ranges[i2], prev = ranges[i2 - 1]; if (range.empty ? range.from <= prev.to : range.from < prev.to) { let from = prev.from, to = Math.max(range.to, prev.to); i2 <= mainIndex && mainIndex--, ranges.splice(--i2, 2, range.anchor > range.head ? _EditorSelection.range(to, from) : _EditorSelection.range(from, to)) } } return new _EditorSelection(ranges, mainIndex) } }; function checkSelection(selection, docLength) { for (let range of selection.ranges) if (range.to > docLength) throw new RangeError("Selection points outside of document") } var nextID = 0, Facet = class _Facet { constructor(combine, compareInput, compare2, isStatic, enables) { this.combine = combine; this.compareInput = compareInput; this.compare = compare2; this.isStatic = isStatic; this.default = combine([]), this.extensions = typeof enables == "function" ? enables(this) : enables } combine; compareInput; compare; isStatic; id = nextID++; default; extensions; get reader() { return this } static define(config = {}) { return new _Facet(config.combine || (a => a), config.compareInput || ((a, b) => a === b), config.compare || (config.combine ? (a, b) => a === b : sameArray), !!config.static, config.enables) } of(value) { return new FacetProvider([], this, 0, value) } compute(deps, get) { if (this.isStatic) throw new Error("Can't compute a static facet"); return new FacetProvider(deps, this, 1, get) } computeN(deps, get) { if (this.isStatic) throw new Error("Can't compute a static facet"); return new FacetProvider(deps, this, 2, get) } from(field, get) { return get || (get = x => x), this.compute([field], state => get(state.field(field))) } }; function sameArray(a, b) { return a == b || a.length == b.length && a.every((e, i2) => e === b[i2]) } var FacetProvider = class { constructor(dependencies, facet, type, value) { this.dependencies = dependencies; this.facet = facet; this.type = type; this.value = value } dependencies; facet; type; value; id = nextID++; dynamicSlot(addresses) { let getter = this.value, compare2 = this.facet.compareInput, id = this.id, idx = addresses[id] >> 1, multi = this.type == 2, depDoc = !1, depSel = !1, depAddrs = []; for (let dep of this.dependencies) dep == "doc" ? depDoc = !0 : dep == "selection" ? depSel = !0 : ((addresses[dep.id] ?? 1) & 1) == 0 && depAddrs.push(addresses[dep.id]); return { create(state) { return state.values[idx] = getter(state), 1 }, update(state, tr) { if (depDoc && tr.docChanged || depSel && (tr.docChanged || tr.selection) || ensureAll(state, depAddrs)) { let newVal = getter(state); if (multi ? !compareArray(newVal, state.values[idx], compare2) : !compare2(newVal, state.values[idx])) return state.values[idx] = newVal, 1 } return 0 }, reconfigure: (state, oldState) => { let newVal, oldAddr = oldState.config.address[id]; if (oldAddr != null) { let oldVal = getAddr(oldState, oldAddr); if (this.dependencies.every(dep => dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) : dep instanceof StateField ? oldState.field(dep, !1) == state.field(dep, !1) : !0) || (multi ? compareArray(newVal = getter(state), oldVal, compare2) : compare2(newVal = getter(state), oldVal))) return state.values[idx] = oldVal, 0 } else newVal = getter(state); return state.values[idx] = newVal, 1 } } } }; function compareArray(a, b, compare2) { if (a.length != b.length) return !1; for (let i2 = 0; i2 < a.length; i2++)if (!compare2(a[i2], b[i2])) return !1; return !0 } function ensureAll(state, addrs) { let changed = !1; for (let addr of addrs) ensureAddr(state, addr) & 1 && (changed = !0); return changed } function dynamicFacetSlot(addresses, facet, providers) { let providerAddrs = providers.map(p => addresses[p.id]), providerTypes = providers.map(p => p.type), dynamic = providerAddrs.filter(p => !(p & 1)), idx = addresses[facet.id] >> 1; function get(state) { let values = []; for (let i2 = 0; i2 < providerAddrs.length; i2++) { let value = getAddr(state, providerAddrs[i2]); if (providerTypes[i2] == 2) for (let val of value) values.push(val); else values.push(value) } return facet.combine(values) } return { create(state) { for (let addr of providerAddrs) ensureAddr(state, addr); return state.values[idx] = get(state), 1 }, update(state, tr) { if (!ensureAll(state, dynamic)) return 0; let value = get(state); return facet.compare(value, state.values[idx]) ? 0 : (state.values[idx] = value, 1) }, reconfigure(state, oldState) { let depChanged = ensureAll(state, providerAddrs), oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet); if (oldProviders && !depChanged && sameArray(providers, oldProviders)) return state.values[idx] = oldValue, 0; let value = get(state); return facet.compare(value, oldValue) ? (state.values[idx] = oldValue, 0) : (state.values[idx] = value, 1) } } } var initField = Facet.define({ static: !0 }), StateField = class _StateField { constructor(id, createF, updateF, compareF, spec) { this.id = id; this.createF = createF; this.updateF = updateF; this.compareF = compareF; this.spec = spec } id; createF; updateF; compareF; spec; provides = void 0; static define(config) { let field = new _StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config); return config.provide && (field.provides = config.provide(field)), field } create(state) { return (state.facet(initField).find(i2 => i2.field == this)?.create || this.createF)(state) } slot(addresses) { let idx = addresses[this.id] >> 1; return { create: state => (state.values[idx] = this.create(state), 1), update: (state, tr) => { let oldVal = state.values[idx], value = this.updateF(oldVal, tr); return this.compareF(oldVal, value) ? 0 : (state.values[idx] = value, 1) }, reconfigure: (state, oldState) => { let init = state.facet(initField), oldInit = oldState.facet(initField), reInit; return (reInit = init.find(i2 => i2.field == this)) && reInit != oldInit.find(i2 => i2.field == this) ? (state.values[idx] = reInit.create(state), 1) : oldState.config.address[this.id] != null ? (state.values[idx] = oldState.field(this), 0) : (state.values[idx] = this.create(state), 1) } } } init(create) { return [this, initField.of({ field: this, create })] } get extension() { return this } }, Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 }; function prec(value) { return ext => new PrecExtension(ext, value) } var Prec = { highest: prec(Prec_.highest), high: prec(Prec_.high), default: prec(Prec_.default), low: prec(Prec_.low), lowest: prec(Prec_.lowest) }, PrecExtension = class { constructor(inner, prec2) { this.inner = inner; this.prec = prec2 } inner; prec }, Compartment = class _Compartment { of(ext) { return new CompartmentInstance(this, ext) } reconfigure(content2) { return _Compartment.reconfigure.of({ compartment: this, extension: content2 }) } get(state) { return state.config.compartments.get(this) } static reconfigure }, CompartmentInstance = class { constructor(compartment, inner) { this.compartment = compartment; this.inner = inner } compartment; inner }, Configuration = class _Configuration { constructor(base2, compartments, dynamicSlots, address, staticValues, facets) { this.base = base2; this.compartments = compartments; this.dynamicSlots = dynamicSlots; this.address = address; this.staticValues = staticValues; this.facets = facets; for (; this.statusTemplate.length < dynamicSlots.length;)this.statusTemplate.push(0) } base; compartments; dynamicSlots; address; staticValues; facets; statusTemplate = []; staticFacet(facet) { let addr = this.address[facet.id]; return addr == null ? facet.default : this.staticValues[addr >> 1] } static resolve(base2, compartments, oldState) { let fields = [], facets = Object.create(null), newCompartments = new Map; for (let ext of flatten(base2, compartments, newCompartments)) ext instanceof StateField ? fields.push(ext) : (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext); let address = Object.create(null), staticValues = [], dynamicSlots = []; for (let field of fields) address[field.id] = dynamicSlots.length << 1, dynamicSlots.push(a => field.slot(a)); let oldFacets = oldState?.config.facets; for (let id in facets) { let providers = facets[id], facet = providers[0].facet, oldProviders = oldFacets && oldFacets[id] || []; if (providers.every(p => p.type == 0)) if (address[facet.id] = staticValues.length << 1 | 1, sameArray(oldProviders, providers)) staticValues.push(oldState.facet(facet)); else { let value = facet.combine(providers.map(p => p.value)); staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value) } else { for (let p of providers) p.type == 0 ? (address[p.id] = staticValues.length << 1 | 1, staticValues.push(p.value)) : (address[p.id] = dynamicSlots.length << 1, dynamicSlots.push(a => p.dynamicSlot(a))); address[facet.id] = dynamicSlots.length << 1, dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers)) } } let dynamic = dynamicSlots.map(f => f(address)); return new _Configuration(base2, newCompartments, dynamic, address, staticValues, facets) } }; function flatten(extension, compartments, newCompartments) { let result = [[], [], [], [], []], seen = new Map; function inner(ext, prec2) { let known = seen.get(ext); if (known != null) { if (known <= prec2) return; let found = result[known].indexOf(ext); found > -1 && result[known].splice(found, 1), ext instanceof CompartmentInstance && newCompartments.delete(ext.compartment) } if (seen.set(ext, prec2), Array.isArray(ext)) for (let e of ext) inner(e, prec2); else if (ext instanceof CompartmentInstance) { if (newCompartments.has(ext.compartment)) throw new RangeError("Duplicate use of compartment in extensions"); let content2 = compartments.get(ext.compartment) || ext.inner; newCompartments.set(ext.compartment, content2), inner(content2, prec2) } else if (ext instanceof PrecExtension) inner(ext.inner, ext.prec); else if (ext instanceof StateField) result[prec2].push(ext), ext.provides && inner(ext.provides, prec2); else if (ext instanceof FacetProvider) result[prec2].push(ext), ext.facet.extensions && inner(ext.facet.extensions, Prec_.default); else { let content2 = ext.extension; if (!content2) throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`); inner(content2, prec2) } } return inner(extension, Prec_.default), result.reduce((a, b) => a.concat(b)) } function ensureAddr(state, addr) { if (addr & 1) return 2; let idx = addr >> 1, status = state.status[idx]; if (status == 4) throw new Error("Cyclic dependency between fields and/or facets"); if (status & 2) return status; state.status[idx] = 4; let changed = state.computeSlot(state, state.config.dynamicSlots[idx]); return state.status[idx] = 2 | changed } function getAddr(state, addr) { return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1] } var languageData = Facet.define(), allowMultipleSelections = Facet.define({ combine: values => values.some(v => v), static: !0 }), lineSeparator = Facet.define({ combine: values => values.length ? values[0] : void 0, static: !0 }), changeFilter = Facet.define(), transactionFilter = Facet.define(), transactionExtender = Facet.define(), readOnly = Facet.define({ combine: values => values.length ? values[0] : !1 }); var Annotation = class { constructor(type, value) { this.type = type; this.value = value } type; value; static define() { return new AnnotationType } }, AnnotationType = class { of(value) { return new Annotation(this, value) } }, StateEffectType = class { constructor(map) { this.map = map } map; of(value) { return new StateEffect(this, value) } }, StateEffect = class _StateEffect { constructor(type, value) { this.type = type; this.value = value } type; value; map(mapping) { let mapped = this.type.map(this.value, mapping); return mapped === void 0 ? void 0 : mapped == this.value ? this : new _StateEffect(this.type, mapped) } is(type) { return this.type == type } static define(spec = {}) { return new StateEffectType(spec.map || (v => v)) } static mapEffects(effects, mapping) { if (!effects.length) return effects; let result = []; for (let effect of effects) { let mapped = effect.map(mapping); mapped && result.push(mapped) } return result } static reconfigure = _StateEffect.define(); static appendConfig = _StateEffect.define() }, Transaction = class _Transaction { constructor(startState, changes, selection, effects, annotations, scrollIntoView2) { this.startState = startState; this.changes = changes; this.selection = selection; this.effects = effects; this.annotations = annotations; this.scrollIntoView = scrollIntoView2; selection && checkSelection(selection, changes.newLength), annotations.some(a => a.type == _Transaction.time) || (this.annotations = annotations.concat(_Transaction.time.of(Date.now()))) } startState; changes; selection; effects; annotations; scrollIntoView; _doc = null; _state = null; static create(startState, changes, selection, effects, annotations, scrollIntoView2) { return new _Transaction(startState, changes, selection, effects, annotations, scrollIntoView2) } 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(type) { for (let ann of this.annotations) if (ann.type == type) return ann.value } get docChanged() { return !this.changes.empty } get reconfigured() { return this.startState.config != this.state.config } isUserEvent(event) { let e = this.annotation(_Transaction.userEvent); return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == ".")) } static time = Annotation.define(); static userEvent = Annotation.define(); static addToHistory = Annotation.define(); static remote = Annotation.define() }; function joinRanges(a, b) { let result = []; for (let iA = 0, iB = 0; ;) { let from, to; if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) from = a[iA++], to = a[iA++]; else if (iB < b.length) from = b[iB++], to = b[iB++]; else return result; !result.length || result[result.length - 1] < from ? result.push(from, to) : result[result.length - 1] < to && (result[result.length - 1] = to) } } function mergeTransaction(a, b, sequential) { let mapForA, mapForB, changes; return sequential ? (mapForA = b.changes, mapForB = ChangeSet.empty(b.changes.length), changes = a.changes.compose(b.changes)) : (mapForA = b.changes.map(a.changes), mapForB = a.changes.mapDesc(b.changes, !0), changes = a.changes.compose(mapForA)), { changes, selection: b.selection ? b.selection.map(mapForB) : a.selection?.map(mapForA), effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)), annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations, scrollIntoView: a.scrollIntoView || b.scrollIntoView } } function resolveTransactionInner(state, spec, docSize) { let sel = spec.selection, annotations = asArray(spec.annotations); return spec.userEvent && (annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent))), { changes: spec.changes instanceof ChangeSet ? spec.changes : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)), selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)), effects: asArray(spec.effects), annotations, scrollIntoView: !!spec.scrollIntoView } } function resolveTransaction(state, specs, filter) { let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length); specs.length && specs[0].filter === !1 && (filter = !1); for (let i2 = 1; i2 < specs.length; i2++) { specs[i2].filter === !1 && (filter = !1); let seq = !!specs[i2].sequential; s = mergeTransaction(s, resolveTransactionInner(state, specs[i2], seq ? s.changes.newLength : state.doc.length), seq) } let tr = Transaction.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView); return extendTransaction(filter ? filterTransaction(tr) : tr) } function filterTransaction(tr) { let state = tr.startState, result = !0; for (let filter of state.facet(changeFilter)) { let value = filter(tr); if (value === !1) { result = !1; break } Array.isArray(value) && (result = result === !0 ? value : joinRanges(result, value)) } if (result !== !0) { let changes, back; if (result === !1) back = tr.changes.invertedDesc, changes = ChangeSet.empty(state.doc.length); else { let filtered = tr.changes.filter(result); changes = filtered.changes, back = filtered.filtered.mapDesc(filtered.changes).invertedDesc } tr = Transaction.create(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView) } let filters = state.facet(transactionFilter); for (let i2 = filters.length - 1; i2 >= 0; i2--) { let filtered = filters[i2](tr); filtered instanceof Transaction ? tr = filtered : Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction ? tr = filtered[0] : tr = resolveTransaction(state, asArray(filtered), !1) } return tr } function extendTransaction(tr) { let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr; for (let i2 = extenders.length - 1; i2 >= 0; i2--) { let extension = extenders[i2](tr); extension && Object.keys(extension).length && (spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr.changes.newLength), !0)) } return spec == tr ? tr : Transaction.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView) } var none = []; function asArray(value) { return value == null ? none : Array.isArray(value) ? value : [value] } var CharCategory = (CharCategory2 => (CharCategory2[CharCategory2.Word = 0] = "Word", CharCategory2[CharCategory2.Space = 1] = "Space", CharCategory2[CharCategory2.Other = 2] = "Other", CharCategory2))(CharCategory || {}), nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/, wordChar; try { wordChar = new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u") } catch { } function hasWordChar(str) { if (wordChar) return wordChar.test(str); for (let i2 = 0; i2 < str.length; i2++) { let ch = str[i2]; if (/\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))) return !0 } return !1 } function makeCategorizer(wordChars) { return char => { if (!/\S/.test(char)) return 1; if (hasWordChar(char)) return 0; for (let i2 = 0; i2 < wordChars.length; i2++)if (char.indexOf(wordChars[i2]) > -1) return 0; return 2 } } var EditorState = class _EditorState { + constructor(config, doc2, selection, values, computeSlot, tr) { this.config = config; this.doc = doc2; this.selection = selection; this.values = values; this.status = config.statusTemplate.slice(), this.computeSlot = computeSlot, tr && (tr._state = this); for (let i2 = 0; i2 < this.config.dynamicSlots.length; i2++)ensureAddr(this, i2 << 1); this.computeSlot = null } config; doc; selection; values; status; computeSlot; field(field, require2 = !0) { let addr = this.config.address[field.id]; if (addr == null) { if (require2) throw new RangeError("Field is not present in this state"); return } return ensureAddr(this, addr), getAddr(this, addr) } update(...specs) { return resolveTransaction(this, specs, !0) } applyTransaction(tr) { let conf = this.config, { base: base2, compartments } = conf; for (let effect of tr.effects) effect.is(Compartment.reconfigure) ? (conf && (compartments = new Map, conf.compartments.forEach((val, key) => compartments.set(key, val)), conf = null), compartments.set(effect.value.compartment, effect.value.extension)) : effect.is(StateEffect.reconfigure) ? (conf = null, base2 = effect.value) : effect.is(StateEffect.appendConfig) && (conf = null, base2 = asArray(base2).concat(effect.value)); let startValues; conf ? startValues = tr.startState.values.slice() : (conf = Configuration.resolve(base2, compartments, this), startValues = new _EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null).values); let selection = tr.startState.facet(allowMultipleSelections) ? tr.newSelection : tr.newSelection.asSingle(); new _EditorState(conf, tr.newDoc, selection, startValues, (state, slot) => slot.update(state, tr), tr) } replaceSelection(text) { return typeof text == "string" && (text = this.toText(text)), this.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: text }, range: EditorSelection.cursor(range.from + text.length) })) } changeByRange(f) { let sel = this.selection, result1 = f(sel.ranges[0]), changes = this.changes(result1.changes), ranges = [result1.range], effects = asArray(result1.effects); for (let i2 = 1; i2 < sel.ranges.length; i2++) { let result = f(sel.ranges[i2]), newChanges = this.changes(result.changes), newMapped = newChanges.map(changes); for (let j = 0; j < i2; j++)ranges[j] = ranges[j].map(newMapped); let mapBy = changes.mapDesc(newChanges, !0); ranges.push(result.range.map(mapBy)), changes = changes.compose(newMapped), effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray(result.effects), mapBy)) } return { changes, selection: EditorSelection.create(ranges, sel.mainIndex), effects } } changes(spec = []) { return spec instanceof ChangeSet ? spec : ChangeSet.of(spec, this.doc.length, this.facet(_EditorState.lineSeparator)) } toText(string2) { return Text.of(string2.split(this.facet(_EditorState.lineSeparator) || DefaultSplit)) } sliceDoc(from = 0, to = this.doc.length) { return this.doc.sliceString(from, to, this.lineBreak) } facet(facet) { let addr = this.config.address[facet.id]; return addr == null ? facet.default : (ensureAddr(this, addr), getAddr(this, addr)) } toJSON(fields) { let result = { doc: this.sliceDoc(), selection: this.selection.toJSON() }; if (fields) for (let prop in fields) { let value = fields[prop]; value instanceof StateField && this.config.address[value.id] != null && (result[prop] = value.spec.toJSON(this.field(fields[prop]), this)) } return result } static fromJSON(json, config = {}, fields) { if (!json || typeof json.doc != "string") throw new RangeError("Invalid JSON representation for EditorState"); let fieldInit = []; if (fields) { for (let prop in fields) if (Object.prototype.hasOwnProperty.call(json, prop)) { let field = fields[prop], value = json[prop]; fieldInit.push(field.init(state => field.spec.fromJSON(value, state))) } } return _EditorState.create({ doc: json.doc, selection: EditorSelection.fromJSON(json.selection), extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit }) } static create(config = {}) { let configuration = Configuration.resolve(config.extensions || [], new Map), doc2 = config.doc instanceof Text ? config.doc : Text.of((config.doc || "").split(configuration.staticFacet(_EditorState.lineSeparator) || DefaultSplit)), selection = config.selection ? config.selection instanceof EditorSelection ? config.selection : EditorSelection.single(config.selection.anchor, config.selection.head) : EditorSelection.single(0); return checkSelection(selection, doc2.length), configuration.staticFacet(allowMultipleSelections) || (selection = selection.asSingle()), new _EditorState(configuration, doc2, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null) } static allowMultipleSelections = allowMultipleSelections; static tabSize = Facet.define({ combine: values => values.length ? values[0] : 4 }); get tabSize() { return this.facet(_EditorState.tabSize) } static lineSeparator = lineSeparator; get lineBreak() { + return this.facet(_EditorState.lineSeparator) || ` +`} static readOnly = readOnly; get readOnly() { return this.facet(readOnly) } static phrases = Facet.define({ compare(a, b) { let kA = Object.keys(a), kB = Object.keys(b); return kA.length == kB.length && kA.every(k => a[k] == b[k]) } }); phrase(phrase2, ...insert2) { for (let map of this.facet(_EditorState.phrases)) if (Object.prototype.hasOwnProperty.call(map, phrase2)) { phrase2 = map[phrase2]; break } return insert2.length && (phrase2 = phrase2.replace(/\$(\$|\d*)/g, (m, i2) => { if (i2 == "$") return "$"; let n = +(i2 || 1); return !n || n > insert2.length ? m : insert2[n - 1] })), phrase2 } static languageData = languageData; languageDataAt(name2, pos, side = -1) { let values = []; for (let provider of this.facet(languageData)) for (let result of provider(this, pos, side)) Object.prototype.hasOwnProperty.call(result, name2) && values.push(result[name2]); return values } charCategorizer(at) { let chars = this.languageDataAt("wordChars", at); return makeCategorizer(chars.length ? chars[0] : "") } wordAt(pos) { let { text, from, length } = this.doc.lineAt(pos), cat = this.charCategorizer(pos), start = pos - from, end = pos - from; for (; start > 0;) { let prev = findClusterBreak2(text, start, !1); if (cat(text.slice(prev, start)) != 0) break; start = prev } for (; end < length;) { let next = findClusterBreak2(text, end); if (cat(text.slice(end, next)) != 0) break; end = next } return start == end ? null : EditorSelection.range(start + from, end + from) } static changeFilter = changeFilter; static transactionFilter = transactionFilter; static transactionExtender = transactionExtender +}; Compartment.reconfigure = StateEffect.define(); function combineConfig(configs, defaults2, combine = {}) { let result = {}; for (let config of configs) for (let key of Object.keys(config)) { let value = config[key], current = result[key]; if (current === void 0) result[key] = value; else if (!(current === value || value === void 0)) if (Object.hasOwnProperty.call(combine, key)) result[key] = combine[key](current, value); else throw new Error("Config merge conflict for field " + key) } for (let key in defaults2) result[key] === void 0 && (result[key] = defaults2[key]); return result } var RangeValue = class { eq(other) { return this == other } range(from, to = from) { return Range.create(from, to, this) } }; RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0; RangeValue.prototype.point = !1; RangeValue.prototype.mapMode = 1; function cmpVal(a, b) { return a == b || a.constructor == b.constructor && a.eq(b) } var Range = class _Range { constructor(from, to, value) { this.from = from; this.to = to; this.value = value } from; to; value; static create(from, to, value) { return new _Range(from, to, value) } }; function cmpRange(a, b) { return a.from - b.from || a.value.startSide - b.value.startSide } var Chunk = class _Chunk { constructor(from, to, value, maxPoint) { this.from = from; this.to = to; this.value = value; this.maxPoint = maxPoint } from; to; value; maxPoint; get length() { return this.to[this.to.length - 1] } findIndex(pos, side, end, startAt = 0) { let arr = end ? this.to : this.from; for (let lo = startAt, hi = arr.length; ;) { if (lo == hi) return lo; let mid = lo + hi >> 1, diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side; if (mid == lo) return diff >= 0 ? lo : hi; diff >= 0 ? hi = mid : lo = mid + 1 } } between(offset, from, to, f) { for (let i2 = this.findIndex(from, -1e9, !0), e = this.findIndex(to, 1e9, !1, i2); i2 < e; i2++)if (f(this.from[i2] + offset, this.to[i2] + offset, this.value[i2]) === !1) return !1 } map(offset, changes) { let value = [], from = [], to = [], newPos = -1, maxPoint = -1; for (let i2 = 0; i2 < this.value.length; i2++) { let val = this.value[i2], curFrom = this.from[i2] + offset, curTo = this.to[i2] + offset, newFrom, newTo; if (curFrom == curTo) { let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode); if (mapped == null || (newFrom = newTo = mapped, val.startSide != val.endSide && (newTo = changes.mapPos(curFrom, val.endSide), newTo < newFrom))) continue } else if (newFrom = changes.mapPos(curFrom, val.startSide), newTo = changes.mapPos(curTo, val.endSide), newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0) continue; (newTo - newFrom || val.endSide - val.startSide) < 0 || (newPos < 0 && (newPos = newFrom), val.point && (maxPoint = Math.max(maxPoint, newTo - newFrom)), value.push(val), from.push(newFrom - newPos), to.push(newTo - newPos)) } return { mapped: value.length ? new _Chunk(from, to, value, maxPoint) : null, pos: newPos } } }, RangeSet = class _RangeSet { constructor(chunkPos, chunk, nextLayer, maxPoint) { this.chunkPos = chunkPos; this.chunk = chunk; this.nextLayer = nextLayer; this.maxPoint = maxPoint } chunkPos; chunk; nextLayer; maxPoint; static create(chunkPos, chunk, nextLayer, maxPoint) { return new _RangeSet(chunkPos, chunk, nextLayer, maxPoint) } get length() { let last = this.chunk.length - 1; return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length) } get size() { if (this.isEmpty) return 0; let size = this.nextLayer.size; for (let chunk of this.chunk) size += chunk.value.length; return size } chunkEnd(index) { return this.chunkPos[index] + this.chunk[index].length } update(updateSpec) { let { add: add2 = [], sort = !1, filterFrom = 0, filterTo = this.length } = updateSpec, filter = updateSpec.filter; if (add2.length == 0 && !filter) return this; if (sort && (add2 = add2.slice().sort(cmpRange)), this.isEmpty) return add2.length ? _RangeSet.of(add2) : this; let cur = new LayerCursor(this, null, -1).goto(0), i2 = 0, spill = [], builder = new RangeSetBuilder; for (; cur.value || i2 < add2.length;)if (i2 < add2.length && (cur.from - add2[i2].from || cur.startSide - add2[i2].value.startSide) >= 0) { let range = add2[i2++]; builder.addInner(range.from, range.to, range.value) || spill.push(range) } else cur.rangeIndex == 1 && cur.chunkIndex < this.chunk.length && (i2 == add2.length || this.chunkEnd(cur.chunkIndex) < add2[i2].from) && (!filter || filterFrom > this.chunkEnd(cur.chunkIndex) || filterTo < this.chunkPos[cur.chunkIndex]) && builder.addChunk(this.chunkPos[cur.chunkIndex], this.chunk[cur.chunkIndex]) ? cur.nextChunk() : ((!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value)) && (builder.addInner(cur.from, cur.to, cur.value) || spill.push(Range.create(cur.from, cur.to, cur.value))), cur.next()); return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? _RangeSet.empty : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo })) } map(changes) { if (changes.empty || this.isEmpty) return this; let chunks = [], chunkPos = [], maxPoint = -1; for (let i2 = 0; i2 < this.chunk.length; i2++) { let start = this.chunkPos[i2], chunk = this.chunk[i2], touch = changes.touchesRange(start, start + chunk.length); if (touch === !1) maxPoint = Math.max(maxPoint, chunk.maxPoint), chunks.push(chunk), chunkPos.push(changes.mapPos(start)); else if (touch === !0) { let { mapped, pos } = chunk.map(start, changes); mapped && (maxPoint = Math.max(maxPoint, mapped.maxPoint), chunks.push(mapped), chunkPos.push(pos)) } } let next = this.nextLayer.map(changes); return chunks.length == 0 ? next : new _RangeSet(chunkPos, chunks, next || _RangeSet.empty, maxPoint) } between(from, to, f) { if (!this.isEmpty) { for (let i2 = 0; i2 < this.chunk.length; i2++) { let start = this.chunkPos[i2], chunk = this.chunk[i2]; if (to >= start && from <= start + chunk.length && chunk.between(start, from - start, to - start, f) === !1) return } this.nextLayer.between(from, to, f) } } iter(from = 0) { return HeapCursor.from([this]).goto(from) } get isEmpty() { return this.nextLayer == this } static iter(sets, from = 0) { return HeapCursor.from(sets).goto(from) } static compare(oldSets, newSets, textDiff, comparator, minPointSize = -1) { let a = oldSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize), b = newSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize), sharedChunks = findSharedChunks(a, b, textDiff), sideA = new SpanCursor(a, sharedChunks, minPointSize), sideB = new SpanCursor(b, sharedChunks, minPointSize); textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator)), textDiff.empty && textDiff.length == 0 && compare(sideA, 0, sideB, 0, 0, comparator) } static eq(oldSets, newSets, from = 0, to) { to == null && (to = 999999999); let a = oldSets.filter(set => !set.isEmpty && newSets.indexOf(set) < 0), b = newSets.filter(set => !set.isEmpty && oldSets.indexOf(set) < 0); if (a.length != b.length) return !1; if (!a.length) return !0; let sharedChunks = findSharedChunks(a, b), sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from); for (; ;) { if (sideA.to != sideB.to || !sameValues(sideA.active, sideB.active) || sideA.point && (!sideB.point || !cmpVal(sideA.point, sideB.point))) return !1; if (sideA.to > to) return !0; sideA.next(), sideB.next() } } static spans(sets, from, to, iterator, minPointSize = -1) { let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos = from, openRanges = cursor.openStart; for (; ;) { let curTo = Math.min(cursor.to, to); if (cursor.point) { let active = cursor.activeForPoint(cursor.to), openCount = cursor.pointFrom < from ? active.length + 1 : cursor.point.startSide < 0 ? active.length : Math.min(active.length, openRanges); iterator.point(pos, curTo, cursor.point, active, openCount, cursor.pointRank), openRanges = Math.min(cursor.openEnd(curTo), active.length) } else curTo > pos && (iterator.span(pos, curTo, cursor.active, openRanges), openRanges = cursor.openEnd(curTo)); if (cursor.to > to) return openRanges + (cursor.point && cursor.to > to ? 1 : 0); pos = cursor.to, cursor.next() } } static of(ranges, sort = !1) { let build = new RangeSetBuilder; for (let range of ranges instanceof Range ? [ranges] : sort ? lazySort(ranges) : ranges) build.add(range.from, range.to, range.value); return build.finish() } static join(sets) { if (!sets.length) return _RangeSet.empty; let result = sets[sets.length - 1]; for (let i2 = sets.length - 2; i2 >= 0; i2--)for (let layer2 = sets[i2]; layer2 != _RangeSet.empty; layer2 = layer2.nextLayer)result = new _RangeSet(layer2.chunkPos, layer2.chunk, result, Math.max(layer2.maxPoint, result.maxPoint)); return result } static empty = new _RangeSet([], [], null, -1) }; function lazySort(ranges) { if (ranges.length > 1) for (let prev = ranges[0], i2 = 1; i2 < ranges.length; i2++) { let cur = ranges[i2]; if (cmpRange(prev, cur) > 0) return ranges.slice().sort(cmpRange); prev = cur } return ranges } RangeSet.empty.nextLayer = RangeSet.empty; var RangeSetBuilder = class _RangeSetBuilder { chunks = []; chunkPos = []; chunkStart = -1; last = null; lastFrom = -1e9; lastTo = -1e9; from = []; to = []; value = []; maxPoint = -1; setMaxPoint = -1; nextLayer = null; finishChunk(newArrays) { this.chunks.push(new Chunk(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, newArrays && (this.from = [], this.to = [], this.value = []) } constructor() { } add(from, to, value) { this.addInner(from, to, value) || (this.nextLayer || (this.nextLayer = new _RangeSetBuilder)).add(from, to, value) } addInner(from, to, value) { let diff = from - this.lastTo || value.startSide - this.last.endSide; if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0) throw new Error("Ranges must be added sorted by `from` position and `startSide`"); return diff < 0 ? !1 : (this.from.length == 250 && this.finishChunk(!0), this.chunkStart < 0 && (this.chunkStart = from), this.from.push(from - this.chunkStart), this.to.push(to - this.chunkStart), this.last = value, this.lastFrom = from, this.lastTo = to, this.value.push(value), value.point && (this.maxPoint = Math.max(this.maxPoint, to - from)), !0) } addChunk(from, chunk) { if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0) return !1; this.from.length && this.finishChunk(!0), this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint), this.chunks.push(chunk), this.chunkPos.push(from); let last = chunk.value.length - 1; return this.last = chunk.value[last], this.lastFrom = chunk.from[last] + from, this.lastTo = chunk.to[last] + from, !0 } finish() { return this.finishInner(RangeSet.empty) } finishInner(next) { if (this.from.length && this.finishChunk(!1), this.chunks.length == 0) return next; let result = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint); return this.from = null, result } }; function findSharedChunks(a, b, textDiff) { let inA = new Map; for (let set of a) for (let i2 = 0; i2 < set.chunk.length; i2++)set.chunk[i2].maxPoint <= 0 && inA.set(set.chunk[i2], set.chunkPos[i2]); let shared = new Set; for (let set of b) for (let i2 = 0; i2 < set.chunk.length; i2++) { let known = inA.get(set.chunk[i2]); known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i2] && !textDiff?.touchesRange(known, known + set.chunk[i2].length) && shared.add(set.chunk[i2]) } return shared } var LayerCursor = class { constructor(layer2, skip, minPoint, rank = 0) { this.layer = layer2; this.skip = skip; this.minPoint = minPoint; this.rank = rank } layer; skip; minPoint; rank; get startSide() { return this.value ? this.value.startSide : 0 } get endSide() { return this.value ? this.value.endSide : 0 } goto(pos, side = -1e9) { return this.chunkIndex = this.rangeIndex = 0, this.gotoInner(pos, side, !1), this } gotoInner(pos, side, forward) { for (; this.chunkIndex < this.layer.chunk.length;) { let next = this.layer.chunk[this.chunkIndex]; if (!(this.skip && this.skip.has(next) || this.layer.chunkEnd(this.chunkIndex) < pos || next.maxPoint < this.minPoint)) break; this.chunkIndex++, forward = !1 } if (this.chunkIndex < this.layer.chunk.length) { let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, !0); (!forward || this.rangeIndex < rangeIndex) && this.setRangeIndex(rangeIndex) } this.next() } forward(pos, side) { (this.to - pos || this.endSide - side) < 0 && this.gotoInner(pos, side, !0) } next() { for (; ;)if (this.chunkIndex == this.layer.chunk.length) { this.from = this.to = 1e9, this.value = null; break } else { let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex], from = chunkPos + chunk.from[this.rangeIndex]; if (this.from = from, this.to = chunkPos + chunk.to[this.rangeIndex], this.value = chunk.value[this.rangeIndex], this.setRangeIndex(this.rangeIndex + 1), this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint) break } } setRangeIndex(index) { if (index == 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 = index } nextChunk() { this.chunkIndex++, this.rangeIndex = 0, this.next() } compare(other) { return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank || this.to - other.to || this.endSide - other.endSide } }, HeapCursor = class _HeapCursor { constructor(heap) { this.heap = heap } heap; static from(sets, skip = null, minPoint = -1) { let heap = []; for (let i2 = 0; i2 < sets.length; i2++)for (let cur = sets[i2]; !cur.isEmpty; cur = cur.nextLayer)cur.maxPoint >= minPoint && heap.push(new LayerCursor(cur, skip, minPoint, i2)); return heap.length == 1 ? heap[0] : new _HeapCursor(heap) } get startSide() { return this.value ? this.value.startSide : 0 } goto(pos, side = -1e9) { for (let cur of this.heap) cur.goto(pos, side); for (let i2 = this.heap.length >> 1; i2 >= 0; i2--)heapBubble(this.heap, i2); return this.next(), this } forward(pos, side) { for (let cur of this.heap) cur.forward(pos, side); for (let i2 = this.heap.length >> 1; i2 >= 0; i2--)heapBubble(this.heap, i2); (this.to - pos || this.value.endSide - side) < 0 && this.next() } next() { if (this.heap.length == 0) this.from = this.to = 1e9, this.value = null, this.rank = -1; else { let top2 = this.heap[0]; this.from = top2.from, this.to = top2.to, this.value = top2.value, this.rank = top2.rank, top2.value && top2.next(), heapBubble(this.heap, 0) } } }; function heapBubble(heap, index) { for (let cur = heap[index]; ;) { let childIndex = (index << 1) + 1; if (childIndex >= heap.length) break; let child = heap[childIndex]; if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0 && (child = heap[childIndex + 1], childIndex++), cur.compare(child) < 0) break; heap[childIndex] = cur, heap[index] = child, index = childIndex } } var SpanCursor = class { constructor(sets, skip, minPoint) { this.minPoint = minPoint; this.cursor = HeapCursor.from(sets, skip, minPoint) } minPoint; cursor; active = []; activeTo = []; activeRank = []; minActive = -1; point = null; pointFrom = 0; pointRank = 0; to = -1e9; endSide = 0; openStart = -1; goto(pos, side = -1e9) { return this.cursor.goto(pos, side), this.active.length = this.activeTo.length = this.activeRank.length = 0, this.minActive = -1, this.to = pos, this.endSide = side, this.openStart = -1, this.next(), this } forward(pos, side) { for (; this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0;)this.removeActive(this.minActive); this.cursor.forward(pos, side) } removeActive(index) { remove(this.active, index), remove(this.activeTo, index), remove(this.activeRank, index), this.minActive = findMinIndex(this.active, this.activeTo) } addActive(trackOpen) { let i2 = 0, { value, to, rank } = this.cursor; for (; i2 < this.activeRank.length && (rank - this.activeRank[i2] || to - this.activeTo[i2]) > 0;)i2++; insert(this.active, i2, value), insert(this.activeTo, i2, to), insert(this.activeRank, i2, rank), trackOpen && insert(trackOpen, i2, this.cursor.from), this.minActive = findMinIndex(this.active, this.activeTo) } next() { let from = this.to, wasPoint = this.point; this.point = null; let trackOpen = this.openStart < 0 ? [] : null; for (; ;) { let a = this.minActive; if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) { if (this.activeTo[a] > from) { this.to = this.activeTo[a], this.endSide = this.active[a].endSide; break } this.removeActive(a), trackOpen && remove(trackOpen, a) } else if (this.cursor.value) if (this.cursor.from > from) { this.to = this.cursor.from, this.endSide = this.cursor.startSide; break } else { let nextVal = this.cursor.value; if (!nextVal.point) this.addActive(trackOpen), this.cursor.next(); else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) this.cursor.next(); else { this.point = nextVal, this.pointFrom = this.cursor.from, this.pointRank = this.cursor.rank, this.to = this.cursor.to, this.endSide = nextVal.endSide, this.cursor.next(), this.forward(this.to, this.endSide); break } } else { this.to = this.endSide = 1e9; break } } if (trackOpen) { this.openStart = 0; for (let i2 = trackOpen.length - 1; i2 >= 0 && trackOpen[i2] < from; i2--)this.openStart++ } } activeForPoint(to) { if (!this.active.length) return this.active; let active = []; for (let i2 = this.active.length - 1; i2 >= 0 && !(this.activeRank[i2] < this.pointRank); i2--)(this.activeTo[i2] > to || this.activeTo[i2] == to && this.active[i2].endSide >= this.point.endSide) && active.push(this.active[i2]); return active.reverse() } openEnd(to) { let open = 0; for (let i2 = this.activeTo.length - 1; i2 >= 0 && this.activeTo[i2] > to; i2--)open++; return open } }; function compare(a, startA, b, startB, length, comparator) { a.goto(startA), b.goto(startB); let endB = startB + length, pos = startB, dPos = startB - startA, bounds = !!comparator.boundChange; for (let boundChange = !1; ;) { let dEnd = a.to + dPos - b.to, diff = dEnd || a.endSide - b.endSide, end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB); if (a.point || b.point ? (a.point && b.point && cmpVal(a.point, b.point) && sameValues(a.activeForPoint(a.to), b.activeForPoint(b.to)) || comparator.comparePoint(pos, clipEnd, a.point, b.point), boundChange = !1) : (boundChange && comparator.boundChange(pos), clipEnd > pos && !sameValues(a.active, b.active) && comparator.compareRange(pos, clipEnd, a.active, b.active), bounds && clipEnd < endB && (dEnd || a.openEnd(end) != b.openEnd(end)) && (boundChange = !0)), end > endB) break; pos = end, diff <= 0 && a.next(), diff >= 0 && b.next() } } function sameValues(a, b) { if (a.length != b.length) return !1; for (let i2 = 0; i2 < a.length; i2++)if (a[i2] != b[i2] && !cmpVal(a[i2], b[i2])) return !1; return !0 } function remove(array, index) { for (let i2 = index, e = array.length - 1; i2 < e; i2++)array[i2] = array[i2 + 1]; array.pop() } function insert(array, index, value) { for (let i2 = array.length - 1; i2 >= index; i2--)array[i2 + 1] = array[i2]; array[index] = value } function findMinIndex(value, array) { let found = -1, foundPos = 1e9; for (let i2 = 0; i2 < array.length; i2++)(array[i2] - foundPos || value[i2].endSide - value[found].endSide) < 0 && (found = i2, foundPos = array[i2]); return found } function countColumn(string2, tabSize, to = string2.length) { let n = 0; for (let i2 = 0; i2 < to && i2 < string2.length;)string2.charCodeAt(i2) == 9 ? (n += tabSize - n % tabSize, i2++) : (n++, i2 = findClusterBreak2(string2, i2)); return n } function findColumn(string2, col, tabSize, strict) { for (let i2 = 0, n = 0; ;) { if (n >= col) return i2; if (i2 == string2.length) break; n += string2.charCodeAt(i2) == 9 ? tabSize - n % tabSize : 1, i2 = findClusterBreak2(string2, i2) } return strict === !0 ? -1 : string2.length } var COUNT = typeof Symbol > "u" ? "__\u037C" : Symbol.for("\u037C"), SET = typeof Symbol > "u" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet"), top = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : {}, StyleModule = class { + constructor(spec, options) { this.rules = []; let { finish } = options || {}; function splitSelector(selector) { return /^@/.test(selector) ? [selector] : selector.split(/,\s*/) } function render(selectors, spec2, target, isKeyframes) { let local = [], isAt = /^@(\w+)\b/.exec(selectors[0]), keyframes = isAt && isAt[1] == "keyframes"; if (isAt && spec2 == null) return target.push(selectors[0] + ";"); for (let prop in spec2) { let value = spec2[prop]; if (/&/.test(prop)) render(prop.split(/,\s*/).map(part => selectors.map(sel => part.replace(/&/, sel))).reduce((a, b) => a.concat(b)), value, target); else if (value && typeof value == "object") { if (!isAt) throw new RangeError("The value of a property (" + prop + ") should be a primitive value."); render(splitSelector(prop), value, local, keyframes) } else value != null && local.push(prop.replace(/_.*/, "").replace(/[A-Z]/g, l => "-" + l.toLowerCase()) + ": " + value + ";") } (local.length || keyframes) && target.push((finish && !isAt && !isKeyframes ? selectors.map(finish) : selectors).join(", ") + " {" + local.join(" ") + "}") } for (let prop in spec) render(splitSelector(prop), spec[prop], this.rules) } getRules() { + return this.rules.join(` +`) + } static newName() { let id = top[COUNT] || 1; return top[COUNT] = id + 1, "\u037C" + id.toString(36) } static mount(root, modules, options) { let set = root[SET], nonce = options && options.nonce; set ? nonce && set.setNonce(nonce) : set = new StyleSet(root, nonce), set.mount(Array.isArray(modules) ? modules : [modules], root) } +}, adoptedSet = new Map, StyleSet = class { + constructor(root, nonce) { let doc2 = root.ownerDocument || root, win = doc2.defaultView; if (!root.head && root.adoptedStyleSheets && win.CSSStyleSheet) { let adopted = adoptedSet.get(doc2); if (adopted) return root[SET] = adopted; this.sheet = new win.CSSStyleSheet, adoptedSet.set(doc2, this) } else this.styleTag = doc2.createElement("style"), nonce && this.styleTag.setAttribute("nonce", nonce); this.modules = [], root[SET] = this } mount(modules, root) { + let sheet = this.sheet, pos = 0, j = 0; for (let i2 = 0; i2 < modules.length; i2++) { let mod = modules[i2], index = this.modules.indexOf(mod); if (index < j && index > -1 && (this.modules.splice(index, 1), j--, index = -1), index == -1) { if (this.modules.splice(j++, 0, mod), sheet) for (let k = 0; k < mod.rules.length; k++)sheet.insertRule(mod.rules[k], pos++) } else { for (; j < index;)pos += this.modules[j++].rules.length; pos += mod.rules.length, j++ } } if (sheet) root.adoptedStyleSheets.indexOf(this.sheet) < 0 && (root.adoptedStyleSheets = [this.sheet, ...root.adoptedStyleSheets]); else { + let text = ""; for (let i2 = 0; i2 < this.modules.length; i2++)text += this.modules[i2].getRules() + ` +`; this.styleTag.textContent = text; let target = root.head || root; this.styleTag.parentNode != target && target.insertBefore(this.styleTag, target.firstChild) + } + } setNonce(nonce) { this.styleTag && this.styleTag.getAttribute("nonce") != nonce && this.styleTag.setAttribute("nonce", nonce) } +}; var nav = typeof navigator < "u" ? navigator : { userAgent: "", vendor: "", platform: "" }, doc = typeof document < "u" ? document : { documentElement: { style: {} } }, ie_edge = /Edge\/(\d+)/.exec(nav.userAgent), ie_upto10 = /MSIE \d/.test(nav.userAgent), ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(nav.userAgent), ie = !!(ie_upto10 || ie_11up || ie_edge), gecko = !ie && /gecko\/(\d+)/i.test(nav.userAgent), chrome = !ie && /Chrome\/(\d+)/.exec(nav.userAgent), webkit = "webkitFontSmoothing" in doc.documentElement.style, safari = !ie && /Apple Computer/.test(nav.vendor), ios = safari && (/Mobile\/\w+/.test(nav.userAgent) || nav.maxTouchPoints > 2), browser_default = { mac: ios || /Mac/.test(nav.platform), windows: /Win/.test(nav.platform), linux: /Linux|X11/.test(nav.platform), ie, ie_version: ie_upto10 ? doc.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0, gecko, gecko_version: gecko ? +(/Firefox\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0, chrome: !!chrome, chrome_version: chrome ? +chrome[1] : 0, ios, android: /Android\b/.test(nav.userAgent), webkit, webkit_version: webkit ? +(/\bAppleWebKit\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0, safari, safari_version: safari ? +(/\bVersion\/(\d+(\.\d+)?)/.exec(nav.userAgent) || [0, 0])[1] : 0, tabSize: doc.documentElement.style.tabSize != null ? "tab-size" : "-moz-tab-size" }; function combineAttrs(source, target) { for (let name2 in source) name2 == "class" && target.class ? target.class += " " + source.class : name2 == "style" && target.style ? target.style += ";" + source.style : target[name2] = source[name2]; return target } var noAttrs = Object.create(null); function attrsEq(a, b, ignore) { if (a == b) return !0; a || (a = noAttrs), b || (b = noAttrs); let keysA = Object.keys(a), keysB = Object.keys(b); if (keysA.length - (ignore && keysA.indexOf(ignore) > -1 ? 1 : 0) != keysB.length - (ignore && keysB.indexOf(ignore) > -1 ? 1 : 0)) return !1; for (let key of keysA) if (key != ignore && (keysB.indexOf(key) == -1 || a[key] !== b[key])) return !1; return !0 } function setAttrs(dom, attrs) { for (let i2 = dom.attributes.length - 1; i2 >= 0; i2--) { let name2 = dom.attributes[i2].name; attrs[name2] == null && dom.removeAttribute(name2) } for (let name2 in attrs) { let value = attrs[name2]; name2 == "style" ? dom.style.cssText = value : dom.getAttribute(name2) != value && dom.setAttribute(name2, value) } } function updateAttrs(dom, prev, attrs) { let changed = !1; if (prev) for (let name2 in prev) attrs && name2 in attrs || (changed = !0, name2 == "style" ? dom.style.cssText = "" : dom.removeAttribute(name2)); if (attrs) for (let name2 in attrs) prev && prev[name2] == attrs[name2] || (changed = !0, name2 == "style" ? dom.style.cssText = attrs[name2] : dom.setAttribute(name2, attrs[name2])); return changed } function getAttrs(dom) { let attrs = Object.create(null); for (let i2 = 0; i2 < dom.attributes.length; i2++) { let attr = dom.attributes[i2]; attrs[attr.name] = attr.value } return attrs } var WidgetType = class { eq(widget) { return !1 } updateDOM(dom, view, from) { return !1 } compare(other) { return this == other || this.constructor == other.constructor && this.eq(other) } get estimatedHeight() { return -1 } get lineBreaks() { return 0 } ignoreEvent(event) { return !0 } coordsAt(dom, pos, side) { return null } get isHidden() { return !1 } get editable() { return !1 } destroy(dom) { } }; var BlockType = (BlockType2 => (BlockType2[BlockType2.Text = 0] = "Text", BlockType2[BlockType2.WidgetBefore = 1] = "WidgetBefore", BlockType2[BlockType2.WidgetAfter = 2] = "WidgetAfter", BlockType2[BlockType2.WidgetRange = 3] = "WidgetRange", BlockType2))(BlockType || {}), Decoration = class extends RangeValue { constructor(startSide, endSide, widget, spec) { super(); this.startSide = startSide; this.endSide = endSide; this.widget = widget; this.spec = spec } startSide; endSide; widget; spec; get heightRelevant() { return !1 } static mark(spec) { return new MarkDecoration(spec) } static widget(spec) { let side = Math.max(-1e4, Math.min(1e4, spec.side || 0)), block = !!spec.block; return side += block && !spec.inlineOrder ? side > 0 ? 3e8 : -4e8 : side > 0 ? 1e8 : -1e8, new PointDecoration(spec, side, side, block, spec.widget || null, !1) } static replace(spec) { let block = !!spec.block, startSide, endSide; if (spec.isBlockGap) startSide = -5e8, endSide = 4e8; else { let { start, end } = getInclusive(spec, block); startSide = (start ? block ? -3e8 : -1 : 5e8) - 1, endSide = (end ? block ? 2e8 : 1 : -6e8) + 1 } return new PointDecoration(spec, startSide, endSide, block, spec.widget || null, !0) } static line(spec) { return new LineDecoration(spec) } static set(of, sort = !1) { return RangeSet.of(of, sort) } static none = RangeSet.empty; hasHeight() { return this.widget ? this.widget.estimatedHeight > -1 : !1 } }, MarkDecoration = class _MarkDecoration extends Decoration { tagName; attrs; constructor(spec) { let { start, end } = getInclusive(spec); super(start ? -1 : 5e8, end ? 1 : -6e8, null, spec), this.tagName = spec.tagName || "span", this.attrs = spec.class && spec.attributes ? combineAttrs(spec.attributes, { class: spec.class }) : spec.class ? { class: spec.class } : spec.attributes || noAttrs } eq(other) { return this == other || other instanceof _MarkDecoration && this.tagName == other.tagName && attrsEq(this.attrs, other.attrs) } range(from, to = from) { if (from >= to) throw new RangeError("Mark decorations may not be empty"); return super.range(from, to) } }; MarkDecoration.prototype.point = !1; var LineDecoration = class _LineDecoration extends Decoration { constructor(spec) { super(-2e8, -2e8, null, spec) } eq(other) { return other instanceof _LineDecoration && this.spec.class == other.spec.class && attrsEq(this.spec.attributes, other.spec.attributes) } range(from, to = from) { if (to != from) throw new RangeError("Line decoration ranges must be zero-length"); return super.range(from, to) } }; LineDecoration.prototype.mapMode = 2; LineDecoration.prototype.point = !0; var PointDecoration = class _PointDecoration extends Decoration { constructor(spec, startSide, endSide, block, widget, isReplace) { super(startSide, endSide, widget, spec); this.block = block; this.isReplace = isReplace; this.mapMode = block ? startSide <= 0 ? 2 : 3 : 1 } block; isReplace; 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(other) { return other instanceof _PointDecoration && widgetsEq(this.widget, other.widget) && this.block == other.block && this.startSide == other.startSide && this.endSide == other.endSide } range(from, to = from) { if (this.isReplace && (from > to || from == to && this.startSide > 0 && this.endSide <= 0)) throw new RangeError("Invalid range for replacement decoration"); if (!this.isReplace && to != from) throw new RangeError("Widget decorations can only have zero-length ranges"); return super.range(from, to) } }; PointDecoration.prototype.point = !0; function getInclusive(spec, block = !1) { let { inclusiveStart: start, inclusiveEnd: end } = spec; return start == null && (start = spec.inclusive), end == null && (end = spec.inclusive), { start: start ?? block, end: end ?? block } } function widgetsEq(a, b) { return a == b || !!(a && b && a.compare(b)) } function addRange(from, to, ranges, margin = 0) { let last = ranges.length - 1; last >= 0 && ranges[last] + margin >= from ? ranges[last] = Math.max(ranges[last], to) : ranges.push(from, to) } var BlockWrapper = class _BlockWrapper extends RangeValue { constructor(tagName, attributes) { super(); this.tagName = tagName; this.attributes = attributes } tagName; attributes; eq(other) { return other == this || other instanceof _BlockWrapper && this.tagName == other.tagName && attrsEq(this.attributes, other.attributes) } static create(spec) { return new _BlockWrapper(spec.tagName, spec.attributes || noAttrs) } static set(of, sort = !1) { return RangeSet.of(of, sort) } }; BlockWrapper.prototype.startSide = BlockWrapper.prototype.endSide = -1; function getSelection(root) { let target; return root.nodeType == 11 ? target = root.getSelection ? root : root.ownerDocument : target = root, target.getSelection() } function contains(dom, node) { return node ? dom == node || dom.contains(node.nodeType != 1 ? node.parentNode : node) : !1 } function hasSelection(dom, selection) { if (!selection.anchorNode) return !1; try { return contains(dom, selection.anchorNode) } catch { return !1 } } function clientRectsFor(dom) { return dom.nodeType == 3 ? textRange(dom, 0, dom.nodeValue.length).getClientRects() : dom.nodeType == 1 ? dom.getClientRects() : [] } function isEquivalentPosition(node, off, targetNode, targetOff) { return targetNode ? scanFor(node, off, targetNode, targetOff, -1) || scanFor(node, off, targetNode, targetOff, 1) : !1 } function domIndex(node) { for (var index = 0; ; index++)if (node = node.previousSibling, !node) return index } function isBlockElement(node) { return node.nodeType == 1 && /^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node.nodeName) } function scanFor(node, off, targetNode, targetOff, dir) { for (; ;) { if (node == targetNode && off == targetOff) return !0; if (off == (dir < 0 ? 0 : maxOffset(node))) { if (node.nodeName == "DIV") return !1; let parent = node.parentNode; if (!parent || parent.nodeType != 1) return !1; off = domIndex(node) + (dir < 0 ? 0 : 1), node = parent } else if (node.nodeType == 1) { if (node = node.childNodes[off + (dir < 0 ? -1 : 0)], node.nodeType == 1 && node.contentEditable == "false") return !1; off = dir < 0 ? maxOffset(node) : 0 } else return !1 } } function maxOffset(node) { return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length } function flattenRect(rect, left) { let x = left ? rect.left : rect.right; return { left: x, right: x, top: rect.top, bottom: rect.bottom } } function windowRect(win) { let vp = win.visualViewport; return vp ? { left: 0, right: vp.width, top: 0, bottom: vp.height } : { left: 0, right: win.innerWidth, top: 0, bottom: win.innerHeight } } function getScale(elt, rect) { let scaleX = rect.width / elt.offsetWidth, scaleY = rect.height / elt.offsetHeight; return (scaleX > .995 && scaleX < 1.005 || !isFinite(scaleX) || Math.abs(rect.width - elt.offsetWidth) < 1) && (scaleX = 1), (scaleY > .995 && scaleY < 1.005 || !isFinite(scaleY) || Math.abs(rect.height - elt.offsetHeight) < 1) && (scaleY = 1), { scaleX, scaleY } } function scrollRectIntoView(dom, rect, side, x, y, xMargin, yMargin, ltr) { let doc2 = dom.ownerDocument, win = doc2.defaultView || window; for (let cur = dom, stop = !1; cur && !stop;)if (cur.nodeType == 1) { let bounding, top2 = cur == doc2.body, scaleX = 1, scaleY = 1; if (top2) bounding = windowRect(win); else { if (/^(fixed|sticky)$/.test(getComputedStyle(cur).position) && (stop = !0), cur.scrollHeight <= cur.clientHeight && cur.scrollWidth <= cur.clientWidth) { cur = cur.assignedSlot || cur.parentNode; continue } let rect2 = cur.getBoundingClientRect(); ({ scaleX, scaleY } = getScale(cur, rect2)), bounding = { left: rect2.left, right: rect2.left + cur.clientWidth * scaleX, top: rect2.top, bottom: rect2.top + cur.clientHeight * scaleY } } let moveX = 0, moveY = 0; if (y == "nearest") rect.top < bounding.top + yMargin ? (moveY = rect.top - (bounding.top + yMargin), side > 0 && rect.bottom > bounding.bottom + moveY && (moveY = rect.bottom - bounding.bottom + yMargin)) : rect.bottom > bounding.bottom - yMargin && (moveY = rect.bottom - bounding.bottom + yMargin, side < 0 && rect.top - moveY < bounding.top && (moveY = rect.top - (bounding.top + yMargin))); else { let rectHeight = rect.bottom - rect.top, boundingHeight = bounding.bottom - bounding.top; moveY = (y == "center" && rectHeight <= boundingHeight ? rect.top + rectHeight / 2 - boundingHeight / 2 : y == "start" || y == "center" && side < 0 ? rect.top - yMargin : rect.bottom - boundingHeight + yMargin) - bounding.top } if (x == "nearest" ? rect.left < bounding.left + xMargin ? (moveX = rect.left - (bounding.left + xMargin), side > 0 && rect.right > bounding.right + moveX && (moveX = rect.right - bounding.right + xMargin)) : rect.right > bounding.right - xMargin && (moveX = rect.right - bounding.right + xMargin, side < 0 && rect.left < bounding.left + moveX && (moveX = rect.left - (bounding.left + xMargin))) : moveX = (x == "center" ? rect.left + (rect.right - rect.left) / 2 - (bounding.right - bounding.left) / 2 : x == "start" == ltr ? rect.left - xMargin : rect.right - (bounding.right - bounding.left) + xMargin) - bounding.left, moveX || moveY) if (top2) win.scrollBy(moveX, moveY); else { let movedX = 0, movedY = 0; if (moveY) { let start = cur.scrollTop; cur.scrollTop += moveY / scaleY, movedY = (cur.scrollTop - start) * scaleY } if (moveX) { let start = cur.scrollLeft; cur.scrollLeft += moveX / scaleX, movedX = (cur.scrollLeft - start) * scaleX } rect = { left: rect.left - movedX, top: rect.top - movedY, right: rect.right - movedX, bottom: rect.bottom - movedY }, movedX && Math.abs(movedX - moveX) < 1 && (x = "nearest"), movedY && Math.abs(movedY - moveY) < 1 && (y = "nearest") } if (top2) break; (rect.top < bounding.top || rect.bottom > bounding.bottom || rect.left < bounding.left || rect.right > bounding.right) && (rect = { left: Math.max(rect.left, bounding.left), right: Math.min(rect.right, bounding.right), top: Math.max(rect.top, bounding.top), bottom: Math.min(rect.bottom, bounding.bottom) }), cur = cur.assignedSlot || cur.parentNode } else if (cur.nodeType == 11) cur = cur.host; else break } function scrollableParents(dom, getX = !0) { let doc2 = dom.ownerDocument, x = null, y = null; for (let cur = dom.parentNode; cur && !(cur == doc2.body || (!getX || x) && y);)if (cur.nodeType == 1) !y && cur.scrollHeight > cur.clientHeight && (y = cur), getX && !x && cur.scrollWidth > cur.clientWidth && (x = cur), cur = cur.assignedSlot || cur.parentNode; else if (cur.nodeType == 11) cur = cur.host; else break; return { x, y } } var DOMSelectionState = class { anchorNode = null; anchorOffset = 0; focusNode = null; focusOffset = 0; eq(domSel) { return this.anchorNode == domSel.anchorNode && this.anchorOffset == domSel.anchorOffset && this.focusNode == domSel.focusNode && this.focusOffset == domSel.focusOffset } setRange(range) { let { anchorNode, focusNode } = range; this.set(anchorNode, Math.min(range.anchorOffset, anchorNode ? maxOffset(anchorNode) : 0), focusNode, Math.min(range.focusOffset, focusNode ? maxOffset(focusNode) : 0)) } set(anchorNode, anchorOffset, focusNode, focusOffset) { this.anchorNode = anchorNode, this.anchorOffset = anchorOffset, this.focusNode = focusNode, this.focusOffset = focusOffset } }, preventScrollSupported = null; browser_default.safari && browser_default.safari_version >= 26 && (preventScrollSupported = !1); function focusPreventScroll(dom) { if (dom.setActive) return dom.setActive(); if (preventScrollSupported) return dom.focus(preventScrollSupported); let stack = []; for (let cur = dom; cur && (stack.push(cur, cur.scrollTop, cur.scrollLeft), cur != cur.ownerDocument); cur = cur.parentNode); if (dom.focus(preventScrollSupported == null ? { get preventScroll() { return preventScrollSupported = { preventScroll: !0 }, !0 } } : void 0), !preventScrollSupported) { preventScrollSupported = !1; for (let i2 = 0; i2 < stack.length;) { let elt = stack[i2++], top2 = stack[i2++], left = stack[i2++]; elt.scrollTop != top2 && (elt.scrollTop = top2), elt.scrollLeft != left && (elt.scrollLeft = left) } } } var scratchRange; function textRange(node, from, to = from) { let range = scratchRange || (scratchRange = document.createRange()); return range.setEnd(node, to), range.setStart(node, from), range } function dispatchKey(elt, name2, code2, mods) { let options = { key: name2, code: name2, keyCode: code2, which: code2, cancelable: !0 }; mods && ({ altKey: options.altKey, ctrlKey: options.ctrlKey, shiftKey: options.shiftKey, metaKey: options.metaKey } = mods); let down = new KeyboardEvent("keydown", options); down.synthetic = !0, elt.dispatchEvent(down); let up = new KeyboardEvent("keyup", options); return up.synthetic = !0, elt.dispatchEvent(up), down.defaultPrevented || up.defaultPrevented } function getRoot(node) { for (; node;) { if (node && (node.nodeType == 9 || node.nodeType == 11 && node.host)) return node; node = node.assignedSlot || node.parentNode } return null } function atElementStart(doc2, selection) { let node = selection.focusNode, offset = selection.focusOffset; if (!node || selection.anchorNode != node || selection.anchorOffset != offset) return !1; for (offset = Math.min(offset, maxOffset(node)); ;)if (offset) { if (node.nodeType != 1) return !1; let prev = node.childNodes[offset - 1]; prev.contentEditable == "false" ? offset-- : (node = prev, offset = maxOffset(node)) } else { if (node == doc2) return !0; offset = domIndex(node), node = node.parentNode } } function isScrolledToBottom(elt) { return elt instanceof Window ? elt.pageYOffset > Math.max(0, elt.document.documentElement.scrollHeight - elt.innerHeight - 4) : elt.scrollTop > Math.max(1, elt.scrollHeight - elt.clientHeight - 4) } function textNodeBefore(startNode, startOffset) { for (let node = startNode, offset = startOffset; ;) { if (node.nodeType == 3 && offset > 0) return { node, offset }; if (node.nodeType == 1 && offset > 0) { if (node.contentEditable == "false") return null; node = node.childNodes[offset - 1], offset = maxOffset(node) } else if (node.parentNode && !isBlockElement(node)) offset = domIndex(node), node = node.parentNode; else return null } } function textNodeAfter(startNode, startOffset) { for (let node = startNode, offset = startOffset; ;) { if (node.nodeType == 3 && offset < node.nodeValue.length) return { node, offset }; if (node.nodeType == 1 && offset < node.childNodes.length) { if (node.contentEditable == "false") return null; node = node.childNodes[offset], offset = 0 } else if (node.parentNode && !isBlockElement(node)) offset = domIndex(node) + 1, node = node.parentNode; else return null } } var DOMPos = class _DOMPos { constructor(node, offset, precise = !0) { this.node = node; this.offset = offset; this.precise = precise } node; offset; precise; static before(dom, precise) { return new _DOMPos(dom.parentNode, domIndex(dom), precise) } static after(dom, precise) { return new _DOMPos(dom.parentNode, domIndex(dom) + 1, precise) } }; var Direction = (Direction2 => (Direction2[Direction2.LTR = 0] = "LTR", Direction2[Direction2.RTL = 1] = "RTL", Direction2))(Direction || {}), LTR = 0, RTL = 1; function dec(str) { let result = []; for (let i2 = 0; i2 < str.length; i2++)result.push(1 << +str[i2]); return result } var LowTypes = dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008"), ArabicTypes = dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333"), Brackets = Object.create(null), BracketStack = []; for (let p of ["()", "[]", "{}"]) { let l = p.charCodeAt(0), r = p.charCodeAt(1); Brackets[l] = r, Brackets[r] = -l } function charType(ch) { return ch <= 247 ? LowTypes[ch] : 1424 <= ch && ch <= 1524 ? 2 : 1536 <= ch && ch <= 1785 ? ArabicTypes[ch - 1536] : 1774 <= ch && ch <= 2220 ? 4 : 8192 <= ch && ch <= 8204 ? 256 : 64336 <= ch && ch <= 65023 ? 4 : 1 } var BidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/, BidiSpan = class { constructor(from, to, level) { this.from = from; this.to = to; this.level = level } from; to; level; get dir() { return this.level % 2 ? RTL : LTR } side(end, dir) { return this.dir == dir == end ? this.to : this.from } forward(forward, dir) { return forward == (this.dir == dir) } static find(order, index, level, assoc) { let maybe = -1; for (let i2 = 0; i2 < order.length; i2++) { let span = order[i2]; if (span.from <= index && span.to >= index) { if (span.level == level) return i2; (maybe < 0 || (assoc != 0 ? assoc < 0 ? span.from < index : span.to > index : order[maybe].level > span.level)) && (maybe = i2) } } if (maybe < 0) throw new RangeError("Index out of range"); return maybe } }; function isolatesEq(a, b) { if (a.length != b.length) return !1; for (let i2 = 0; i2 < a.length; i2++) { let iA = a[i2], iB = b[i2]; if (iA.from != iB.from || iA.to != iB.to || iA.direction != iB.direction || !isolatesEq(iA.inner, iB.inner)) return !1 } return !0 } var types = []; function computeCharTypes(line, rFrom, rTo, isolates, outerType) { for (let iI = 0; iI <= isolates.length; iI++) { let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo, prevType = iI ? 256 : outerType; for (let i2 = from, prev = prevType, prevStrong = prevType; i2 < to; i2++) { let type = charType(line.charCodeAt(i2)); type == 512 ? type = prev : type == 8 && prevStrong == 4 && (type = 16), types[i2] = type == 4 ? 2 : type, type & 7 && (prevStrong = type), prev = type } for (let i2 = from, prev = prevType, prevStrong = prevType; i2 < to; i2++) { let type = types[i2]; if (type == 128) i2 < to - 1 && prev == types[i2 + 1] && prev & 24 ? type = types[i2] = prev : types[i2] = 256; else if (type == 64) { let end = i2 + 1; for (; end < to && types[end] == 64;)end++; let replace2 = i2 && prev == 8 || end < rTo && types[end] == 8 ? prevStrong == 1 ? 1 : 8 : 256; for (let j = i2; j < end; j++)types[j] = replace2; i2 = end - 1 } else type == 8 && prevStrong == 1 && (types[i2] = 1); prev = type, type & 7 && (prevStrong = type) } } } function processBracketPairs(line, rFrom, rTo, isolates, outerType) { let oppositeType = outerType == 1 ? 2 : 1; for (let iI = 0, sI = 0, context = 0; iI <= isolates.length; iI++) { let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo; for (let i2 = from, ch, br, type; i2 < to; i2++)if (br = Brackets[ch = line.charCodeAt(i2)]) if (br < 0) { for (let sJ = sI - 3; sJ >= 0; sJ -= 3)if (BracketStack[sJ + 1] == -br) { let flags = BracketStack[sJ + 2], type2 = flags & 2 ? outerType : flags & 4 ? flags & 1 ? oppositeType : outerType : 0; type2 && (types[i2] = types[BracketStack[sJ]] = type2), sI = sJ; break } } else { if (BracketStack.length == 189) break; BracketStack[sI++] = i2, BracketStack[sI++] = ch, BracketStack[sI++] = context } else if ((type = types[i2]) == 2 || type == 1) { let embed = type == outerType; context = embed ? 0 : 1; for (let sJ = sI - 3; sJ >= 0; sJ -= 3) { let cur = BracketStack[sJ + 2]; if (cur & 2) break; if (embed) BracketStack[sJ + 2] |= 2; else { if (cur & 4) break; BracketStack[sJ + 2] |= 4 } } } } } function processNeutrals(rFrom, rTo, isolates, outerType) { for (let iI = 0, prev = outerType; iI <= isolates.length; iI++) { let from = iI ? isolates[iI - 1].to : rFrom, to = iI < isolates.length ? isolates[iI].from : rTo; for (let i2 = from; i2 < to;) { let type = types[i2]; if (type == 256) { let end = i2 + 1; for (; ;)if (end == to) { if (iI == isolates.length) break; end = isolates[iI++].to, to = iI < isolates.length ? isolates[iI].from : rTo } else if (types[end] == 256) end++; else break; let beforeL = prev == 1, afterL = (end < rTo ? types[end] : outerType) == 1, replace2 = beforeL == afterL ? beforeL ? 1 : 2 : outerType; for (let j = end, jI = iI, fromJ = jI ? isolates[jI - 1].to : rFrom; j > i2;)j == fromJ && (j = isolates[--jI].from, fromJ = jI ? isolates[jI - 1].to : rFrom), types[--j] = replace2; i2 = end } else prev = type, i2++ } } } function emitSpans(line, from, to, level, baseLevel, isolates, order) { let ourType = level % 2 ? 2 : 1; if (level % 2 == baseLevel % 2) for (let iCh = from, iI = 0; iCh < to;) { let sameDir = !0, isNum = !1; if (iI == isolates.length || iCh < isolates[iI].from) { let next = types[iCh]; next != ourType && (sameDir = !1, isNum = next == 16) } let recurse = !sameDir && ourType == 1 ? [] : null, localLevel = sameDir ? level : level + 1, iScan = iCh; run: for (; ;)if (iI < isolates.length && iScan == isolates[iI].from) { if (isNum) break run; let iso = isolates[iI]; if (!sameDir) for (let upto = iso.to, jI = iI + 1; ;) { if (upto == to) break run; if (jI < isolates.length && isolates[jI].from == upto) upto = isolates[jI++].to; else { if (types[upto] == ourType) break run; break } } if (iI++, recurse) recurse.push(iso); else { iso.from > iCh && order.push(new BidiSpan(iCh, iso.from, localLevel)); let dirSwap = iso.direction == LTR != !(localLevel % 2); computeSectionOrder(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order), iCh = iso.to } iScan = iso.to } else { if (iScan == to || (sameDir ? types[iScan] != ourType : types[iScan] == ourType)) break; iScan++ } recurse ? emitSpans(line, iCh, iScan, level + 1, baseLevel, recurse, order) : iCh < iScan && order.push(new BidiSpan(iCh, iScan, localLevel)), iCh = iScan } else for (let iCh = to, iI = isolates.length; iCh > from;) { let sameDir = !0, isNum = !1; if (!iI || iCh > isolates[iI - 1].to) { let next = types[iCh - 1]; next != ourType && (sameDir = !1, isNum = next == 16) } let recurse = !sameDir && ourType == 1 ? [] : null, localLevel = sameDir ? level : level + 1, iScan = iCh; run: for (; ;)if (iI && iScan == isolates[iI - 1].to) { if (isNum) break run; let iso = isolates[--iI]; if (!sameDir) for (let upto = iso.from, jI = iI; ;) { if (upto == from) break run; if (jI && isolates[jI - 1].to == upto) upto = isolates[--jI].from; else { if (types[upto - 1] == ourType) break run; break } } if (recurse) recurse.push(iso); else { iso.to < iCh && order.push(new BidiSpan(iso.to, iCh, localLevel)); let dirSwap = iso.direction == LTR != !(localLevel % 2); computeSectionOrder(line, dirSwap ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order), iCh = iso.from } iScan = iso.from } else { if (iScan == from || (sameDir ? types[iScan - 1] != ourType : types[iScan - 1] == ourType)) break; iScan-- } recurse ? emitSpans(line, iScan, iCh, level + 1, baseLevel, recurse, order) : iScan < iCh && order.push(new BidiSpan(iScan, iCh, localLevel)), iCh = iScan } } function computeSectionOrder(line, level, baseLevel, isolates, from, to, order) { let outerType = level % 2 ? 2 : 1; computeCharTypes(line, from, to, isolates, outerType), processBracketPairs(line, from, to, isolates, outerType), processNeutrals(from, to, isolates, outerType), emitSpans(line, from, to, level, baseLevel, isolates, order) } function computeOrder(line, direction, isolates) { if (!line) return [new BidiSpan(0, 0, direction == RTL ? 1 : 0)]; if (direction == LTR && !isolates.length && !BidiRE.test(line)) return trivialOrder(line.length); if (isolates.length) for (; line.length > types.length;)types[types.length] = 256; let order = [], level = direction == LTR ? 0 : 1; return computeSectionOrder(line, level, level, isolates, 0, line.length, order), order } function trivialOrder(length) { return [new BidiSpan(0, length, 0)] } var movedOver = ""; function moveVisually(line, order, dir, start, forward) { let startIndex = start.head - line.from, spanI = BidiSpan.find(order, startIndex, start.bidiLevel ?? -1, start.assoc), span = order[spanI], spanEnd = span.side(forward, dir); if (startIndex == spanEnd) { let nextI = spanI += forward ? 1 : -1; if (nextI < 0 || nextI >= order.length) return null; span = order[spanI = nextI], startIndex = span.side(!forward, dir), spanEnd = span.side(forward, dir) } let nextIndex = findClusterBreak2(line.text, startIndex, span.forward(forward, dir)); (nextIndex < span.from || nextIndex > span.to) && (nextIndex = spanEnd), movedOver = line.text.slice(Math.min(startIndex, nextIndex), Math.max(startIndex, nextIndex)); let nextSpan = spanI == (forward ? order.length - 1 : 0) ? null : order[spanI + (forward ? 1 : -1)]; return nextSpan && nextIndex == spanEnd && nextSpan.level + (forward ? 0 : 1) < span.level ? EditorSelection.cursor(nextSpan.side(!forward, dir) + line.from, nextSpan.forward(forward, dir) ? 1 : -1, nextSpan.level) : EditorSelection.cursor(nextIndex + line.from, span.forward(forward, dir) ? -1 : 1, span.level) } function autoDirection(text, from, to) { for (let i2 = from; i2 < to; i2++) { let type = charType(text.charCodeAt(i2)); if (type == 1) return LTR; if (type == 2 || type == 4) return RTL } return LTR } var clickAddsSelectionRange = Facet.define(), dragMovesSelection = Facet.define(), mouseSelectionStyle = Facet.define(), exceptionSink = Facet.define(), updateListener = Facet.define(), inputHandler = Facet.define(), focusChangeEffect = Facet.define(), clipboardInputFilter = Facet.define(), clipboardOutputFilter = Facet.define(), perLineTextDirection = Facet.define({ combine: values => values.some(x => x) }), nativeSelectionHidden = Facet.define({ combine: values => values.some(x => x) }), scrollHandler = Facet.define(), ScrollTarget = class _ScrollTarget { constructor(range, y, x, yMargin, xMargin, isSnapshot = !1) { this.range = range; this.y = y; this.x = x; this.yMargin = yMargin; this.xMargin = xMargin; this.isSnapshot = isSnapshot } range; y; x; yMargin; xMargin; isSnapshot; map(changes) { return changes.empty ? this : new _ScrollTarget(this.range.map(changes), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot) } clip(state) { return this.range.to <= state.doc.length ? this : new _ScrollTarget(EditorSelection.cursor(state.doc.length), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot) } }, scrollIntoView = StateEffect.define({ map: (t2, ch) => t2.map(ch) }), setEditContextFormatting = StateEffect.define(); function logException(state, exception, context) { let handler = state.facet(exceptionSink); handler.length ? handler[0](exception) : window.onerror && window.onerror(String(exception), context, void 0, void 0, exception) || (context ? console.error(context + ":", exception) : console.error(exception)) } var editable = Facet.define({ combine: values => values.length ? values[0] : !0 }), nextPluginID = 0, viewPlugin = Facet.define({ combine(plugins) { return plugins.filter((p, i2) => { for (let j = 0; j < i2; j++)if (plugins[j].plugin == p.plugin) return !1; return !0 }) } }), ViewPlugin = class _ViewPlugin { constructor(id, create, domEventHandlers, domEventObservers, buildExtensions) { this.id = id; this.create = create; this.domEventHandlers = domEventHandlers; this.domEventObservers = domEventObservers; this.baseExtensions = buildExtensions(this), this.extension = this.baseExtensions.concat(viewPlugin.of({ plugin: this, arg: void 0 })) } id; create; domEventHandlers; domEventObservers; extension; baseExtensions; of(arg) { return this.baseExtensions.concat(viewPlugin.of({ plugin: this, arg })) } static define(create, spec) { let { eventHandlers, eventObservers, provide, decorations: deco } = spec || {}; return new _ViewPlugin(nextPluginID++, create, eventHandlers, eventObservers, plugin2 => { let ext = []; return deco && ext.push(decorations.of(view => { let pluginInst = view.plugin(plugin2); return pluginInst ? deco(pluginInst) : Decoration.none })), provide && ext.push(provide(plugin2)), ext }) } static fromClass(cls, spec) { return _ViewPlugin.define((view, arg) => new cls(view, arg), spec) } }, PluginInstance = class { constructor(spec) { this.spec = spec } spec; mustUpdate = null; value = null; get plugin() { return this.spec && this.spec.plugin } update(view) { if (this.value) { if (this.mustUpdate) { let update = this.mustUpdate; if (this.mustUpdate = null, this.value.update) try { this.value.update(update) } catch (e) { if (logException(update.state, e, "CodeMirror plugin crashed"), this.value.destroy) try { this.value.destroy() } catch { } this.deactivate() } } } else if (this.spec) try { this.value = this.spec.plugin.create(view, this.spec.arg) } catch (e) { logException(view.state, e, "CodeMirror plugin crashed"), this.deactivate() } return this } destroy(view) { if (this.value?.destroy) try { this.value.destroy() } catch (e) { logException(view.state, e, "CodeMirror plugin crashed") } } deactivate() { this.spec = this.value = null } }, editorAttributes = Facet.define(), contentAttributes = Facet.define(), decorations = Facet.define(), blockWrappers = Facet.define(), outerDecorations = Facet.define(), atomicRanges = Facet.define(), bidiIsolatedRanges = Facet.define(); function getIsolatedRanges(view, line) { let isolates = view.state.facet(bidiIsolatedRanges); if (!isolates.length) return isolates; let sets = isolates.map(i2 => i2 instanceof Function ? i2(view) : i2), result = []; return RangeSet.spans(sets, line.from, line.to, { point() { }, span(fromDoc, toDoc, active, open) { let from = fromDoc - line.from, to = toDoc - line.from, level = result; for (let i2 = active.length - 1; i2 >= 0; i2--, open--) { let direction = active[i2].spec.bidiIsolate, update; if (direction == null && (direction = autoDirection(line.text, from, to)), open > 0 && level.length && (update = level[level.length - 1]).to == from && update.direction == direction) update.to = to, level = update.inner; else { let add2 = { from, to, direction, inner: [] }; level.push(add2), level = add2.inner } } } }), result } var scrollMargins = Facet.define(); function getScrollMargins(view) { let left = 0, right = 0, top2 = 0, bottom = 0; for (let source of view.state.facet(scrollMargins)) { let m = source(view); m && (m.left != null && (left = Math.max(left, m.left)), m.right != null && (right = Math.max(right, m.right)), m.top != null && (top2 = Math.max(top2, m.top)), m.bottom != null && (bottom = Math.max(bottom, m.bottom))) } return { left, right, top: top2, bottom } } var styleModule = Facet.define(); var ChangedRange = class _ChangedRange { constructor(fromA, toA, fromB, toB) { this.fromA = fromA; this.toA = toA; this.fromB = fromB; this.toB = toB } fromA; toA; fromB; toB; join(other) { return new _ChangedRange(Math.min(this.fromA, other.fromA), Math.max(this.toA, other.toA), Math.min(this.fromB, other.fromB), Math.max(this.toB, other.toB)) } addToSet(set) { let i2 = set.length, me = this; for (; i2 > 0; i2--) { let range = set[i2 - 1]; if (!(range.fromA > me.toA)) { if (range.toA < me.fromA) break; me = me.join(range), set.splice(i2 - 1, 1) } } return set.splice(i2, 0, me), set } static extendWithRanges(diff, ranges) { if (ranges.length == 0) return diff; let result = []; for (let dI = 0, rI = 0, off = 0; ;) { let nextD = dI < diff.length ? diff[dI].fromB : 1e9, nextR = rI < ranges.length ? ranges[rI] : 1e9, fromB = Math.min(nextD, nextR); if (fromB == 1e9) break; let fromA = fromB + off, toB = fromB, toA = fromA; for (; ;)if (rI < ranges.length && ranges[rI] <= toB) { let end = ranges[rI + 1]; rI += 2, toB = Math.max(toB, end); for (let i2 = dI; i2 < diff.length && diff[i2].fromB <= toB; i2++)off = diff[i2].toA - diff[i2].toB; toA = Math.max(toA, end + off) } else if (dI < diff.length && diff[dI].fromB <= toB) { let next = diff[dI++]; toB = Math.max(toB, next.toB), toA = Math.max(toA, next.toA), off = next.toA - next.toB } else break; result.push(new _ChangedRange(fromA, toA, fromB, toB)) } return result } }, ViewUpdate = class _ViewUpdate { constructor(view, state, transactions) { this.view = view; this.state = state; this.transactions = transactions; this.startState = view.state, this.changes = ChangeSet.empty(this.startState.doc.length); for (let tr of transactions) this.changes = this.changes.compose(tr.changes); let changedRanges = []; this.changes.iterChangedRanges((fromA, toA, fromB, toB) => changedRanges.push(new ChangedRange(fromA, toA, fromB, toB))), this.changedRanges = changedRanges } view; state; transactions; changes; startState; flags = 0; changedRanges; static create(view, state, transactions) { return new _ViewUpdate(view, state, transactions) } 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(tr => tr.selection) } get empty() { return this.flags == 0 && this.transactions.length == 0 } }; var noChildren = [], Tile = class { constructor(dom, length, flags = 0) { this.dom = dom; this.length = length; this.flags = flags; dom.cmTile = this } dom; length; flags; parent = null; get breakAfter() { return this.flags & 1 } get children() { return noChildren } isWidget() { return !1 } get isHidden() { return !1 } isComposite() { return !1 } isLine() { return !1 } isText() { return !1 } isBlock() { return !1 } get domAttrs() { return null } sync(track) { if (this.flags |= 2, this.flags & 4) { this.flags &= -5; let attrs = this.domAttrs; attrs && setAttrs(this.dom, attrs) } } toString() { return this.constructor.name + (this.children.length ? `(${this.children})` : "") + (this.breakAfter ? "#" : "") } destroy() { this.parent = null } setDOM(dom) { this.dom = dom, dom.cmTile = this } get posAtStart() { return this.parent ? this.parent.posBefore(this) : 0 } get posAtEnd() { return this.posAtStart + this.length } posBefore(tile, start = this.posAtStart) { let pos = start; for (let child of this.children) { if (child == tile) return pos; pos += child.length + child.breakAfter } throw new RangeError("Invalid child in posBefore") } posAfter(tile) { return this.posBefore(tile) + tile.length } covers(side) { return !0 } coordsIn(pos, side) { return null } domPosFor(off, side) { let index = domIndex(this.dom), after = this.length ? off > 0 : side > 0; return new DOMPos(this.parent.dom, index + (after ? 1 : 0), off == 0 || off == this.length) } markDirty(attrs) { this.flags &= -3, attrs && (this.flags |= 4), this.parent && this.parent.flags & 2 && this.parent.markDirty(!1) } get overrideDOMText() { return null } get root() { for (let t2 = this; t2; t2 = t2.parent)if (t2 instanceof DocTile) return t2; return null } static get(dom) { return dom.cmTile } }, CompositeTile = class extends Tile { _children = []; constructor(dom) { super(dom, 0) } isComposite() { return !0 } get children() { return this._children } get lastChild() { return this.children.length ? this.children[this.children.length - 1] : null } append(child) { this.children.push(child), child.parent = this } sync(track) { if (this.flags & 2) return; super.sync(track); let parent = this.dom, prev = null, next, tracking = track?.node == parent ? track : null, length = 0; for (let child of this.children) { if (child.sync(track), length += child.length + child.breakAfter, next = prev ? prev.nextSibling : parent.firstChild, tracking && next != child.dom && (tracking.written = !0), child.dom.parentNode == parent) for (; next && next != child.dom;)next = rm(next); else parent.insertBefore(child.dom, next); prev = child.dom } for (next = prev ? prev.nextSibling : parent.firstChild, tracking && next && (tracking.written = !0); next;)next = rm(next); this.length = length } }; function rm(dom) { let next = dom.nextSibling; return dom.parentNode.removeChild(dom), next } var DocTile = class extends CompositeTile { constructor(view, dom) { super(dom); this.view = view } view; owns(tile) { for (; tile; tile = tile.parent)if (tile == this) return !0; return !1 } isBlock() { return !0 } nearest(dom) { for (; ;) { if (!dom) return null; let tile = Tile.get(dom); if (tile && this.owns(tile)) return tile; dom = dom.parentNode } } blockTiles(f) { for (let stack = [], cur = this, i2 = 0, pos = 0; ;)if (i2 == cur.children.length) { if (!stack.length) return; cur = cur.parent, cur.breakAfter && pos++, i2 = stack.pop() } else { let next = cur.children[i2++]; if (next instanceof BlockWrapperTile) stack.push(i2), cur = next, i2 = 0; else { let end = pos + next.length, result = f(next, pos); if (result !== void 0) return result; pos = end + next.breakAfter } } } resolveBlock(pos, side) { let before, beforeOff = -1, after, afterOff = -1; if (this.blockTiles((tile, off) => { let end = off + tile.length; if (pos >= off && pos <= end) { if (tile.isWidget() && side >= -1 && side <= 1) { if (tile.flags & 32) return !0; tile.flags & 16 && (before = void 0) } (off < pos || pos == end && (side < -1 ? tile.length : tile.covers(1))) && (!before || !tile.isWidget() && before.isWidget()) && (before = tile, beforeOff = pos - off), (end > pos || pos == off && (side > 1 ? tile.length : tile.covers(-1))) && (!after || !tile.isWidget() && after.isWidget()) && (after = tile, afterOff = pos - off) } }), !before && !after) throw new Error("No tile at position " + pos); return before && side < 0 || !after ? { tile: before, offset: beforeOff } : { tile: after, offset: afterOff } } }, BlockWrapperTile = class _BlockWrapperTile extends CompositeTile { constructor(dom, wrapper) { super(dom); this.wrapper = wrapper } wrapper; isBlock() { return !0 } covers(side) { return this.children.length ? side < 0 ? this.children[0].covers(-1) : this.lastChild.covers(1) : !1 } get domAttrs() { return this.wrapper.attributes } static of(wrapper, dom) { let tile = new _BlockWrapperTile(dom || document.createElement(wrapper.tagName), wrapper); return dom || (tile.flags |= 4), tile } }, LineTile = class _LineTile extends CompositeTile { constructor(dom, attrs) { super(dom); this.attrs = attrs } attrs; isLine() { return !0 } static start(attrs, dom, keepAttrs) { let line = new _LineTile(dom || document.createElement("div"), attrs); return (!dom || !keepAttrs) && (line.flags |= 4), line } get domAttrs() { return this.attrs } resolveInline(pos, side, forCoords) { let before = null, beforeOff = -1, after = null, afterOff = -1; function scan(tile, pos2) { for (let i2 = 0, off = 0; i2 < tile.children.length && off <= pos2; i2++) { let child = tile.children[i2], end = off + child.length; end >= pos2 && (child.isComposite() ? scan(child, pos2 - off) : (!after || after.isHidden && (side > 0 || forCoords && onSameLine(after, child))) && (end > pos2 || child.flags & 32) ? (after = child, afterOff = pos2 - off) : (off < pos2 || child.flags & 16 && !child.isHidden) && (before = child, beforeOff = pos2 - off)), off = end } } scan(this, pos); let target = (side < 0 ? before : after) || before || after; return target ? { tile: target, offset: target == before ? beforeOff : afterOff } : null } coordsIn(pos, side) { let found = this.resolveInline(pos, side, !0); return found ? found.tile.coordsIn(Math.max(0, found.offset), side) : fallbackRect(this) } domIn(pos, side) { let found = this.resolveInline(pos, side); if (found) { let { tile, offset } = found; if (this.dom.contains(tile.dom)) return tile.isText() ? new DOMPos(tile.dom, Math.min(tile.dom.nodeValue.length, offset)) : tile.domPosFor(offset, tile.flags & 16 ? 1 : tile.flags & 32 ? -1 : side); let parent = found.tile.parent, saw = !1, last; for (let ch of parent.children) { if (saw) return new DOMPos(ch.dom, 0); if (ch == found.tile) { if (last) return new DOMPos(last.dom, maxOffset(last.dom)); saw = !0 } } } return new DOMPos(this.dom, 0) } }; function fallbackRect(tile) { let last = tile.dom.lastChild; if (!last) return tile.dom.getBoundingClientRect(); let rects = clientRectsFor(last); return rects[rects.length - 1] || null } function onSameLine(a, b) { let posA = a.coordsIn(0, 1), posB = b.coordsIn(0, 1); return posA && posB && posB.top < posA.bottom } var MarkTile = class _MarkTile extends CompositeTile { constructor(dom, mark) { super(dom); this.mark = mark } mark; get domAttrs() { return this.mark.attrs } static of(mark, dom) { let tile = new _MarkTile(dom || document.createElement(mark.tagName), mark); return dom || (tile.flags |= 4), tile } }, TextTile = class _TextTile extends Tile { constructor(dom, text) { super(dom, text.length); this.text = text } text; sync(track) { this.flags & 2 || (super.sync(track), this.dom.nodeValue != this.text && (track && track.node == this.dom && (track.written = !0), this.dom.nodeValue = this.text)) } isText() { return !0 } toString() { return JSON.stringify(this.text) } coordsIn(pos, side) { let length = this.dom.nodeValue.length; pos > length && (pos = length); let from = pos, to = pos, flatten2 = 0; pos == 0 && side < 0 || pos == length && side >= 0 ? browser_default.chrome || browser_default.gecko || (pos ? (from--, flatten2 = 1) : to < length && (to++, flatten2 = -1)) : side < 0 ? from-- : to < length && to++; let rects = textRange(this.dom, from, to).getClientRects(); if (!rects.length) return null; let rect = rects[(flatten2 ? flatten2 < 0 : side >= 0) ? 0 : rects.length - 1]; return browser_default.safari && !flatten2 && rect.width == 0 && (rect = Array.prototype.find.call(rects, r => r.width) || rect), flatten2 ? flattenRect(rect, flatten2 < 0) : rect || null } static of(text, dom) { let tile = new _TextTile(dom || document.createTextNode(text), text); return dom || (tile.flags |= 2), tile } }, WidgetTile = class _WidgetTile extends Tile { constructor(dom, length, widget, flags) { super(dom, length, flags); this.widget = widget } widget; isWidget() { return !0 } get isHidden() { return this.widget.isHidden } covers(side) { return this.flags & 48 ? !1 : (this.flags & (side < 0 ? 64 : 128)) > 0 } coordsIn(pos, side) { return this.coordsInWidget(pos, side, !1) } coordsInWidget(pos, side, block) { let custom = this.widget.coordsAt(this.dom, pos, side); if (custom) return custom; if (block) return flattenRect(this.dom.getBoundingClientRect(), this.length ? pos == 0 : side <= 0); { let rects = this.dom.getClientRects(), rect = null; if (!rects.length) return null; let fromBack = this.flags & 16 ? !0 : this.flags & 32 ? !1 : pos > 0; for (let i2 = fromBack ? rects.length - 1 : 0; rect = rects[i2], !(pos > 0 ? i2 == 0 : i2 == rects.length - 1 || rect.top < rect.bottom); i2 += fromBack ? -1 : 1); return flattenRect(rect, !fromBack) } } get overrideDOMText() { if (!this.length) return Text.empty; let { root } = this; if (!root) return Text.empty; let start = this.posAtStart; return root.view.state.doc.slice(start, start + this.length) } destroy() { super.destroy(), this.widget.destroy(this.dom) } static of(widget, view, length, flags, dom) { return dom || (dom = widget.toDOM(view), widget.editable || (dom.contentEditable = "false")), new _WidgetTile(dom, length, widget, flags) } }, WidgetBufferTile = class extends Tile { constructor(flags) { let img = document.createElement("img"); img.className = "cm-widgetBuffer", img.setAttribute("aria-hidden", "true"), super(img, 0, flags) } get isHidden() { return !0 } get overrideDOMText() { return Text.empty } coordsIn(pos) { return this.dom.getBoundingClientRect() } }, TilePointer = class { tile; index = 0; beforeBreak = !1; parents = []; constructor(top2) { this.tile = top2 } advance(dist2, side, walker) { let { tile, index, beforeBreak, parents } = this; for (; dist2 || side > 0;)if (tile.isComposite()) if (beforeBreak) { if (!dist2) break; walker && walker.break(), dist2--, beforeBreak = !1 } else if (index == tile.children.length) { if (!dist2 && !parents.length) break; walker && walker.leave(tile), beforeBreak = !!tile.breakAfter, { tile, index } = parents.pop(), index++ } else { let next = tile.children[index], brk = next.breakAfter; (side > 0 ? next.length <= dist2 : next.length < dist2) && (!walker || walker.skip(next, 0, next.length) !== !1 || !next.isComposite) ? (beforeBreak = !!brk, index++, dist2 -= next.length) : (parents.push({ tile, index }), tile = next, index = 0, walker && next.isComposite() && walker.enter(next)) } else if (index == tile.length) beforeBreak = !!tile.breakAfter, { tile, index } = parents.pop(), index++; else if (dist2) { let take = Math.min(dist2, tile.length - index); walker && walker.skip(tile, index, index + take), dist2 -= take, index += take } else break; return this.tile = tile, this.index = index, this.beforeBreak = beforeBreak, this } get root() { return this.parents.length ? this.parents[0].tile : this.tile } }; var LOG_builder = !1; var OpenWrapper = class { constructor(from, to, wrapper, rank) { this.from = from; this.to = to; this.wrapper = wrapper; this.rank = rank } from; to; wrapper; rank }, TileBuilder = class { constructor(cache, root, blockWrappers2) { this.cache = cache; this.root = root; this.blockWrappers = blockWrappers2 } cache; root; blockWrappers; curLine = null; lastBlock = null; afterWidget = null; pos = 0; wrappers = []; wrapperPos = 0; addText(text, marks, openStart, tile) { this.flushBuffer(); let parent = this.ensureMarks(marks, openStart), prev = parent.lastChild; if (prev && prev.isText() && !(prev.flags & 8) && prev.length + text.length < 512) { this.cache.reused.set(prev, 2); let tile2 = parent.children[parent.children.length - 1] = new TextTile(prev.dom, prev.text + text); tile2.parent = parent } else parent.append(tile || TextTile.of(text, this.cache.find(TextTile)?.dom)); this.pos += text.length, this.afterWidget = null } addComposition(composition, context) { let line = this.curLine; line.dom != context.line.dom && (line.setDOM(this.cache.reused.has(context.line) ? freeNode(context.line.dom) : context.line.dom), this.cache.reused.set(context.line, 2)); let head = line; for (let i2 = context.marks.length - 1; i2 >= 0; i2--) { let mark = context.marks[i2], last = head.lastChild; if (last instanceof MarkTile && last.mark.eq(mark.mark)) last.dom != mark.dom && last.setDOM(freeNode(mark.dom)), head = last; else { if (this.cache.reused.get(mark)) { let tile = Tile.get(mark.dom); tile && tile.setDOM(freeNode(mark.dom)) } let nw = MarkTile.of(mark.mark, mark.dom); head.append(nw), head = nw } this.cache.reused.set(mark, 2) } let oldTile = Tile.get(composition.text); oldTile && this.cache.reused.set(oldTile, 2); let text = new TextTile(composition.text, composition.text.nodeValue); text.flags |= 8, head.append(text) } addInlineWidget(widget, marks, openStart) { let noSpace = this.afterWidget && widget.flags & 48 && (this.afterWidget.flags & 48) == (widget.flags & 48); noSpace || this.flushBuffer(); let parent = this.ensureMarks(marks, openStart); !noSpace && !(widget.flags & 16) && parent.append(this.getBuffer(1)), parent.append(widget), this.pos += widget.length, this.afterWidget = widget } addMark(tile, marks, openStart) { this.flushBuffer(), this.ensureMarks(marks, openStart).append(tile), this.pos += tile.length, this.afterWidget = null } addBlockWidget(widget) { this.getBlockPos().append(widget), this.pos += widget.length, this.lastBlock = widget, this.endLine() } continueWidget(length) { let widget = this.afterWidget || this.lastBlock; widget.length += length, this.pos += length } addLineStart(attrs, dom) { attrs || (attrs = lineBaseAttrs); let tile = LineTile.start(attrs, dom || this.cache.find(LineTile)?.dom, !!dom); this.getBlockPos().append(this.lastBlock = this.curLine = tile) } addLine(tile) { this.getBlockPos().append(tile), this.pos += tile.length, this.lastBlock = tile, this.endLine() } addBreak() { this.lastBlock.flags |= 1, this.endLine(), this.pos++ } addLineStartIfNotCovered(attrs) { this.blockPosCovered() || this.addLineStart(attrs) } ensureLine(attrs) { this.curLine || this.addLineStart(attrs) } ensureMarks(marks, openStart) { let parent = this.curLine; for (let i2 = marks.length - 1; i2 >= 0; i2--) { let mark = marks[i2], last; if (openStart > 0 && (last = parent.lastChild) && last instanceof MarkTile && last.mark.eq(mark)) parent = last, openStart--; else { let tile = MarkTile.of(mark, this.cache.find(MarkTile, m => m.mark.eq(mark))?.dom); parent.append(tile), parent = tile, openStart = 0 } } return parent } endLine() { if (this.curLine) { this.flushBuffer(); let last = this.curLine.lastChild; (!last || !hasContent(this.curLine, !1) || last.dom.nodeName != "BR" && last.isWidget() && !(browser_default.ios && hasContent(this.curLine, !0))) && this.curLine.append(this.cache.findWidget(BreakWidget, 0, 32) || new WidgetTile(BreakWidget.toDOM(), 0, BreakWidget, 32)), this.curLine = this.afterWidget = null } } updateBlockWrappers() { this.wrapperPos > this.pos + 1e4 && (this.blockWrappers.goto(this.pos), this.wrappers.length = 0); for (let i2 = this.wrappers.length - 1; i2 >= 0; i2--)this.wrappers[i2].to < this.pos && this.wrappers.splice(i2, 1); for (let cur = this.blockWrappers; cur.value && cur.from <= this.pos; cur.next())if (cur.to >= this.pos) { let wrap = new OpenWrapper(cur.from, cur.to, cur.value, cur.rank), i2 = this.wrappers.length; for (; i2 > 0 && (this.wrappers[i2 - 1].rank - wrap.rank || this.wrappers[i2 - 1].to - wrap.to) < 0;)i2--; this.wrappers.splice(i2, 0, wrap) } this.wrapperPos = this.pos } getBlockPos() { this.updateBlockWrappers(); let parent = this.root; for (let wrap of this.wrappers) { let last = parent.lastChild; if (wrap.from < this.pos && last instanceof BlockWrapperTile && last.wrapper.eq(wrap.wrapper)) parent = last; else { let tile = BlockWrapperTile.of(wrap.wrapper, this.cache.find(BlockWrapperTile, t2 => t2.wrapper.eq(wrap.wrapper))?.dom); parent.append(tile), parent = tile } } return parent } blockPosCovered() { let last = this.lastBlock; return last != null && !last.breakAfter && (!last.isWidget() || (last.flags & 160) > 0) } getBuffer(side) { let flags = 2 | (side < 0 ? 16 : 32), found = this.cache.find(WidgetBufferTile, void 0, 1); return found && (found.flags = flags), found || new WidgetBufferTile(flags) } flushBuffer() { this.afterWidget && !(this.afterWidget.flags & 32) && (this.afterWidget.parent.append(this.getBuffer(-1)), this.afterWidget = null) } }, TextStream = class { cursor; skipCount = 0; text = ""; textOff = 0; constructor(doc2) { this.cursor = doc2.iter() } skip(len) { this.textOff + len <= this.text.length ? this.textOff += len : (this.skipCount += len - (this.text.length - this.textOff), this.text = "", this.textOff = 0) } next(maxLen) { if (this.textOff == this.text.length) { let { value, lineBreak, done } = this.cursor.next(this.skipCount); if (this.skipCount = 0, done) throw new Error("Ran out of text content when drawing inline views"); this.text = value; let len = this.textOff = Math.min(maxLen, value.length); return lineBreak ? null : value.slice(0, len) } let end = Math.min(this.text.length, this.textOff + maxLen), chars = this.text.slice(this.textOff, end); return this.textOff = end, chars } }, buckets = [WidgetTile, LineTile, TextTile, MarkTile, WidgetBufferTile, BlockWrapperTile, DocTile]; for (let i2 = 0; i2 < buckets.length; i2++)buckets[i2].bucket = i2; var TileCache = class { constructor(view) { this.view = view } view; buckets = buckets.map(() => []); index = buckets.map(() => 0); reused = new Map; add(tile) { let i2 = tile.constructor.bucket, bucket = this.buckets[i2]; bucket.length < 6 ? bucket.push(tile) : bucket[this.index[i2] = (this.index[i2] + 1) % 6] = tile } find(cls, test, type = 2) { let i2 = cls.bucket, bucket = this.buckets[i2], off = this.index[i2]; for (let j = bucket.length - 1; j >= 0; j--) { let index = (j + off) % bucket.length, tile = bucket[index]; if ((!test || test(tile)) && !this.reused.has(tile)) return bucket.splice(index, 1), index < off && this.index[i2]--, this.reused.set(tile, type), tile } return null } findWidget(widget, length, flags) { let widgets = this.buckets[0]; if (widgets.length) for (let i2 = 0, pass = 0; ; i2++) { if (i2 == widgets.length) { if (pass) return null; pass = 1, i2 = 0 } let tile = widgets[i2]; if (!this.reused.has(tile) && (pass == 0 ? tile.widget.compare(widget) : tile.widget.constructor == widget.constructor && widget.updateDOM(tile.dom, this.view, tile.widget))) return widgets.splice(i2, 1), i2 < this.index[0] && this.index[0]--, tile.widget == widget && tile.length == length && (tile.flags & 497) == flags ? (this.reused.set(tile, 1), tile) : (this.reused.set(tile, 2), new WidgetTile(tile.dom, length, widget, tile.flags & -498 | flags)) } } reuse(tile) { return this.reused.set(tile, 1), tile } maybeReuse(tile, type = 2) { if (!this.reused.has(tile)) return this.reused.set(tile, type), tile.dom } clear() { for (let i2 = 0; i2 < this.buckets.length; i2++)this.buckets[i2].length = this.index[i2] = 0 } }, TileUpdate = class { constructor(view, old, blockWrappers2, decorations2, disallowBlockEffectsFor) { this.view = view; this.decorations = decorations2; this.disallowBlockEffectsFor = disallowBlockEffectsFor; this.cache = new TileCache(view), this.text = new TextStream(view.state.doc), this.builder = new TileBuilder(this.cache, new DocTile(view, view.contentDOM), RangeSet.iter(blockWrappers2)), this.cache.reused.set(old, 2), this.old = new TilePointer(old), this.reuseWalker = { skip: (tile, from, to) => { if (this.cache.add(tile), tile.isComposite()) return !1 }, enter: tile => this.cache.add(tile), leave: () => { }, break: () => { } } } view; decorations; disallowBlockEffectsFor; text; builder; old; openWidget = !1; openMarks = 0; cache; reuseWalker; run(changes, composition) { LOG_builder && console.log("Build with changes", JSON.stringify(changes)), LOG_builder && composition && console.log("Composition=", JSON.stringify(composition.range), composition.text.nodeValue), LOG_builder && console.log("<<< " + this.old.tile); let compositionContext = composition && this.getCompositionContext(composition.text); for (let posA = 0, posB = 0, i2 = 0; ;) { let next = i2 < changes.length ? changes[i2++] : null, skipA = next ? next.fromA : this.old.root.length; if (skipA > posA) { LOG_builder && console.log("Preserve", posA, "to", skipA); let len = skipA - posA; this.preserve(len, !i2, !next), posA = skipA, posB += len } if (!next) break; composition && next.fromA <= composition.range.fromA && next.toA >= composition.range.toA ? (LOG_builder && console.log("Emit composition", posB, "to", next.toB, "over", posA, "to", next.toA), this.forward(next.fromA, composition.range.fromA, composition.range.fromA < composition.range.toA ? 1 : -1), this.emit(posB, composition.range.fromB), this.cache.clear(), this.builder.addComposition(composition, compositionContext), this.text.skip(composition.range.toB - composition.range.fromB), this.forward(composition.range.fromA, next.toA), this.emit(composition.range.toB, next.toB)) : (LOG_builder && console.log("Emit", posB, "to", next.toB, "over", posA, "to", next.toA), this.forward(next.fromA, next.toA), this.emit(posB, next.toB)), posB = next.toB, posA = next.toA } return LOG_builder && console.log(">>> " + this.builder.root), this.builder.curLine && this.builder.endLine(), this.builder.root } preserve(length, incStart, incEnd) { let activeMarks = getMarks(this.old), openMarks = this.openMarks; this.old.advance(length, incEnd ? 1 : -1, { skip: (tile, from, to) => { if (tile.isWidget()) if (this.openWidget) this.builder.continueWidget(to - from); else { let widget = to > 0 || from < tile.length ? WidgetTile.of(tile.widget, this.view, to - from, tile.flags & 496, this.cache.maybeReuse(tile)) : this.cache.reuse(tile); widget.flags & 256 ? (widget.flags &= -2, this.builder.addBlockWidget(widget)) : (this.builder.ensureLine(null), this.builder.addInlineWidget(widget, activeMarks, openMarks), openMarks = activeMarks.length) } else if (tile.isText()) this.builder.ensureLine(null), !from && to == tile.length && !this.cache.reused.has(tile) ? this.builder.addText(tile.text, activeMarks, openMarks, this.cache.reuse(tile)) : (this.cache.add(tile), this.builder.addText(tile.text.slice(from, to), activeMarks, openMarks)), openMarks = activeMarks.length; else if (tile.isLine()) tile.flags &= -2, this.cache.reused.set(tile, 1), this.builder.addLine(tile); else if (tile instanceof WidgetBufferTile) this.cache.add(tile); else if (tile instanceof MarkTile) this.builder.ensureLine(null), this.builder.addMark(tile, activeMarks, openMarks), this.cache.reused.set(tile, 1), openMarks = activeMarks.length; else return !1; this.openWidget = !1 }, enter: tile => { tile.isLine() ? this.builder.addLineStart(tile.attrs, this.cache.maybeReuse(tile)) : (this.cache.add(tile), tile instanceof MarkTile && activeMarks.unshift(tile.mark)), this.openWidget = !1 }, leave: tile => { tile.isLine() ? activeMarks.length && (activeMarks.length = openMarks = 0) : tile instanceof MarkTile && (activeMarks.shift(), openMarks = Math.min(openMarks, activeMarks.length)) }, break: () => { this.builder.addBreak(), this.openWidget = !1 } }), this.text.skip(length) } emit(from, to) { let pendingLineAttrs = null, b = this.builder, markCount = 0, openEnd = RangeSet.spans(this.decorations, from, to, { point: (from2, to2, deco, active, openStart, index) => { if (deco instanceof PointDecoration) { if (this.disallowBlockEffectsFor[index]) { if (deco.block) throw new RangeError("Block decorations may not be specified via plugins"); if (to2 > this.view.state.doc.lineAt(from2).to) throw new RangeError("Decorations that replace line breaks may not be specified via plugins") } if (markCount = active.length, openStart > active.length) b.continueWidget(to2 - from2); else { let widget = deco.widget || (deco.block ? NullWidget.block : NullWidget.inline), flags = widgetFlags(deco), tile = this.cache.findWidget(widget, to2 - from2, flags) || WidgetTile.of(widget, this.view, to2 - from2, flags); deco.block ? (deco.startSide > 0 && b.addLineStartIfNotCovered(pendingLineAttrs), b.addBlockWidget(tile)) : (b.ensureLine(pendingLineAttrs), b.addInlineWidget(tile, active, openStart)) } pendingLineAttrs = null } else pendingLineAttrs = addLineDeco(pendingLineAttrs, deco); to2 > from2 && this.text.skip(to2 - from2) }, span: (from2, to2, active, openStart) => { for (let pos = from2; pos < to2;) { let chars = this.text.next(Math.min(512, to2 - pos)); chars == null ? (b.addLineStartIfNotCovered(pendingLineAttrs), b.addBreak(), pos++) : (b.ensureLine(pendingLineAttrs), b.addText(chars, active, pos == from2 ? openStart : active.length), pos += chars.length), pendingLineAttrs = null } } }); b.addLineStartIfNotCovered(pendingLineAttrs), this.openWidget = openEnd > markCount, this.openMarks = openEnd } forward(from, to, side = 1) { to - from <= 10 ? this.old.advance(to - from, side, this.reuseWalker) : (this.old.advance(5, -1, this.reuseWalker), this.old.advance(to - from - 10, -1), this.old.advance(5, side, this.reuseWalker)) } getCompositionContext(text) { let marks = [], line = null; for (let parent = text.parentNode; ; parent = parent.parentNode) { let tile = Tile.get(parent); if (parent == this.view.contentDOM) break; tile instanceof MarkTile ? marks.push(tile) : tile?.isLine() ? line = tile : tile instanceof BlockWrapperTile || (parent.nodeName == "DIV" && !line && parent != this.view.contentDOM ? line = new LineTile(parent, lineBaseAttrs) : line || marks.push(MarkTile.of(new MarkDecoration({ tagName: parent.nodeName.toLowerCase(), attributes: getAttrs(parent) }), parent))) } return { line, marks } } }; function hasContent(tile, requireText) { let scan = tile2 => { for (let ch of tile2.children) if ((requireText ? ch.isText() : ch.length) || scan(ch)) return !0; return !1 }; return scan(tile) } function widgetFlags(deco) { let flags = deco.isReplace ? (deco.startSide < 0 ? 64 : 0) | (deco.endSide > 0 ? 128 : 0) : deco.startSide > 0 ? 32 : 16; return deco.block && (flags |= 256), flags } var lineBaseAttrs = { class: "cm-line" }; function addLineDeco(value, deco) { let attrs = deco.spec.attributes, cls = deco.spec.class; return !attrs && !cls || (value || (value = { class: "cm-line" }), attrs && combineAttrs(attrs, value), cls && (value.class += " " + cls)), value } function getMarks(ptr) { let found = []; for (let i2 = ptr.parents.length; i2 > 1; i2--) { let tile = i2 == ptr.parents.length ? ptr.tile : ptr.parents[i2].tile; tile instanceof MarkTile && found.push(tile.mark) } return found } function freeNode(node) { let tile = Tile.get(node); return tile && tile.setDOM(node.cloneNode()), node } var NullWidget = class _NullWidget extends WidgetType { constructor(tag) { super(); this.tag = tag } tag; eq(other) { return other.tag == this.tag } toDOM() { return document.createElement(this.tag) } updateDOM(elt) { return elt.nodeName.toLowerCase() == this.tag } get isHidden() { return !0 } static inline = new _NullWidget("span"); static block = new _NullWidget("div") }, BreakWidget = new class extends WidgetType { toDOM() { return document.createElement("br") } get isHidden() { return !0 } get editable() { return !0 } }; var DocView = class { constructor(view) { this.view = view; this.updateDeco(), this.tile = new DocTile(view, view.contentDOM), this.updateInner([new ChangedRange(0, 0, 0, view.state.doc.length)], null) } view; tile; decorations = []; blockWrappers = []; dynamicDecorationMap = [!1]; domChanged = null; hasComposition = null; editContextFormatting = Decoration.none; lastCompositionAfterCursor = !1; minWidth = 0; minWidthFrom = 0; minWidthTo = 0; impreciseAnchor = null; impreciseHead = null; forceSelection = !1; lastUpdate = Date.now(); update(update) { let changedRanges = update.changedRanges; this.minWidth > 0 && changedRanges.length && (changedRanges.every(({ fromA, toA }) => toA < this.minWidthFrom || fromA > this.minWidthTo) ? (this.minWidthFrom = update.changes.mapPos(this.minWidthFrom, 1), this.minWidthTo = update.changes.mapPos(this.minWidthTo, 1)) : this.minWidth = this.minWidthFrom = this.minWidthTo = 0), this.updateEditContextFormatting(update); let readCompositionAt = -1; this.view.inputState.composing >= 0 && !this.view.observer.editContext && (this.domChanged?.newSel ? readCompositionAt = this.domChanged.newSel.head : !touchesComposition(update.changes, this.hasComposition) && !update.selectionSet && (readCompositionAt = update.state.selection.main.head)); let composition = readCompositionAt > -1 ? findCompositionRange(this.view, update.changes, readCompositionAt) : null; if (this.domChanged = null, this.hasComposition) { let { from, to } = this.hasComposition; changedRanges = new ChangedRange(from, to, update.changes.mapPos(from, -1), update.changes.mapPos(to, 1)).addToSet(changedRanges.slice()) } this.hasComposition = composition ? { from: composition.range.fromB, to: composition.range.toB } : null, (browser_default.ie || browser_default.chrome) && !composition && update && update.state.doc.lines != update.startState.doc.lines && (this.forceSelection = !0); let prevDeco = this.decorations, prevWrappers = this.blockWrappers; this.updateDeco(); let decoDiff = findChangedDeco(prevDeco, this.decorations, update.changes); decoDiff.length && (changedRanges = ChangedRange.extendWithRanges(changedRanges, decoDiff)); let blockDiff = findChangedWrappers(prevWrappers, this.blockWrappers, update.changes); return blockDiff.length && (changedRanges = ChangedRange.extendWithRanges(changedRanges, blockDiff)), composition && !changedRanges.some(r => r.fromA <= composition.range.fromA && r.toA >= composition.range.toA) && (changedRanges = composition.range.addToSet(changedRanges.slice())), this.tile.flags & 2 && changedRanges.length == 0 ? !1 : (this.updateInner(changedRanges, composition), update.transactions.length && (this.lastUpdate = Date.now()), !0) } updateInner(changes, composition) { this.view.viewState.mustMeasureContent = !0; let { observer } = this.view; observer.ignore(() => { if (composition || changes.length) { let oldTile = this.tile, builder = new TileUpdate(this.view, oldTile, this.blockWrappers, this.decorations, this.dynamicDecorationMap); composition && Tile.get(composition.text) && builder.cache.reused.set(Tile.get(composition.text), 2), this.tile = builder.run(changes, composition), destroyDropped(oldTile, builder.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 track = browser_default.chrome || browser_default.ios ? { node: observer.selectionRange.focusNode, written: !1 } : void 0; this.tile.sync(track), track && (track.written || observer.selectionRange.focusNode != track.node || !this.tile.dom.contains(track.node)) && (this.forceSelection = !0), this.tile.dom.style.height = "" }); let gaps = []; if (this.view.viewport.from || this.view.viewport.to < this.view.state.doc.length) for (let child of this.tile.children) child.isWidget() && child.widget instanceof BlockGapWidget && gaps.push(child.dom); observer.updateGaps(gaps) } updateEditContextFormatting(update) { this.editContextFormatting = this.editContextFormatting.map(update.changes); for (let tr of update.transactions) for (let effect of tr.effects) effect.is(setEditContextFormatting) && (this.editContextFormatting = effect.value) } updateSelection(mustRead = !1, fromPointer = !1) { (mustRead || !this.view.observer.selectionRange.focusNode) && this.view.observer.readSelectionRange(); let { dom } = this.tile, activeElt = this.view.root.activeElement, focused = activeElt == dom, selectionNotFocus = !focused && !(this.view.state.facet(editable) || dom.tabIndex > -1) && hasSelection(dom, this.view.observer.selectionRange) && !(activeElt && dom.contains(activeElt)); if (!(focused || fromPointer || selectionNotFocus)) return; let force = this.forceSelection; this.forceSelection = !1; let main = this.view.state.selection.main, anchor, head; if (main.empty ? head = anchor = this.inlineDOMNearPos(main.anchor, main.assoc || 1) : (head = this.inlineDOMNearPos(main.head, main.head == main.from ? 1 : -1), anchor = this.inlineDOMNearPos(main.anchor, main.anchor == main.from ? 1 : -1)), browser_default.gecko && main.empty && !this.hasComposition && betweenUneditable(anchor)) { let dummy = document.createTextNode(""); this.view.observer.ignore(() => anchor.node.insertBefore(dummy, anchor.node.childNodes[anchor.offset] || null)), anchor = head = new DOMPos(dummy, 0), force = !0 } let domSel = this.view.observer.selectionRange; (force || !domSel.focusNode || (!isEquivalentPosition(anchor.node, anchor.offset, domSel.anchorNode, domSel.anchorOffset) || !isEquivalentPosition(head.node, head.offset, domSel.focusNode, domSel.focusOffset)) && !this.suppressWidgetCursorChange(domSel, main)) && (this.view.observer.ignore(() => { browser_default.android && browser_default.chrome && dom.contains(domSel.focusNode) && inUneditable(domSel.focusNode, dom) && (dom.blur(), dom.focus({ preventScroll: !0 })); let rawSel = getSelection(this.view.root); if (rawSel) if (main.empty) { if (browser_default.gecko) { let nextTo = nextToUneditable(anchor.node, anchor.offset); if (nextTo && nextTo != 3) { let text = (nextTo == 1 ? textNodeBefore : textNodeAfter)(anchor.node, anchor.offset); text && (anchor = new DOMPos(text.node, text.offset)) } } rawSel.collapse(anchor.node, anchor.offset), main.bidiLevel != null && rawSel.caretBidiLevel !== void 0 && (rawSel.caretBidiLevel = main.bidiLevel) } else if (rawSel.extend) { rawSel.collapse(anchor.node, anchor.offset); try { rawSel.extend(head.node, head.offset) } catch { } } else { let range = document.createRange(); main.anchor > main.head && ([anchor, head] = [head, anchor]), range.setEnd(head.node, head.offset), range.setStart(anchor.node, anchor.offset), rawSel.removeAllRanges(), rawSel.addRange(range) } selectionNotFocus && this.view.root.activeElement == dom && (dom.blur(), activeElt && activeElt.focus()) }), this.view.observer.setSelectionRange(anchor, head)), this.impreciseAnchor = anchor.precise ? null : new DOMPos(domSel.anchorNode, domSel.anchorOffset), this.impreciseHead = head.precise ? null : new DOMPos(domSel.focusNode, domSel.focusOffset) } suppressWidgetCursorChange(sel, cursor) { return this.hasComposition && cursor.empty && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset) && this.posFromDOM(sel.focusNode, sel.focusOffset) == cursor.head } enforceCursorAssoc() { if (this.hasComposition) return; let { view } = this, cursor = view.state.selection.main, sel = getSelection(view.root), { anchorNode, anchorOffset } = view.observer.selectionRange; if (!sel || !cursor.empty || !cursor.assoc || !sel.modify) return; let line = this.lineAt(cursor.head, cursor.assoc); if (!line) return; let lineStart = line.posAtStart; if (cursor.head == lineStart || cursor.head == lineStart + line.length) return; let before = this.coordsAt(cursor.head, -1), after = this.coordsAt(cursor.head, 1); if (!before || !after || before.bottom > after.top) return; let dom = this.domAtPos(cursor.head + cursor.assoc, cursor.assoc); sel.collapse(dom.node, dom.offset), sel.modify("move", cursor.assoc < 0 ? "forward" : "backward", "lineboundary"), view.observer.readSelectionRange(); let newRange = view.observer.selectionRange; view.docView.posFromDOM(newRange.anchorNode, newRange.anchorOffset) != cursor.from && sel.collapse(anchorNode, anchorOffset) } posFromDOM(node, offset) { let tile = this.tile.nearest(node); if (!tile) return this.tile.dom.compareDocumentPosition(node) & 2 ? 0 : this.view.state.doc.length; let start = tile.posAtStart; if (tile.isComposite()) { let after; if (node == tile.dom) after = tile.dom.childNodes[offset]; else { let bias = maxOffset(node) == 0 ? 0 : offset == 0 ? -1 : 1; for (; ;) { let parent = node.parentNode; if (parent == tile.dom) break; bias == 0 && parent.firstChild != parent.lastChild && (node == parent.firstChild ? bias = -1 : bias = 1), node = parent } bias < 0 ? after = node : after = node.nextSibling } if (after == tile.dom.firstChild) return start; for (; after && !Tile.get(after);)after = after.nextSibling; if (!after) return start + tile.length; for (let i2 = 0, pos = start; ; i2++) { let child = tile.children[i2]; if (child.dom == after) return pos; pos += child.length + child.breakAfter } } else return tile.isText() ? node == tile.dom ? start + offset : start + (offset ? tile.length : 0) : start } domAtPos(pos, side) { let { tile, offset } = this.tile.resolveBlock(pos, side); return tile.isWidget() ? tile.domPosFor(pos, side) : tile.domIn(offset, side) } inlineDOMNearPos(pos, side) { let before, beforeOff = -1, beforeBad = !1, after, afterOff = -1, afterBad = !1; return this.tile.blockTiles((tile, off) => { if (tile.isWidget()) { if (tile.flags & 32 && off >= pos) return !0; tile.flags & 16 && (beforeBad = !0) } else { let end = off + tile.length; if (off <= pos && (before = tile, beforeOff = pos - off, beforeBad = end < pos), end >= pos && !after && (after = tile, afterOff = pos - off, afterBad = off > pos), off > pos && after) return !0 } }), !before && !after ? this.domAtPos(pos, side) : (beforeBad && after ? before = null : afterBad && before && (after = null), before && side < 0 || !after ? before.domIn(beforeOff, side) : after.domIn(afterOff, side)) } coordsAt(pos, side) { let { tile, offset } = this.tile.resolveBlock(pos, side); return tile.isWidget() ? tile.widget instanceof BlockGapWidget ? null : tile.coordsInWidget(offset, side, !0) : tile.coordsIn(offset, side) } lineAt(pos, side) { let { tile } = this.tile.resolveBlock(pos, side); return tile.isLine() ? tile : null } coordsForChar(pos) { let { tile, offset } = this.tile.resolveBlock(pos, 1); if (!tile.isLine()) return null; function scan(tile2, offset2) { if (tile2.isComposite()) for (let ch of tile2.children) { if (ch.length >= offset2) { let found = scan(ch, offset2); if (found) return found } if (offset2 -= ch.length, offset2 < 0) break } else if (tile2.isText() && offset2 < tile2.length) { let end = findClusterBreak2(tile2.text, offset2); if (end == offset2) return null; let rects = textRange(tile2.dom, offset2, end).getClientRects(); for (let i2 = 0; i2 < rects.length; i2++) { let rect = rects[i2]; if (i2 == rects.length - 1 || rect.top < rect.bottom && rect.left < rect.right) return rect } } return null } return scan(tile, offset) } measureVisibleLineHeights(viewport) { let result = [], { from, to } = viewport, contentWidth = this.view.contentDOM.clientWidth, isWider = contentWidth > Math.max(this.view.scrollDOM.clientWidth, this.minWidth) + 1, widest = -1, ltr = this.view.textDirection == 0, spaceAbove = 0, scan = (tile, pos, measureBounds) => { for (let i2 = 0; i2 < tile.children.length && !(pos > to); i2++) { let child = tile.children[i2], end = pos + child.length, childRect = child.dom.getBoundingClientRect(), { height } = childRect; if (measureBounds && !i2 && (spaceAbove += childRect.top - measureBounds.top), child instanceof BlockWrapperTile) end > from && scan(child, pos, childRect); else if (pos >= from && (spaceAbove > 0 && result.push(-spaceAbove), result.push(height + spaceAbove), spaceAbove = 0, isWider)) { let last = child.dom.lastChild, rects = last ? clientRectsFor(last) : []; if (rects.length) { let rect = rects[rects.length - 1], width = ltr ? rect.right - childRect.left : childRect.right - rect.left; width > widest && (widest = width, this.minWidth = contentWidth, this.minWidthFrom = pos, this.minWidthTo = end) } } measureBounds && i2 == tile.children.length - 1 && (spaceAbove += measureBounds.bottom - childRect.bottom), pos = end + child.breakAfter } }; return scan(this.tile, 0, null), result } textDirectionAt(pos) { let { tile } = this.tile.resolveBlock(pos, 1); return getComputedStyle(tile.dom).direction == "rtl" ? 1 : 0 } measureTextSize() { let lineMeasure = this.tile.blockTiles(tile => { if (tile.isLine() && tile.children.length && tile.length <= 20) { let totalWidth = 0, textHeight2; for (let child of tile.children) { if (!child.isText() || /[^ -~]/.test(child.text)) return; let rects = clientRectsFor(child.dom); if (rects.length != 1) return; totalWidth += rects[0].width, textHeight2 = rects[0].height } if (totalWidth) return { lineHeight: tile.dom.getBoundingClientRect().height, charWidth: totalWidth / tile.length, textHeight: textHeight2 } } }); if (lineMeasure) return lineMeasure; let dummy = document.createElement("div"), lineHeight, charWidth, textHeight; return dummy.className = "cm-line", dummy.style.width = "99999px", dummy.style.position = "absolute", dummy.textContent = "abc def ghi jkl mno pqr stu", this.view.observer.ignore(() => { this.tile.dom.appendChild(dummy); let rect = clientRectsFor(dummy.firstChild)[0]; lineHeight = dummy.getBoundingClientRect().height, charWidth = rect && rect.width ? rect.width / 27 : 7, textHeight = rect && rect.height ? rect.height : lineHeight, dummy.remove() }), { lineHeight, charWidth, textHeight } } computeBlockGapDeco() { let deco = [], vs = this.view.viewState; for (let pos = 0, i2 = 0; ; i2++) { let next = i2 == vs.viewports.length ? null : vs.viewports[i2], end = next ? next.from - 1 : this.view.state.doc.length; if (end > pos) { let height = (vs.lineBlockAt(end).bottom - vs.lineBlockAt(pos).top) / this.view.scaleY; deco.push(Decoration.replace({ widget: new BlockGapWidget(height), block: !0, inclusive: !0, isBlockGap: !0 }).range(pos, end)) } if (!next) break; pos = next.to + 1 } return Decoration.set(deco) } updateDeco() { let i2 = 1, allDeco = this.view.state.facet(decorations).map(d => (this.dynamicDecorationMap[i2++] = typeof d == "function") ? d(this.view) : d), dynamicOuter = !1, outerDeco = this.view.state.facet(outerDecorations).map((d, i3) => { let dynamic = typeof d == "function"; return dynamic && (dynamicOuter = !0), dynamic ? d(this.view) : d }); for (outerDeco.length && (this.dynamicDecorationMap[i2++] = dynamicOuter, allDeco.push(RangeSet.join(outerDeco))), this.decorations = [this.editContextFormatting, ...allDeco, this.computeBlockGapDeco(), this.view.viewState.lineGapDeco]; i2 < this.decorations.length;)this.dynamicDecorationMap[i2++] = !1; this.blockWrappers = this.view.state.facet(blockWrappers).map(v => typeof v == "function" ? v(this.view) : v) } scrollIntoView(target) { if (target.isSnapshot) { let ref = this.view.viewState.lineBlockAt(target.range.head); this.view.scrollDOM.scrollTop = ref.top - target.yMargin, this.view.scrollDOM.scrollLeft = target.xMargin; return } for (let handler of this.view.state.facet(scrollHandler)) try { if (handler(this.view, target.range, target)) return !0 } catch (e) { logException(this.view.state, e, "scroll handler") } let { range } = target, rect = this.coordsAt(range.head, range.assoc ?? (range.empty ? 0 : range.head > range.anchor ? -1 : 1)), other; if (!rect) return; !range.empty && (other = this.coordsAt(range.anchor, range.anchor > range.head ? -1 : 1)) && (rect = { left: Math.min(rect.left, other.left), top: Math.min(rect.top, other.top), right: Math.max(rect.right, other.right), bottom: Math.max(rect.bottom, other.bottom) }); let margins = getScrollMargins(this.view), targetRect = { left: rect.left - margins.left, top: rect.top - margins.top, right: rect.right + margins.right, bottom: rect.bottom + margins.bottom }, { offsetWidth, offsetHeight } = this.view.scrollDOM; if (scrollRectIntoView(this.view.scrollDOM, targetRect, range.head < range.anchor ? -1 : 1, target.x, target.y, Math.max(Math.min(target.xMargin, offsetWidth), -offsetWidth), Math.max(Math.min(target.yMargin, offsetHeight), -offsetHeight), this.view.textDirection == 0), window.visualViewport && window.innerHeight - window.visualViewport.height > 1 && (rect.top > window.pageYOffset + window.visualViewport.offsetTop + window.visualViewport.height || rect.bottom < window.pageYOffset + window.visualViewport.offsetTop)) { let line = this.view.docView.lineAt(range.head, 1); line && line.dom.scrollIntoView({ block: "nearest" }) } } lineHasWidget(pos) { let scan = child => child.isWidget() || child.children.some(scan); return scan(this.tile.resolveBlock(pos, 1).tile) } destroy() { destroyDropped(this.tile) } }; function destroyDropped(tile, reused) { let r = reused?.get(tile); if (r != 1) { r == null && tile.destroy(); for (let ch of tile.children) destroyDropped(ch, reused) } } function betweenUneditable(pos) { return pos.node.nodeType == 1 && pos.node.firstChild && (pos.offset == 0 || pos.node.childNodes[pos.offset - 1].contentEditable == "false") && (pos.offset == pos.node.childNodes.length || pos.node.childNodes[pos.offset].contentEditable == "false") } function findCompositionNode(view, headPos) { let sel = view.observer.selectionRange; if (!sel.focusNode) return null; let textBefore = textNodeBefore(sel.focusNode, sel.focusOffset), textAfter = textNodeAfter(sel.focusNode, sel.focusOffset), textNode = textBefore || textAfter; if (textAfter && textBefore && textAfter.node != textBefore.node) { let tileAfter = Tile.get(textAfter.node); if (!tileAfter || tileAfter.isText() && tileAfter.text != textAfter.node.nodeValue) textNode = textAfter; else if (view.docView.lastCompositionAfterCursor) { let tileBefore = Tile.get(textBefore.node); !tileBefore || tileBefore.isText() && tileBefore.text != textBefore.node.nodeValue || (textNode = textAfter) } } if (view.docView.lastCompositionAfterCursor = textNode != textBefore, !textNode) return null; let from = headPos - textNode.offset; return { from, to: from + textNode.node.nodeValue.length, node: textNode.node } } function findCompositionRange(view, changes, headPos) { let found = findCompositionNode(view, headPos); if (!found) return null; let { node: textNode, from, to } = found, text = textNode.nodeValue; if (/[\n\r]/.test(text) || view.state.doc.sliceString(found.from, found.to) != text) return null; let inv = changes.invertedDesc; return { range: new ChangedRange(inv.mapPos(from), inv.mapPos(to), from, to), text: textNode } } function nextToUneditable(node, offset) { return node.nodeType != 1 ? 0 : (offset && node.childNodes[offset - 1].contentEditable == "false" ? 1 : 0) | (offset < node.childNodes.length && node.childNodes[offset].contentEditable == "false" ? 2 : 0) } var DecorationComparator = class { changes = []; compareRange(from, to) { addRange(from, to, this.changes) } comparePoint(from, to) { addRange(from, to, this.changes) } boundChange(pos) { addRange(pos, pos, this.changes) } }; function findChangedDeco(a, b, diff) { let comp = new DecorationComparator; return RangeSet.compare(a, b, diff, comp), comp.changes } var WrapperComparator = class { changes = []; compareRange(from, to) { addRange(from, to, this.changes) } comparePoint() { } boundChange(pos) { addRange(pos, pos, this.changes) } }; function findChangedWrappers(a, b, diff) { let comp = new WrapperComparator; return RangeSet.compare(a, b, diff, comp), comp.changes } function inUneditable(node, inside) { for (let cur = node; cur && cur != inside; cur = cur.assignedSlot || cur.parentNode)if (cur.nodeType == 1 && cur.contentEditable == "false") return !0; return !1 } function touchesComposition(changes, composition) { let touched = !1; return composition && changes.iterChangedRanges((from, to) => { from < composition.to && to > composition.from && (touched = !0) }), touched } var BlockGapWidget = class extends WidgetType { constructor(height) { super(); this.height = height } height; toDOM() { let elt = document.createElement("div"); return elt.className = "cm-gap", this.updateDOM(elt), elt } eq(other) { return other.height == this.height } updateDOM(elt) { return elt.style.height = this.height + "px", !0 } get editable() { return !0 } get estimatedHeight() { return this.height } ignoreEvent() { return !1 } }; function groupAt(state, pos, bias = 1) { let categorize = state.charCategorizer(pos), line = state.doc.lineAt(pos), linePos = pos - line.from; if (line.length == 0) return EditorSelection.cursor(pos); linePos == 0 ? bias = 1 : linePos == line.length && (bias = -1); let from = linePos, to = linePos; bias < 0 ? from = findClusterBreak2(line.text, linePos, !1) : to = findClusterBreak2(line.text, linePos); let cat = categorize(line.text.slice(from, to)); for (; from > 0;) { let prev = findClusterBreak2(line.text, from, !1); if (categorize(line.text.slice(prev, from)) != cat) break; from = prev } for (; to < line.length;) { let next = findClusterBreak2(line.text, to); if (categorize(line.text.slice(to, next)) != cat) break; to = next } return EditorSelection.range(from + line.from, to + line.from) } function posAtCoordsImprecise(view, contentRect, block, x, y) { let into = Math.round((x - contentRect.left) * view.defaultCharacterWidth); if (view.lineWrapping && block.height > view.defaultLineHeight * 1.5) { let textHeight = view.viewState.heightOracle.textHeight, line = Math.floor((y - block.top - (view.defaultLineHeight - textHeight) * .5) / textHeight); into += line * view.viewState.heightOracle.lineLength } let content2 = view.state.sliceDoc(block.from, block.to); return block.from + findColumn(content2, into, view.state.tabSize) } function blockAt(view, pos, side) { let line = view.lineBlockAt(pos); if (Array.isArray(line.type)) { let best; for (let l of line.type) { if (l.from > pos) break; if (!(l.to < pos)) { if (l.from < pos && l.to > pos) return l; (!best || l.type == 0 && (best.type != l.type || (side < 0 ? l.from < pos : l.to > pos))) && (best = l) } } return best || line } return line } function moveToLineBoundary(view, start, forward, includeWrap) { let line = blockAt(view, start.head, start.assoc || -1), coords = !includeWrap || line.type != 0 || !(view.lineWrapping || line.widgetLineBreaks) ? null : view.coordsAtPos(start.assoc < 0 && start.head > line.from ? start.head - 1 : start.head); if (coords) { let editorRect = view.dom.getBoundingClientRect(), direction = view.textDirectionAt(line.from), pos = view.posAtCoords({ x: forward == (direction == 0) ? editorRect.right - 1 : editorRect.left + 1, y: (coords.top + coords.bottom) / 2 }); if (pos != null) return EditorSelection.cursor(pos, forward ? -1 : 1) } return EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1) } function moveByChar(view, start, forward, by) { + let line = view.state.doc.lineAt(start.head), spans = view.bidiSpans(line), direction = view.textDirectionAt(line.from); for (let cur = start, check = null; ;) { + let next = moveVisually(line, spans, direction, cur, forward), char = movedOver; if (!next) { + if (line.number == (forward ? view.state.doc.lines : 1)) return cur; char = ` +`, line = view.state.doc.line(line.number + (forward ? 1 : -1)), spans = view.bidiSpans(line), next = view.visualLineSide(line, !forward) + } if (check) { if (!check(char)) return cur } else { if (!by) return next; check = by(char) } cur = next + } +} function byGroup(view, pos, start) { let categorize = view.state.charCategorizer(pos), cat = categorize(start); return next => { let nextCat = categorize(next); return cat == 1 && (cat = nextCat), cat == nextCat } } function moveVertically(view, start, forward, distance) { let startPos = start.head, dir = forward ? 1 : -1; if (startPos == (forward ? view.state.doc.length : 0)) return EditorSelection.cursor(startPos, start.assoc); let goal = start.goalColumn, startY, rect = view.contentDOM.getBoundingClientRect(), startCoords = view.coordsAtPos(startPos, start.assoc || ((start.empty ? forward : start.head == start.from) ? 1 : -1)), docTop = view.documentTop; if (startCoords) goal == null && (goal = startCoords.left - rect.left), startY = dir < 0 ? startCoords.top : startCoords.bottom; else { let line = view.viewState.lineBlockAt(startPos); goal == null && (goal = Math.min(rect.right - rect.left, view.defaultCharacterWidth * (startPos - line.from))), startY = (dir < 0 ? line.top : line.bottom) + docTop } let resolvedGoal = rect.left + goal, halfText = view.viewState.heightOracle.textHeight >> 1, dist2 = distance ?? halfText; for (let scan = 0; ; scan += halfText) { let y = startY + (dist2 + scan) * dir, pos = posAtCoords(view, { x: resolvedGoal, y }, !1, dir); if (forward ? y > rect.bottom : y < rect.top) return EditorSelection.cursor(pos.pos, pos.assoc); let posCoords = view.coordsAtPos(pos.pos, pos.assoc), mid = posCoords ? (posCoords.top + posCoords.bottom) / 2 : 0; if (!posCoords || (forward ? mid > startY : mid < startY)) return EditorSelection.cursor(pos.pos, pos.assoc, void 0, goal) } } function skipAtomicRanges(atoms, pos, bias) { for (; ;) { let moved = 0; for (let set of atoms) set.between(pos - 1, pos + 1, (from, to, value) => { if (pos > from && pos < to) { let side = moved || bias || (pos - from < to - pos ? -1 : 1); pos = side < 0 ? from : to, moved = side } }); if (!moved) return pos } } function skipAtomsForSelection(atoms, sel) { let ranges = null; for (let i2 = 0; i2 < sel.ranges.length; i2++) { let range = sel.ranges[i2], updated = null; if (range.empty) { let pos = skipAtomicRanges(atoms, range.from, 0); pos != range.from && (updated = EditorSelection.cursor(pos, -1)) } else { let from = skipAtomicRanges(atoms, range.from, -1), to = skipAtomicRanges(atoms, range.to, 1); (from != range.from || to != range.to) && (updated = EditorSelection.range(range.from == range.anchor ? from : to, range.from == range.head ? from : to)) } updated && (ranges || (ranges = sel.ranges.slice()), ranges[i2] = updated) } return ranges ? EditorSelection.create(ranges, sel.mainIndex) : sel } function skipAtoms(view, oldPos, pos) { let newPos = skipAtomicRanges(view.state.facet(atomicRanges).map(f => f(view)), pos.from, oldPos.head > pos.from ? -1 : 1); return newPos == pos.from ? pos : EditorSelection.cursor(newPos, newPos < pos.from ? 1 : -1) } var PosAssoc = class { constructor(pos, assoc) { this.pos = pos; this.assoc = assoc } pos; assoc }; function posAtCoords(view, coords, precise, scanY) { let content2 = view.contentDOM.getBoundingClientRect(), docTop = content2.top + view.viewState.paddingTop, { x, y } = coords, yOffset = y - docTop, block; for (; ;) { if (yOffset < 0) return new PosAssoc(0, 1); if (yOffset > view.viewState.docHeight) return new PosAssoc(view.state.doc.length, -1); if (block = view.elementAtHeight(yOffset), scanY == null) break; if (block.type == 0) { if (scanY < 0 ? block.to < view.viewport.from : block.from > view.viewport.to) break; let rect = view.docView.coordsAt(scanY < 0 ? block.from : block.to, scanY > 0 ? -1 : 1); if (rect && (scanY < 0 ? rect.top <= yOffset + docTop : rect.bottom >= yOffset + docTop)) break } let halfLine = view.viewState.heightOracle.textHeight / 2; yOffset = scanY > 0 ? block.bottom + halfLine : block.top - halfLine } if (view.viewport.from >= block.to || view.viewport.to <= block.from) { if (precise) return null; if (block.type == 0) { let pos = posAtCoordsImprecise(view, content2, block, x, y); return new PosAssoc(pos, pos == block.from ? 1 : -1) } } if (block.type != 0) return yOffset < (block.top + block.bottom) / 2 ? new PosAssoc(block.from, 1) : new PosAssoc(block.to, -1); let line = view.docView.lineAt(block.from, 2); return (!line || line.length != block.length) && (line = view.docView.lineAt(block.from, -2)), new InlineCoordsScan(view, x, y, view.textDirectionAt(block.from)).scanTile(line, block.from) } var InlineCoordsScan = class { constructor(view, x, y, baseDir) { this.view = view; this.x = x; this.y = y; this.baseDir = baseDir } view; x; y; baseDir; line = null; spans = null; bidiSpansAt(pos) { return (!this.line || this.line.from > pos || this.line.to < pos) && (this.line = this.view.state.doc.lineAt(pos), this.spans = this.view.bidiSpans(this.line)), this } baseDirAt(pos, side) { let { line, spans } = this.bidiSpansAt(pos); return spans[BidiSpan.find(spans, pos - line.from, -1, side)].level == this.baseDir } dirAt(pos, side) { let { line, spans } = this.bidiSpansAt(pos); return spans[BidiSpan.find(spans, pos - line.from, -1, side)].dir } bidiIn(from, to) { let { spans, line } = this.bidiSpansAt(from); return spans.length > 1 || spans.length && (spans[0].level != this.baseDir || spans[0].to + line.from < to) } scan(positions, getRects) { let lo = 0, hi = positions.length - 1, seen = new Set, bidi = this.bidiIn(positions[0], positions[hi]), above, below, closestI = -1, closestDx = 1e9, closestRect; search: for (; lo < hi;) { let dist2 = hi - lo, mid = lo + hi >> 1; adjust: if (seen.has(mid)) { let scan = lo + Math.floor(Math.random() * dist2); for (let i2 = 0; i2 < dist2; i2++) { if (!seen.has(scan)) { mid = scan; break adjust } scan++, scan == hi && (scan = lo) } break search } seen.add(mid); let rects = getRects(mid); if (rects) for (let i2 = 0; i2 < rects.length; i2++) { let rect = rects[i2], side = 0; if (!(rect.width == 0 && rects.length > 1)) { if (rect.bottom < this.y) (!above || above.bottom < rect.bottom) && (above = rect), side = 1; else if (rect.top > this.y) (!below || below.top > rect.top) && (below = rect), side = -1; else { let off = rect.left > this.x ? this.x - rect.left : rect.right < this.x ? this.x - rect.right : 0, dx = Math.abs(off); dx < closestDx && (closestI = mid, closestDx = dx, closestRect = rect), off && (side = off < 0 == (this.baseDir == 0) ? -1 : 1) } side == -1 && (!bidi || this.baseDirAt(positions[mid], 1)) ? hi = mid : side == 1 && (!bidi || this.baseDirAt(positions[mid + 1], -1)) && (lo = mid + 1) } } } if (!closestRect) { let side = above && (!below || this.y - above.bottom < below.top - this.y) ? above : below; return this.y = (side.top + side.bottom) / 2, this.scan(positions, getRects) } if (closestDx) { if (above && above.bottom > closestRect.top) return this.y = above.bottom - 1, this.scan(positions, getRects); if (below && below.top < closestRect.bottom) return this.y = below.top + 1, this.scan(positions, getRects) } let ltr = (bidi ? this.dirAt(positions[closestI], 1) : this.baseDir) == 0; return { i: closestI, after: this.x > (closestRect.left + closestRect.right) / 2 == ltr } } scanText(tile, offset) { let positions = []; for (let i2 = 0; i2 < tile.length; i2 = findClusterBreak2(tile.text, i2))positions.push(offset + i2); positions.push(offset + tile.length); let scan = this.scan(positions, i2 => { let off = positions[i2] - offset, end = positions[i2 + 1] - offset; return textRange(tile.dom, off, end).getClientRects() }); return scan.after ? new PosAssoc(positions[scan.i + 1], -1) : new PosAssoc(positions[scan.i], 1) } scanTile(tile, offset) { if (!tile.length) return new PosAssoc(offset, 1); if (tile.children.length == 1) { let child2 = tile.children[0]; if (child2.isText()) return this.scanText(child2, offset); if (child2.isComposite()) return this.scanTile(child2, offset) } let positions = [offset]; for (let i2 = 0, pos2 = offset; i2 < tile.children.length; i2++)positions.push(pos2 += tile.children[i2].length); let scan = this.scan(positions, i2 => { let child2 = tile.children[i2]; return child2.flags & 48 ? null : (child2.dom.nodeType == 1 ? child2.dom : textRange(child2.dom, 0, child2.length)).getClientRects() }), child = tile.children[scan.i], pos = positions[scan.i]; return child.isText() ? this.scanText(child, pos) : child.isComposite() ? this.scanTile(child, pos) : scan.after ? new PosAssoc(positions[scan.i + 1], -1) : new PosAssoc(pos, 1) } }; var LineBreakPlaceholder = "\uFFFF", DOMReader = class { constructor(points, view) { this.points = points; this.view = view; this.lineSeparator = view.state.facet(EditorState.lineSeparator) } points; view; text = ""; lineSeparator; append(text) { this.text += text } lineBreak() { this.text += LineBreakPlaceholder } readRange(start, end) { if (!start) return this; let parent = start.parentNode; for (let cur = start; ;) { this.findPointBefore(parent, cur); let oldLen = this.text.length; this.readNode(cur); let tile = Tile.get(cur), next = cur.nextSibling; if (next == end) { tile?.breakAfter && !next && parent != this.view.contentDOM && this.lineBreak(); break } let nextTile = Tile.get(next); (tile && nextTile ? tile.breakAfter : (tile ? tile.breakAfter : isBlockElement(cur)) || isBlockElement(next) && (cur.nodeName != "BR" || tile?.isWidget()) && this.text.length > oldLen) && !isEmptyToEnd(next, end) && this.lineBreak(), cur = next } return this.findPointBefore(parent, end), this } readTextNode(node) { let text = node.nodeValue; for (let point of this.points) point.node == node && (point.pos = this.text.length + Math.min(point.offset, text.length)); for (let off = 0, re = this.lineSeparator ? null : /\r\n?|\n/g; ;) { let nextBreak = -1, breakSize = 1, m; if (this.lineSeparator ? (nextBreak = text.indexOf(this.lineSeparator, off), breakSize = this.lineSeparator.length) : (m = re.exec(text)) && (nextBreak = m.index, breakSize = m[0].length), this.append(text.slice(off, nextBreak < 0 ? text.length : nextBreak)), nextBreak < 0) break; if (this.lineBreak(), breakSize > 1) for (let point of this.points) point.node == node && point.pos > this.text.length && (point.pos -= breakSize - 1); off = nextBreak + breakSize } } readNode(node) { let tile = Tile.get(node), fromView = tile && tile.overrideDOMText; if (fromView != null) { this.findPointInside(node, fromView.length); for (let i2 = fromView.iter(); !i2.next().done;)i2.lineBreak ? this.lineBreak() : this.append(i2.value) } else node.nodeType == 3 ? this.readTextNode(node) : node.nodeName == "BR" ? node.nextSibling && this.lineBreak() : node.nodeType == 1 && this.readRange(node.firstChild, null) } findPointBefore(node, next) { for (let point of this.points) point.node == node && node.childNodes[point.offset] == next && (point.pos = this.text.length) } findPointInside(node, length) { for (let point of this.points) (node.nodeType == 3 ? point.node == node : node.contains(point.node)) && (point.pos = this.text.length + (isAtEnd(node, point.node, point.offset) ? length : 0)) } }; function isAtEnd(parent, node, offset) { for (; ;) { if (!node || offset < maxOffset(node)) return !1; if (node == parent) return !0; offset = domIndex(node) + 1, node = node.parentNode } } function isEmptyToEnd(node, end) { let widgets; for (; !(node == end || !node); node = node.nextSibling) { let view = Tile.get(node); if (!view?.isWidget()) return !1; view && (widgets || (widgets = [])).push(view) } if (widgets) { for (let w of widgets) if (w.overrideDOMText?.length) return !1 } return !0 } var DOMPoint = class { constructor(node, offset) { this.node = node; this.offset = offset } node; offset; pos = -1 }; var DOMChange = class { constructor(view, start, end, typeOver) { this.typeOver = typeOver; this.domChanged = start > -1; let { impreciseHead: iHead, impreciseAnchor: iAnchor } = view.docView, curSel = view.state.selection; if (view.state.readOnly && start > -1) this.newSel = null; else if (start > -1 && (this.bounds = domBoundsAround(view.docView.tile, start, end, 0))) { let selPoints = iHead || iAnchor ? [] : selectionPoints(view), reader = new DOMReader(selPoints, view); reader.readRange(this.bounds.startDOM, this.bounds.endDOM), this.text = reader.text, this.newSel = selectionFromPoints(selPoints, this.bounds.from) } else { let domSel = view.observer.selectionRange, head = iHead && iHead.node == domSel.focusNode && iHead.offset == domSel.focusOffset || !contains(view.contentDOM, domSel.focusNode) ? curSel.main.head : view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset), anchor = iAnchor && iAnchor.node == domSel.anchorNode && iAnchor.offset == domSel.anchorOffset || !contains(view.contentDOM, domSel.anchorNode) ? curSel.main.anchor : view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset), vp = view.viewport; if ((browser_default.ios || browser_default.chrome) && curSel.main.empty && head != anchor && (vp.from > 0 || vp.to < view.state.doc.length)) { let from = Math.min(head, anchor), to = Math.max(head, anchor), offFrom = vp.from - from, offTo = vp.to - to; (offFrom == 0 || offFrom == 1 || from == 0) && (offTo == 0 || offTo == -1 || to == view.state.doc.length) && (head = 0, anchor = view.state.doc.length) } if (view.inputState.composing > -1 && curSel.ranges.length > 1) this.newSel = curSel.replaceRange(EditorSelection.range(anchor, head)); else if (view.lineWrapping && anchor == head && !(curSel.main.empty && curSel.main.head == head) && view.inputState.lastTouchTime > Date.now() - 100) { let before = view.coordsAtPos(head, -1), assoc = 0; before && (assoc = view.inputState.lastTouchY <= before.bottom ? -1 : 1), this.newSel = EditorSelection.create([EditorSelection.cursor(head, assoc)]) } else this.newSel = EditorSelection.single(anchor, head) } } typeOver; bounds = null; text = ""; newSel; domChanged }; function domBoundsAround(tile, from, to, offset) { if (tile.isComposite()) { let fromI = -1, fromStart = -1, toI = -1, toEnd = -1; for (let i2 = 0, pos = offset, prevEnd = offset; i2 < tile.children.length; i2++) { let child = tile.children[i2], end = pos + child.length; if (pos < from && end > to) return domBoundsAround(child, from, to, pos); if (end >= from && fromI == -1 && (fromI = i2, fromStart = pos), pos > to && child.dom.parentNode == tile.dom) { toI = i2, toEnd = prevEnd; break } prevEnd = end, pos = end + child.breakAfter } return { from: fromStart, to: toEnd < 0 ? offset + tile.length : toEnd, startDOM: (fromI ? tile.children[fromI - 1].dom.nextSibling : null) || tile.dom.firstChild, endDOM: toI < tile.children.length && toI >= 0 ? tile.children[toI].dom : null } } else return tile.isText() ? { from: offset, to: offset + tile.length, startDOM: tile.dom, endDOM: tile.dom.nextSibling } : null } function applyDOMChange(view, domChange) { + let change, { newSel } = domChange, { state } = view, sel = state.selection.main, lastKey = view.inputState.lastKeyTime > Date.now() - 100 ? view.inputState.lastKeyCode : -1; if (domChange.bounds) { let { from, to } = domChange.bounds, preferredPos = sel.from, preferredSide = null; (lastKey === 8 || browser_default.android && domChange.text.length < to - from) && (preferredPos = sel.to, preferredSide = "end"); let cmp = state.doc.sliceString(from, to, LineBreakPlaceholder), selEnd, diff; !sel.empty && sel.from >= from && sel.to <= to && (domChange.typeOver || cmp != domChange.text) && cmp.slice(0, sel.from - from) == domChange.text.slice(0, sel.from - from) && cmp.slice(sel.to - from) == domChange.text.slice(selEnd = domChange.text.length - (cmp.length - (sel.to - from))) ? change = { from: sel.from, to: sel.to, insert: Text.of(domChange.text.slice(sel.from - from, selEnd).split(LineBreakPlaceholder)) } : (diff = findDiff(cmp, domChange.text, preferredPos - from, preferredSide)) && (browser_default.chrome && lastKey == 13 && diff.toB == diff.from + 2 && domChange.text.slice(diff.from, diff.toB) == LineBreakPlaceholder + LineBreakPlaceholder && diff.toB--, change = { from: from + diff.from, to: from + diff.toA, insert: Text.of(domChange.text.slice(diff.from, diff.toB).split(LineBreakPlaceholder)) }) } else newSel && (!view.hasFocus && state.facet(editable) || sameSelPos(newSel, sel)) && (newSel = null); if (!change && !newSel) return !1; if ((browser_default.mac || browser_default.android) && change && change.from == change.to && change.from == sel.head - 1 && /^\. ?$/.test(change.insert.toString()) && view.contentDOM.getAttribute("autocorrect") == "off" ? (newSel && change.insert.length == 2 && (newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1)), change = { from: change.from, to: change.to, insert: Text.of([change.insert.toString().replace(".", " ")]) }) : state.doc.lineAt(sel.from).to < sel.to && view.docView.lineHasWidget(sel.to) && view.inputState.insertingTextAt > Date.now() - 50 ? change = { from: sel.from, to: sel.to, insert: state.toText(view.inputState.insertingText) } : browser_default.chrome && change && change.from == change.to && change.from == sel.head && change.insert.toString() == ` + `&& view.lineWrapping && (newSel && (newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1)), change = { from: sel.from, to: sel.to, insert: Text.of([" "]) }), change) return applyDOMChangeInner(view, change, newSel, lastKey); if (newSel && !sameSelPos(newSel, sel)) { let scrollIntoView2 = !1, userEvent = "select"; return view.inputState.lastSelectionTime > Date.now() - 50 && (view.inputState.lastSelectionOrigin == "select" && (scrollIntoView2 = !0), userEvent = view.inputState.lastSelectionOrigin, userEvent == "select.pointer" && (newSel = skipAtomsForSelection(state.facet(atomicRanges).map(f => f(view)), newSel))), view.dispatch({ selection: newSel, scrollIntoView: scrollIntoView2, userEvent }), !0 } else return !1 +} function applyDOMChangeInner(view, change, newSel, lastKey = -1) { if (browser_default.ios && view.inputState.flushIOSKey(change)) return !0; let sel = view.state.selection.main; if (browser_default.android && (change.to == sel.to && (change.from == sel.from || change.from == sel.from - 1 && view.state.sliceDoc(change.from, sel.from) == " ") && change.insert.length == 1 && change.insert.lines == 2 && dispatchKey(view.contentDOM, "Enter", 13) || (change.from == sel.from - 1 && change.to == sel.to && change.insert.length == 0 || lastKey == 8 && change.insert.length < change.to - change.from && change.to > sel.head) && dispatchKey(view.contentDOM, "Backspace", 8) || change.from == sel.from && change.to == sel.to + 1 && change.insert.length == 0 && dispatchKey(view.contentDOM, "Delete", 46))) return !0; let text = change.insert.toString(); view.inputState.composing >= 0 && view.inputState.composing++; let defaultTr, defaultInsert = () => defaultTr || (defaultTr = applyDefaultInsert(view, change, newSel)); return view.state.facet(inputHandler).some(h => h(view, change.from, change.to, text, defaultInsert)) || view.dispatch(defaultInsert()), !0 } function applyDefaultInsert(view, change, newSel) { let tr, startState = view.state, sel = startState.selection.main, inAtomic = -1; if (change.from == change.to && change.from < sel.from || change.from > sel.to) { let side = change.from < sel.from ? -1 : 1, pos = side < 0 ? sel.from : sel.to, moved = skipAtomicRanges(startState.facet(atomicRanges).map(f => f(view)), pos, side); change.from == moved && (inAtomic = moved) } if (inAtomic > -1) tr = { changes: change, selection: EditorSelection.cursor(change.from + change.insert.length, -1) }; else if (change.from >= sel.from && change.to <= sel.to && change.to - change.from >= (sel.to - sel.from) / 3 && (!newSel || newSel.main.empty && newSel.main.from == change.from + change.insert.length) && view.inputState.composing < 0) { let before = sel.from < change.from ? startState.sliceDoc(sel.from, change.from) : "", after = sel.to > change.to ? startState.sliceDoc(change.to, sel.to) : ""; tr = startState.replaceSelection(view.state.toText(before + change.insert.sliceString(0, void 0, view.state.lineBreak) + after)) } else { let changes = startState.changes(change), mainSel = newSel && newSel.main.to <= changes.newLength ? newSel.main : void 0; if (startState.selection.ranges.length > 1 && (view.inputState.composing >= 0 || view.inputState.compositionPendingChange) && change.to <= sel.to + 10 && change.to >= sel.to - 10) { let replaced = view.state.sliceDoc(change.from, change.to), compositionRange, composition = newSel && findCompositionNode(view, newSel.main.head); if (composition) { let dLen = change.insert.length - (change.to - change.from); compositionRange = { from: composition.from, to: composition.to - dLen } } else compositionRange = view.state.doc.lineAt(sel.head); let offset = sel.to - change.to; tr = startState.changeByRange(range => { if (range.from == sel.from && range.to == sel.to) return { changes, range: mainSel || range.map(changes) }; let to = range.to - offset, from = to - replaced.length; if (view.state.sliceDoc(from, to) != replaced || to >= compositionRange.from && from <= compositionRange.to) return { range }; let rangeChanges = startState.changes({ from, to, insert: change.insert }), selOff = range.to - sel.to; return { changes: rangeChanges, range: mainSel ? EditorSelection.range(Math.max(0, mainSel.anchor + selOff), Math.max(0, mainSel.head + selOff)) : range.map(rangeChanges) } }) } else tr = { changes, selection: mainSel && startState.selection.replaceRange(mainSel) } } let userEvent = "input.type"; return (view.composing || view.inputState.compositionPendingChange && view.inputState.compositionEndedAt > Date.now() - 50) && (view.inputState.compositionPendingChange = !1, userEvent += ".compose", view.inputState.compositionFirstChange && (userEvent += ".start", view.inputState.compositionFirstChange = !1)), startState.update(tr, { userEvent, scrollIntoView: !0 }) } function findDiff(a, b, preferredPos, preferredSide) { let minLen = Math.min(a.length, b.length), from = 0; for (; from < minLen && a.charCodeAt(from) == b.charCodeAt(from);)from++; if (from == minLen && a.length == b.length) return null; let toA = a.length, toB = b.length; for (; toA > 0 && toB > 0 && a.charCodeAt(toA - 1) == b.charCodeAt(toB - 1);)toA--, toB--; if (preferredSide == "end") { let adjust = Math.max(0, from - Math.min(toA, toB)); preferredPos -= toA + adjust - from } if (toA < from && a.length < b.length) { let move = preferredPos <= from && preferredPos >= toA ? from - preferredPos : 0; from -= move, toB = from + (toB - toA), toA = from } else if (toB < from) { let move = preferredPos <= from && preferredPos >= toB ? from - preferredPos : 0; from -= move, toA = from + (toA - toB), toB = from } return { from, toA, toB } } function selectionPoints(view) { let result = []; if (view.root.activeElement != view.contentDOM) return result; let { anchorNode, anchorOffset, focusNode, focusOffset } = view.observer.selectionRange; return anchorNode && (result.push(new DOMPoint(anchorNode, anchorOffset)), (focusNode != anchorNode || focusOffset != anchorOffset) && result.push(new DOMPoint(focusNode, focusOffset))), result } function selectionFromPoints(points, base2) { if (points.length == 0) return null; let anchor = points[0].pos, head = points.length == 2 ? points[1].pos : anchor; return anchor > -1 && head > -1 ? EditorSelection.single(anchor + base2, head + base2) : null } function sameSelPos(selection, range) { return range.head == selection.main.head && range.anchor == selection.main.anchor } var InputState = class { constructor(view) { this.view = view; this.handleEvent = this.handleEvent.bind(this), this.notifiedFocused = view.hasFocus, browser_default.safari && view.contentDOM.addEventListener("input", () => null), browser_default.gecko && firefoxCopyCutHack(view.contentDOM.ownerDocument) } view; lastKeyCode = 0; lastKeyTime = 0; lastTouchTime = 0; lastTouchX = 0; lastTouchY = 0; lastFocusTime = 0; lastScrollTop = 0; lastScrollLeft = 0; lastWheelEvent = 0; pendingIOSKey = void 0; tabFocusMode = -1; lastSelectionOrigin = null; lastSelectionTime = 0; lastContextMenu = 0; scrollHandlers = []; handlers = Object.create(null); composing = -1; compositionFirstChange = null; compositionEndedAt = 0; compositionPendingKey = !1; compositionPendingChange = !1; insertingText = ""; insertingTextAt = 0; mouseSelection = null; draggedContent = null; notifiedFocused; setSelectionOrigin(origin) { this.lastSelectionOrigin = origin, this.lastSelectionTime = Date.now() } handleEvent(event) { !eventBelongsToEditor(this.view, event) || this.ignoreDuringComposition(event) || event.type == "keydown" && this.keydown(event) || (this.view.updateState != 0 ? Promise.resolve().then(() => this.runHandlers(event.type, event)) : this.runHandlers(event.type, event)) } runHandlers(type, event) { let handlers2 = this.handlers[type]; if (handlers2) { for (let observer of handlers2.observers) observer(this.view, event); for (let handler of handlers2.handlers) { if (event.defaultPrevented) break; if (handler(this.view, event)) { event.preventDefault(); break } } } } ensureHandlers(plugins) { let handlers2 = computeHandlers(plugins), prev = this.handlers, dom = this.view.contentDOM; for (let type in handlers2) if (type != "scroll") { let passive = !handlers2[type].handlers.length, exists = prev[type]; exists && passive != !exists.handlers.length && (dom.removeEventListener(type, this.handleEvent), exists = null), exists || dom.addEventListener(type, this.handleEvent, { passive }) } for (let type in prev) type != "scroll" && !handlers2[type] && dom.removeEventListener(type, this.handleEvent); this.handlers = handlers2 } keydown(event) { if (this.lastKeyCode = event.keyCode, this.lastKeyTime = Date.now(), event.keyCode == 9 && this.tabFocusMode > -1 && (!this.tabFocusMode || Date.now() <= this.tabFocusMode)) return !0; if (this.tabFocusMode > 0 && event.keyCode != 27 && modifierCodes.indexOf(event.keyCode) < 0 && (this.tabFocusMode = -1), browser_default.android && browser_default.chrome && !event.synthetic && (event.keyCode == 13 || event.keyCode == 8)) return this.view.observer.delayAndroidKey(event.key, event.keyCode), !0; let pending; return browser_default.ios && !event.synthetic && !event.altKey && !event.metaKey && !event.shiftKey && ((pending = PendingKeys.find(key => key.keyCode == event.keyCode)) && !event.ctrlKey || EmacsyPendingKeys.indexOf(event.key) > -1 && event.ctrlKey) ? (this.pendingIOSKey = pending || event, setTimeout(() => this.flushIOSKey(), 250), !0) : (event.keyCode != 229 && this.view.observer.forceFlush(), !1) } flushIOSKey(change) { let key = this.pendingIOSKey; return !key || key.key == "Enter" && change && change.from < change.to && /^\S+$/.test(change.insert.toString()) ? !1 : (this.pendingIOSKey = void 0, dispatchKey(this.view.contentDOM, key.key, key.keyCode, key instanceof KeyboardEvent ? key : void 0)) } ignoreDuringComposition(event) { return !/^key/.test(event.type) || event.synthetic ? !1 : this.composing > 0 ? !0 : browser_default.safari && !browser_default.ios && this.compositionPendingKey && Date.now() - this.compositionEndedAt < 100 ? (this.compositionPendingKey = !1, !0) : !1 } startMouseSelection(mouseSelection) { this.mouseSelection && this.mouseSelection.destroy(), this.mouseSelection = mouseSelection } update(update) { this.view.observer.update(update), this.mouseSelection && this.mouseSelection.update(update), this.draggedContent && update.docChanged && (this.draggedContent = this.draggedContent.map(update.changes)), update.transactions.length && (this.lastKeyCode = this.lastSelectionTime = 0) } destroy() { this.mouseSelection && this.mouseSelection.destroy() } }; function bindHandler(plugin2, handler) { return (view, event) => { try { return handler.call(plugin2, event, view) } catch (e) { logException(view.state, e) } } } function computeHandlers(plugins) { let result = Object.create(null); function record(type) { return result[type] || (result[type] = { observers: [], handlers: [] }) } for (let plugin2 of plugins) { let spec = plugin2.spec, handlers2 = spec && spec.plugin.domEventHandlers, observers2 = spec && spec.plugin.domEventObservers; if (handlers2) for (let type in handlers2) { let f = handlers2[type]; f && record(type).handlers.push(bindHandler(plugin2.value, f)) } if (observers2) for (let type in observers2) { let f = observers2[type]; f && record(type).observers.push(bindHandler(plugin2.value, f)) } } for (let type in handlers) record(type).handlers.push(handlers[type]); for (let type in observers) record(type).observers.push(observers[type]); return result } var PendingKeys = [{ key: "Backspace", keyCode: 8, inputType: "deleteContentBackward" }, { key: "Enter", keyCode: 13, inputType: "insertParagraph" }, { key: "Enter", keyCode: 13, inputType: "insertLineBreak" }, { key: "Delete", keyCode: 46, inputType: "deleteContentForward" }], EmacsyPendingKeys = "dthko", modifierCodes = [16, 17, 18, 20, 91, 92, 224, 225], dragScrollMargin = 6; function dragScrollSpeed(dist2) { return Math.max(0, dist2) * .7 + 8 } function dist(a, b) { return Math.max(Math.abs(a.clientX - b.clientX), Math.abs(a.clientY - b.clientY)) } var MouseSelection = class { constructor(view, startEvent, style, mustSelect) { this.view = view; this.startEvent = startEvent; this.style = style; this.mustSelect = mustSelect; this.lastEvent = startEvent, this.scrollParents = scrollableParents(view.contentDOM), this.atoms = view.state.facet(atomicRanges).map(f => f(view)); let doc2 = view.contentDOM.ownerDocument; doc2.addEventListener("mousemove", this.move = this.move.bind(this)), doc2.addEventListener("mouseup", this.up = this.up.bind(this)), this.extend = startEvent.shiftKey, this.multiple = view.state.facet(EditorState.allowMultipleSelections) && addsSelectionRange(view, startEvent), this.dragging = isInPrimarySelection(view, startEvent) && getClickType(startEvent) == 1 ? null : !1 } view; startEvent; style; mustSelect; dragging; extend; multiple; lastEvent; scrollParents; scrollSpeed = { x: 0, y: 0 }; scrolling = -1; atoms; start(event) { this.dragging === !1 && this.select(event) } move(event) { if (event.buttons == 0) return this.destroy(); if (this.dragging || this.dragging == null && dist(this.startEvent, event) < 10) return; this.select(this.lastEvent = event); let sx = 0, sy = 0, left = 0, top2 = 0, right = this.view.win.innerWidth, bottom = this.view.win.innerHeight; this.scrollParents.x && ({ left, right } = this.scrollParents.x.getBoundingClientRect()), this.scrollParents.y && ({ top: top2, bottom } = this.scrollParents.y.getBoundingClientRect()); let margins = getScrollMargins(this.view); event.clientX - margins.left <= left + dragScrollMargin ? sx = -dragScrollSpeed(left - event.clientX) : event.clientX + margins.right >= right - dragScrollMargin && (sx = dragScrollSpeed(event.clientX - right)), event.clientY - margins.top <= top2 + dragScrollMargin ? sy = -dragScrollSpeed(top2 - event.clientY) : event.clientY + margins.bottom >= bottom - dragScrollMargin && (sy = dragScrollSpeed(event.clientY - bottom)), this.setScrollSpeed(sx, sy) } up(event) { this.dragging == null && this.select(this.lastEvent), this.dragging || event.preventDefault(), this.destroy() } destroy() { this.setScrollSpeed(0, 0); let doc2 = this.view.contentDOM.ownerDocument; doc2.removeEventListener("mousemove", this.move), doc2.removeEventListener("mouseup", this.up), this.view.inputState.mouseSelection = this.view.inputState.draggedContent = null } setScrollSpeed(sx, sy) { this.scrollSpeed = { x: sx, y: sy }, sx || sy ? this.scrolling < 0 && (this.scrolling = setInterval(() => this.scroll(), 50)) : this.scrolling > -1 && (clearInterval(this.scrolling), this.scrolling = -1) } scroll() { let { x, y } = this.scrollSpeed; x && this.scrollParents.x && (this.scrollParents.x.scrollLeft += x, x = 0), y && this.scrollParents.y && (this.scrollParents.y.scrollTop += y, y = 0), (x || y) && this.view.win.scrollBy(x, y), this.dragging === !1 && this.select(this.lastEvent) } select(event) { let { view } = this, selection = skipAtomsForSelection(this.atoms, this.style.get(event, this.extend, this.multiple)); (this.mustSelect || !selection.eq(view.state.selection, this.dragging === !1)) && this.view.dispatch({ selection, userEvent: "select.pointer" }), this.mustSelect = !1 } update(update) { update.transactions.some(tr => tr.isUserEvent("input.type")) ? this.destroy() : this.style.update(update) && setTimeout(() => this.select(this.lastEvent), 20) } }; function addsSelectionRange(view, event) { let facet = view.state.facet(clickAddsSelectionRange); return facet.length ? facet[0](event) : browser_default.mac ? event.metaKey : event.ctrlKey } function dragMovesSelection2(view, event) { let facet = view.state.facet(dragMovesSelection); return facet.length ? facet[0](event) : browser_default.mac ? !event.altKey : !event.ctrlKey } function isInPrimarySelection(view, event) { let { main } = view.state.selection; if (main.empty) return !1; let sel = getSelection(view.root); if (!sel || sel.rangeCount == 0) return !0; let rects = sel.getRangeAt(0).getClientRects(); for (let i2 = 0; i2 < rects.length; i2++) { let rect = rects[i2]; if (rect.left <= event.clientX && rect.right >= event.clientX && rect.top <= event.clientY && rect.bottom >= event.clientY) return !0 } return !1 } function eventBelongsToEditor(view, event) { if (!event.bubbles) return !0; if (event.defaultPrevented) return !1; for (let node = event.target, tile; node != view.contentDOM; node = node.parentNode)if (!node || node.nodeType == 11 || (tile = Tile.get(node)) && tile.isWidget() && !tile.isHidden && tile.widget.ignoreEvent(event)) return !1; return !0 } var handlers = Object.create(null), observers = Object.create(null), brokenClipboardAPI = browser_default.ie && browser_default.ie_version < 15 || browser_default.ios && browser_default.webkit_version < 604; function capturePaste(view) { let parent = view.dom.parentNode; if (!parent) return; let target = parent.appendChild(document.createElement("textarea")); target.style.cssText = "position: fixed; left: -10000px; top: 10px", target.focus(), setTimeout(() => { view.focus(), target.remove(), doPaste(view, target.value) }, 50) } function textFilter(state, facet, text) { for (let filter of state.facet(facet)) text = filter(text, state); return text } function doPaste(view, input) { input = textFilter(view.state, clipboardInputFilter, input); let { state } = view, changes, i2 = 1, text = state.toText(input), byLine = text.lines == state.selection.ranges.length; if (lastLinewiseCopy != null && state.selection.ranges.every(r => r.empty) && lastLinewiseCopy == text.toString()) { let lastLine = -1; changes = state.changeByRange(range => { let line = state.doc.lineAt(range.from); if (line.from == lastLine) return { range }; lastLine = line.from; let insert2 = state.toText((byLine ? text.line(i2++).text : input) + state.lineBreak); return { changes: { from: line.from, insert: insert2 }, range: EditorSelection.cursor(range.from + insert2.length) } }) } else byLine ? changes = state.changeByRange(range => { let line = text.line(i2++); return { changes: { from: range.from, to: range.to, insert: line.text }, range: EditorSelection.cursor(range.from + line.length) } }) : changes = state.replaceSelection(text); view.dispatch(changes, { userEvent: "input.paste", scrollIntoView: !0 }) } observers.scroll = view => { view.inputState.lastScrollTop = view.scrollDOM.scrollTop, view.inputState.lastScrollLeft = view.scrollDOM.scrollLeft }; observers.wheel = observers.mousewheel = view => { view.inputState.lastWheelEvent = Date.now() }; handlers.keydown = (view, event) => (view.inputState.setSelectionOrigin("select"), event.keyCode == 27 && view.inputState.tabFocusMode != 0 && (view.inputState.tabFocusMode = Date.now() + 2e3), !1); observers.touchstart = (view, e) => { let iState = view.inputState, touch = e.targetTouches[0]; iState.lastTouchTime = Date.now(), touch && (iState.lastTouchX = touch.clientX, iState.lastTouchY = touch.clientY), iState.setSelectionOrigin("select.pointer") }; observers.touchmove = view => { view.inputState.setSelectionOrigin("select.pointer") }; handlers.mousedown = (view, event) => { if (view.observer.flush(), view.inputState.lastTouchTime > Date.now() - 2e3) return !1; let style = null; for (let makeStyle of view.state.facet(mouseSelectionStyle)) if (style = makeStyle(view, event), style) break; if (!style && event.button == 0 && (style = basicMouseSelection(view, event)), style) { let mustFocus = !view.hasFocus; view.inputState.startMouseSelection(new MouseSelection(view, event, style, mustFocus)), mustFocus && view.observer.ignore(() => { focusPreventScroll(view.contentDOM); let active = view.root.activeElement; active && !active.contains(view.contentDOM) && active.blur() }); let mouseSel = view.inputState.mouseSelection; if (mouseSel) return mouseSel.start(event), mouseSel.dragging === !1 } else view.inputState.setSelectionOrigin("select.pointer"); return !1 }; function rangeForClick(view, pos, bias, type) { if (type == 1) return EditorSelection.cursor(pos, bias); if (type == 2) return groupAt(view.state, pos, bias); { let visual = view.docView.lineAt(pos, bias), line = view.state.doc.lineAt(visual ? visual.posAtEnd : pos), from = visual ? visual.posAtStart : line.from, to = visual ? visual.posAtEnd : line.to; return to < view.state.doc.length && to == line.to && to++, EditorSelection.range(from, to) } } var BadMouseDetail = browser_default.ie && browser_default.ie_version <= 11, lastMouseDown = null, lastMouseDownCount = 0, lastMouseDownTime = 0; function getClickType(event) { if (!BadMouseDetail) return event.detail; let last = lastMouseDown, lastTime = lastMouseDownTime; return lastMouseDown = event, lastMouseDownTime = Date.now(), lastMouseDownCount = !last || lastTime > Date.now() - 400 && Math.abs(last.clientX - event.clientX) < 2 && Math.abs(last.clientY - event.clientY) < 2 ? (lastMouseDownCount + 1) % 3 : 1 } function basicMouseSelection(view, event) { let start = view.posAndSideAtCoords({ x: event.clientX, y: event.clientY }, !1), type = getClickType(event), startSel = view.state.selection; return { update(update) { update.docChanged && (start.pos = update.changes.mapPos(start.pos), startSel = startSel.map(update.changes)) }, get(event2, extend, multiple) { let cur = view.posAndSideAtCoords({ x: event2.clientX, y: event2.clientY }, !1), removed, range = rangeForClick(view, cur.pos, cur.assoc, type); if (start.pos != cur.pos && !extend) { let startRange = rangeForClick(view, start.pos, start.assoc, type), from = Math.min(startRange.from, range.from), to = Math.max(startRange.to, range.to); range = from < range.from ? EditorSelection.range(from, to, range.assoc) : EditorSelection.range(to, from, range.assoc) } return extend ? startSel.replaceRange(startSel.main.extend(range.from, range.to, range.assoc)) : multiple && type == 1 && startSel.ranges.length > 1 && (removed = removeRangeAround(startSel, cur.pos)) ? removed : multiple ? startSel.addRange(range) : EditorSelection.create([range]) } } } function removeRangeAround(sel, pos) { for (let i2 = 0; i2 < sel.ranges.length; i2++) { let { from, to } = sel.ranges[i2]; if (from <= pos && to >= pos) return EditorSelection.create(sel.ranges.slice(0, i2).concat(sel.ranges.slice(i2 + 1)), sel.mainIndex == i2 ? 0 : sel.mainIndex - (sel.mainIndex > i2 ? 1 : 0)) } return null } handlers.dragstart = (view, event) => { let { selection: { main: range } } = view.state; if (event.target.draggable) { let tile = view.docView.tile.nearest(event.target); if (tile && tile.isWidget()) { let from = tile.posAtStart, to = from + tile.length; (from >= range.to || to <= range.from) && (range = EditorSelection.range(from, to)) } } let { inputState } = view; return inputState.mouseSelection && (inputState.mouseSelection.dragging = !0), inputState.draggedContent = range, event.dataTransfer && (event.dataTransfer.setData("Text", textFilter(view.state, clipboardOutputFilter, view.state.sliceDoc(range.from, range.to))), event.dataTransfer.effectAllowed = "copyMove"), !1 }; handlers.dragend = view => (view.inputState.draggedContent = null, !1); function dropText(view, event, text, direct) { if (text = textFilter(view.state, clipboardInputFilter, text), !text) return; let dropPos = view.posAtCoords({ x: event.clientX, y: event.clientY }, !1), { draggedContent } = view.inputState, del = direct && draggedContent && dragMovesSelection2(view, event) ? { from: draggedContent.from, to: draggedContent.to } : null, ins = { from: dropPos, insert: text }, changes = view.state.changes(del ? [del, ins] : ins); view.focus(), view.dispatch({ changes, selection: { anchor: changes.mapPos(dropPos, -1), head: changes.mapPos(dropPos, 1) }, userEvent: del ? "move.drop" : "input.drop" }), view.inputState.draggedContent = null } handlers.drop = (view, event) => { if (!event.dataTransfer) return !1; if (view.state.readOnly) return !0; let files = event.dataTransfer.files; if (files && files.length) { let text = Array(files.length), read = 0, finishFile = () => { ++read == files.length && dropText(view, event, text.filter(s => s != null).join(view.state.lineBreak), !1) }; for (let i2 = 0; i2 < files.length; i2++) { let reader = new FileReader; reader.onerror = finishFile, reader.onload = () => { /[\x00-\x08\x0e-\x1f]{2}/.test(reader.result) || (text[i2] = reader.result), finishFile() }, reader.readAsText(files[i2]) } return !0 } else { let text = event.dataTransfer.getData("Text"); if (text) return dropText(view, event, text, !0), !0 } return !1 }; handlers.paste = (view, event) => { if (view.state.readOnly) return !0; view.observer.flush(); let data = brokenClipboardAPI ? null : event.clipboardData; return data ? (doPaste(view, data.getData("text/plain") || data.getData("text/uri-list")), !0) : (capturePaste(view), !1) }; function captureCopy(view, text) { let parent = view.dom.parentNode; if (!parent) return; let target = parent.appendChild(document.createElement("textarea")); target.style.cssText = "position: fixed; left: -10000px; top: 10px", target.value = text, target.focus(), target.selectionEnd = text.length, target.selectionStart = 0, setTimeout(() => { target.remove(), view.focus() }, 50) } function copiedRange(state) { let content2 = [], ranges = [], linewise = !1; for (let range of state.selection.ranges) range.empty || (content2.push(state.sliceDoc(range.from, range.to)), ranges.push(range)); if (!content2.length) { let upto = -1; for (let { from } of state.selection.ranges) { let line = state.doc.lineAt(from); line.number > upto && (content2.push(line.text), ranges.push({ from: line.from, to: Math.min(state.doc.length, line.to + 1) })), upto = line.number } linewise = !0 } return { text: textFilter(state, clipboardOutputFilter, content2.join(state.lineBreak)), ranges, linewise } } var lastLinewiseCopy = null; handlers.copy = handlers.cut = (view, event) => { if (!hasSelection(view.contentDOM, view.observer.selectionRange)) return !1; let { text, ranges, linewise } = copiedRange(view.state); if (!text && !linewise) return !1; lastLinewiseCopy = linewise ? text : null, event.type == "cut" && !view.state.readOnly && view.dispatch({ changes: ranges, scrollIntoView: !0, userEvent: "delete.cut" }); let data = brokenClipboardAPI ? null : event.clipboardData; return data ? (data.clearData(), data.setData("text/plain", text), !0) : (captureCopy(view, text), !1) }; var isFocusChange = Annotation.define(); function focusChangeTransaction(state, focus) { let effects = []; for (let getEffect of state.facet(focusChangeEffect)) { let effect = getEffect(state, focus); effect && effects.push(effect) } return effects.length ? state.update({ effects, annotations: isFocusChange.of(!0) }) : null } function updateForFocusChange(view) { setTimeout(() => { let focus = view.hasFocus; if (focus != view.inputState.notifiedFocused) { let tr = focusChangeTransaction(view.state, focus); tr ? view.dispatch(tr) : view.update([]) } }, 10) } observers.focus = view => { view.inputState.lastFocusTime = Date.now(), !view.scrollDOM.scrollTop && (view.inputState.lastScrollTop || view.inputState.lastScrollLeft) && (view.scrollDOM.scrollTop = view.inputState.lastScrollTop, view.scrollDOM.scrollLeft = view.inputState.lastScrollLeft), updateForFocusChange(view) }; observers.blur = view => { view.observer.clearSelectionRange(), updateForFocusChange(view) }; observers.compositionstart = observers.compositionupdate = view => { view.observer.editContext || (view.inputState.compositionFirstChange == null && (view.inputState.compositionFirstChange = !0), view.inputState.composing < 0 && (view.inputState.composing = 0)) }; observers.compositionend = view => { view.observer.editContext || (view.inputState.composing = -1, view.inputState.compositionEndedAt = Date.now(), view.inputState.compositionPendingKey = !0, view.inputState.compositionPendingChange = view.observer.pendingRecords().length > 0, view.inputState.compositionFirstChange = null, browser_default.chrome && browser_default.android ? view.observer.flushSoon() : view.inputState.compositionPendingChange ? Promise.resolve().then(() => view.observer.flush()) : setTimeout(() => { view.inputState.composing < 0 && view.docView.hasComposition && view.update([]) }, 50)) }; observers.contextmenu = view => { view.inputState.lastContextMenu = Date.now() }; handlers.beforeinput = (view, event) => { if ((event.inputType == "insertText" || event.inputType == "insertCompositionText") && (view.inputState.insertingText = event.data, view.inputState.insertingTextAt = Date.now()), event.inputType == "insertReplacementText" && view.observer.editContext) { let text = event.dataTransfer?.getData("text/plain"), ranges = event.getTargetRanges(); if (text && ranges.length) { let r = ranges[0], from = view.posAtDOM(r.startContainer, r.startOffset), to = view.posAtDOM(r.endContainer, r.endOffset); return applyDOMChangeInner(view, { from, to, insert: view.state.toText(text) }, null), !0 } } let pending; if (browser_default.chrome && browser_default.android && (pending = PendingKeys.find(key => key.inputType == event.inputType)) && (view.observer.delayAndroidKey(pending.key, pending.keyCode), pending.key == "Backspace" || pending.key == "Delete")) { let startViewHeight = window.visualViewport?.height || 0; setTimeout(() => { (window.visualViewport?.height || 0) > startViewHeight + 10 && view.hasFocus && (view.contentDOM.blur(), view.focus()) }, 100) } return browser_default.ios && event.inputType == "deleteContentForward" && view.observer.flushSoon(), browser_default.safari && event.inputType == "insertText" && view.inputState.composing >= 0 && setTimeout(() => observers.compositionend(view, event), 20), !1 }; var appliedFirefoxHack = new Set; function firefoxCopyCutHack(doc2) { appliedFirefoxHack.has(doc2) || (appliedFirefoxHack.add(doc2), doc2.addEventListener("copy", () => { }), doc2.addEventListener("cut", () => { })) } var wrappingWhiteSpace = ["pre-wrap", "normal", "pre-line", "break-spaces"], heightChangeFlag = !1; function clearHeightChangeFlag() { heightChangeFlag = !1 } var HeightOracle = class { constructor(lineWrapping) { this.lineWrapping = lineWrapping } lineWrapping; doc = Text.empty; heightSamples = {}; lineHeight = 14; charWidth = 7; textHeight = 14; lineLength = 30; heightForGap(from, to) { let lines = this.doc.lineAt(to).number - this.doc.lineAt(from).number + 1; return this.lineWrapping && (lines += Math.max(0, Math.ceil((to - from - lines * this.lineLength * .5) / this.lineLength))), this.lineHeight * lines } heightForLine(length) { return this.lineWrapping ? (1 + Math.max(0, Math.ceil((length - this.lineLength) / Math.max(1, this.lineLength - 5)))) * this.lineHeight : this.lineHeight } setDoc(doc2) { return this.doc = doc2, this } mustRefreshForWrapping(whiteSpace) { return wrappingWhiteSpace.indexOf(whiteSpace) > -1 != this.lineWrapping } mustRefreshForHeights(lineHeights) { let newHeight = !1; for (let i2 = 0; i2 < lineHeights.length; i2++) { let h = lineHeights[i2]; h < 0 ? i2++ : this.heightSamples[Math.floor(h * 10)] || (newHeight = !0, this.heightSamples[Math.floor(h * 10)] = !0) } return newHeight } refresh(whiteSpace, lineHeight, charWidth, textHeight, lineLength, knownHeights) { let lineWrapping = wrappingWhiteSpace.indexOf(whiteSpace) > -1, changed = Math.abs(lineHeight - this.lineHeight) > .3 || this.lineWrapping != lineWrapping || Math.abs(charWidth - this.charWidth) > .1; if (this.lineWrapping = lineWrapping, this.lineHeight = lineHeight, this.charWidth = charWidth, this.textHeight = textHeight, this.lineLength = lineLength, changed) { this.heightSamples = {}; for (let i2 = 0; i2 < knownHeights.length; i2++) { let h = knownHeights[i2]; h < 0 ? i2++ : this.heightSamples[Math.floor(h * 10)] = !0 } } return changed } }, MeasuredHeights = class { constructor(from, heights) { this.from = from; this.heights = heights } from; heights; index = 0; get more() { return this.index < this.heights.length } }, BlockInfo = class _BlockInfo { constructor(from, length, top2, height, _content) { this.from = from; this.length = length; this.top = top2; this.height = height; this._content = _content } from; length; top; height; _content; 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 PointDecoration ? this._content.widget : null } get widgetLineBreaks() { return typeof this._content == "number" ? this._content : 0 } join(other) { let content2 = (Array.isArray(this._content) ? this._content : [this]).concat(Array.isArray(other._content) ? other._content : [other]); return new _BlockInfo(this.from, this.length + other.length, this.top, this.height + other.height, content2) } }, QueryType = (QueryType3 => (QueryType3[QueryType3.ByPos = 0] = "ByPos", QueryType3[QueryType3.ByHeight = 1] = "ByHeight", QueryType3[QueryType3.ByPosNoHeight = 2] = "ByPosNoHeight", QueryType3))(QueryType || {}); var Epsilon = .001, HeightMap = class _HeightMap { constructor(length, height, flags = 2) { this.length = length; this.height = height; this.flags = flags } length; height; flags; get outdated() { return (this.flags & 2) > 0 } set outdated(value) { this.flags = (value ? 2 : 0) | this.flags & -3 } setHeight(height) { this.height != height && (Math.abs(this.height - height) > Epsilon && (heightChangeFlag = !0), this.height = height) } replace(_from, _to, nodes) { return _HeightMap.of(nodes) } decomposeLeft(_to, result) { result.push(this) } decomposeRight(_from, result) { result.push(this) } applyChanges(decorations2, oldDoc, oracle, changes) { let me = this, doc2 = oracle.doc; for (let i2 = changes.length - 1; i2 >= 0; i2--) { let { fromA, toA, fromB, toB } = changes[i2], start = me.lineAt(fromA, 2, oracle.setDoc(oldDoc), 0, 0), end = start.to >= toA ? start : me.lineAt(toA, 2, oracle, 0, 0); for (toB += end.to - toA, toA = end.to; i2 > 0 && start.from <= changes[i2 - 1].toA;)fromA = changes[i2 - 1].fromA, fromB = changes[i2 - 1].fromB, i2--, fromA < start.from && (start = me.lineAt(fromA, 2, oracle, 0, 0)); fromB += start.from - fromA, fromA = start.from; let nodes = NodeBuilder.build(oracle.setDoc(doc2), decorations2, fromB, toB); me = replace(me, me.replace(fromA, toA, nodes)) } return me.updateHeight(oracle, 0) } static empty() { return new HeightMapText(0, 0, 0) } static of(nodes) { if (nodes.length == 1) return nodes[0]; let i2 = 0, j = nodes.length, before = 0, after = 0; for (; ;)if (i2 == j) if (before > after * 2) { let split = nodes[i2 - 1]; split.break ? nodes.splice(--i2, 1, split.left, null, split.right) : nodes.splice(--i2, 1, split.left, split.right), j += 1 + split.break, before -= split.size } else if (after > before * 2) { let split = nodes[j]; split.break ? nodes.splice(j, 1, split.left, null, split.right) : nodes.splice(j, 1, split.left, split.right), j += 2 + split.break, after -= split.size } else break; else if (before < after) { let next = nodes[i2++]; next && (before += next.size) } else { let next = nodes[--j]; next && (after += next.size) } let brk = 0; return nodes[i2 - 1] == null ? (brk = 1, i2--) : nodes[i2] == null && (brk = 1, j++), new HeightMapBranch(_HeightMap.of(nodes.slice(0, i2)), brk, _HeightMap.of(nodes.slice(j))) } }; function replace(old, val) { return old == val ? old : (old.constructor != val.constructor && (heightChangeFlag = !0), val) } HeightMap.prototype.size = 1; var SpaceDeco = Decoration.replace({}), HeightMapBlock = class extends HeightMap { constructor(length, height, deco) { super(length, height); this.deco = deco } deco; spaceAbove = 0; mainBlock(top2, offset) { return new BlockInfo(offset, this.length, top2 + this.spaceAbove, this.height - this.spaceAbove, this.deco || 0) } blockAt(height, _oracle, top2, offset) { return this.spaceAbove && height < top2 + this.spaceAbove ? new BlockInfo(offset, 0, top2, this.spaceAbove, SpaceDeco) : this.mainBlock(top2, offset) } lineAt(_value, _type, oracle, top2, offset) { let main = this.mainBlock(top2, offset); return this.spaceAbove ? this.blockAt(0, oracle, top2, offset).join(main) : main } forEachLine(from, to, oracle, top2, offset, f) { from <= offset + this.length && to >= offset && f(this.lineAt(0, 0, oracle, top2, offset)) } setMeasuredHeight(measured) { let next = measured.heights[measured.index++]; next < 0 ? (this.spaceAbove = -next, next = measured.heights[measured.index++]) : this.spaceAbove = 0, this.setHeight(next) } updateHeight(oracle, offset = 0, _force = !1, measured) { return measured && measured.from <= offset && measured.more && this.setMeasuredHeight(measured), this.outdated = !1, this } toString() { return `block(${this.length})` } }, HeightMapText = class _HeightMapText extends HeightMapBlock { collapsed = 0; widgetHeight = 0; breaks = 0; constructor(length, height, above) { super(length, height, null), this.spaceAbove = above } mainBlock(top2, offset) { return new BlockInfo(offset, this.length, top2 + this.spaceAbove, this.height - this.spaceAbove, this.breaks) } replace(_from, _to, nodes) { let node = nodes[0]; return nodes.length == 1 && (node instanceof _HeightMapText || node instanceof HeightMapGap && node.flags & 4) && Math.abs(this.length - node.length) < 10 ? (node instanceof HeightMapGap ? node = new _HeightMapText(node.length, this.height, this.spaceAbove) : node.height = this.height, this.outdated || (node.outdated = !1), node) : HeightMap.of(nodes) } updateHeight(oracle, offset = 0, force = !1, measured) { return measured && measured.from <= offset && measured.more ? this.setMeasuredHeight(measured) : (force || this.outdated) && (this.spaceAbove = 0, this.setHeight(Math.max(this.widgetHeight, oracle.heightForLine(this.length - this.collapsed)) + this.breaks * oracle.lineHeight)), this.outdated = !1, this } toString() { return `line(${this.length}${this.collapsed ? -this.collapsed : ""}${this.widgetHeight ? ":" + this.widgetHeight : ""})` } }, HeightMapGap = class _HeightMapGap extends HeightMap { constructor(length) { super(length, 0) } heightMetrics(oracle, offset) { let firstLine = oracle.doc.lineAt(offset).number, lastLine = oracle.doc.lineAt(offset + this.length).number, lines = lastLine - firstLine + 1, perLine, perChar = 0; if (oracle.lineWrapping) { let totalPerLine = Math.min(this.height, oracle.lineHeight * lines); perLine = totalPerLine / lines, this.length > lines + 1 && (perChar = (this.height - totalPerLine) / (this.length - lines - 1)) } else perLine = this.height / lines; return { firstLine, lastLine, perLine, perChar } } blockAt(height, oracle, top2, offset) { let { firstLine, lastLine, perLine, perChar } = this.heightMetrics(oracle, offset); if (oracle.lineWrapping) { let guess = offset + (height < oracle.lineHeight ? 0 : Math.round(Math.max(0, Math.min(1, (height - top2) / this.height)) * this.length)), line = oracle.doc.lineAt(guess), lineHeight = perLine + line.length * perChar, lineTop = Math.max(top2, height - lineHeight / 2); return new BlockInfo(line.from, line.length, lineTop, lineHeight, 0) } else { let line = Math.max(0, Math.min(lastLine - firstLine, Math.floor((height - top2) / perLine))), { from, length } = oracle.doc.line(firstLine + line); return new BlockInfo(from, length, top2 + perLine * line, perLine, 0) } } lineAt(value, type, oracle, top2, offset) { if (type == 1) return this.blockAt(value, oracle, top2, offset); if (type == 2) { let { from, to } = oracle.doc.lineAt(value); return new BlockInfo(from, to - from, 0, 0, 0) } let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset), line = oracle.doc.lineAt(value), lineHeight = perLine + line.length * perChar, linesAbove = line.number - firstLine, lineTop = top2 + perLine * linesAbove + perChar * (line.from - offset - linesAbove); return new BlockInfo(line.from, line.length, Math.max(top2, Math.min(lineTop, top2 + this.height - lineHeight)), lineHeight, 0) } forEachLine(from, to, oracle, top2, offset, f) { from = Math.max(from, offset), to = Math.min(to, offset + this.length); let { firstLine, perLine, perChar } = this.heightMetrics(oracle, offset); for (let pos = from, lineTop = top2; pos <= to;) { let line = oracle.doc.lineAt(pos); if (pos == from) { let linesAbove = line.number - firstLine; lineTop += perLine * linesAbove + perChar * (from - offset - linesAbove) } let lineHeight = perLine + perChar * line.length; f(new BlockInfo(line.from, line.length, lineTop, lineHeight, 0)), lineTop += lineHeight, pos = line.to + 1 } } replace(from, to, nodes) { let after = this.length - to; if (after > 0) { let last = nodes[nodes.length - 1]; last instanceof _HeightMapGap ? nodes[nodes.length - 1] = new _HeightMapGap(last.length + after) : nodes.push(null, new _HeightMapGap(after - 1)) } if (from > 0) { let first = nodes[0]; first instanceof _HeightMapGap ? nodes[0] = new _HeightMapGap(from + first.length) : nodes.unshift(new _HeightMapGap(from - 1), null) } return HeightMap.of(nodes) } decomposeLeft(to, result) { result.push(new _HeightMapGap(to - 1), null) } decomposeRight(from, result) { result.push(null, new _HeightMapGap(this.length - from - 1)) } updateHeight(oracle, offset = 0, force = !1, measured) { let end = offset + this.length; if (measured && measured.from <= offset + this.length && measured.more) { let nodes = [], pos = Math.max(offset, measured.from), singleHeight = -1; for (measured.from > offset && nodes.push(new _HeightMapGap(measured.from - offset - 1).updateHeight(oracle, offset)); pos <= end && measured.more;) { let len = oracle.doc.lineAt(pos).length; nodes.length && nodes.push(null); let height = measured.heights[measured.index++], above = 0; height < 0 && (above = -height, height = measured.heights[measured.index++]), singleHeight == -1 ? singleHeight = height : Math.abs(height - singleHeight) >= Epsilon && (singleHeight = -2); let line = new HeightMapText(len, height, above); line.outdated = !1, nodes.push(line), pos += len + 1 } pos <= end && nodes.push(null, new _HeightMapGap(end - pos).updateHeight(oracle, pos)); let result = HeightMap.of(nodes); return (singleHeight < 0 || Math.abs(result.height - this.height) >= Epsilon || Math.abs(singleHeight - this.heightMetrics(oracle, offset).perLine) >= Epsilon) && (heightChangeFlag = !0), replace(this, result) } else (force || this.outdated) && (this.setHeight(oracle.heightForGap(offset, offset + this.length)), this.outdated = !1); return this } toString() { return `gap(${this.length})` } }, HeightMapBranch = class extends HeightMap { constructor(left, brk, right) { super(left.length + brk + right.length, left.height + right.height, brk | (left.outdated || right.outdated ? 2 : 0)); this.left = left; this.right = right; this.size = left.size + right.size } left; right; size; get break() { return this.flags & 1 } blockAt(height, oracle, top2, offset) { let mid = top2 + this.left.height; return height < mid ? this.left.blockAt(height, oracle, top2, offset) : this.right.blockAt(height, oracle, mid, offset + this.left.length + this.break) } lineAt(value, type, oracle, top2, offset) { let rightTop = top2 + this.left.height, rightOffset = offset + this.left.length + this.break, left = type == 1 ? value < rightTop : value < rightOffset, base2 = left ? this.left.lineAt(value, type, oracle, top2, offset) : this.right.lineAt(value, type, oracle, rightTop, rightOffset); if (this.break || (left ? base2.to < rightOffset : base2.from > rightOffset)) return base2; let subQuery = type == 2 ? 2 : 0; return left ? base2.join(this.right.lineAt(rightOffset, subQuery, oracle, rightTop, rightOffset)) : this.left.lineAt(rightOffset, subQuery, oracle, top2, offset).join(base2) } forEachLine(from, to, oracle, top2, offset, f) { let rightTop = top2 + this.left.height, rightOffset = offset + this.left.length + this.break; if (this.break) from < rightOffset && this.left.forEachLine(from, to, oracle, top2, offset, f), to >= rightOffset && this.right.forEachLine(from, to, oracle, rightTop, rightOffset, f); else { let mid = this.lineAt(rightOffset, 0, oracle, top2, offset); from < mid.from && this.left.forEachLine(from, mid.from - 1, oracle, top2, offset, f), mid.to >= from && mid.from <= to && f(mid), to > mid.to && this.right.forEachLine(mid.to + 1, to, oracle, rightTop, rightOffset, f) } } replace(from, to, nodes) { let rightStart = this.left.length + this.break; if (to < rightStart) return this.balanced(this.left.replace(from, to, nodes), this.right); if (from > this.left.length) return this.balanced(this.left, this.right.replace(from - rightStart, to - rightStart, nodes)); let result = []; from > 0 && this.decomposeLeft(from, result); let left = result.length; for (let node of nodes) result.push(node); if (from > 0 && mergeGaps(result, left - 1), to < this.length) { let right = result.length; this.decomposeRight(to, result), mergeGaps(result, right) } return HeightMap.of(result) } decomposeLeft(to, result) { let left = this.left.length; if (to <= left) return this.left.decomposeLeft(to, result); result.push(this.left), this.break && (left++, to >= left && result.push(null)), to > left && this.right.decomposeLeft(to - left, result) } decomposeRight(from, result) { let left = this.left.length, right = left + this.break; if (from >= right) return this.right.decomposeRight(from - right, result); from < left && this.left.decomposeRight(from, result), this.break && from < right && result.push(null), result.push(this.right) } balanced(left, right) { return left.size > 2 * right.size || right.size > 2 * left.size ? HeightMap.of(this.break ? [left, null, right] : [left, right]) : (this.left = replace(this.left, left), this.right = replace(this.right, right), this.setHeight(left.height + right.height), this.outdated = left.outdated || right.outdated, this.size = left.size + right.size, this.length = left.length + this.break + right.length, this) } updateHeight(oracle, offset = 0, force = !1, measured) { let { left, right } = this, rightStart = offset + left.length + this.break, rebalance = null; return measured && measured.from <= offset + left.length && measured.more ? rebalance = left = left.updateHeight(oracle, offset, force, measured) : left.updateHeight(oracle, offset, force), measured && measured.from <= rightStart + right.length && measured.more ? rebalance = right = right.updateHeight(oracle, rightStart, force, measured) : right.updateHeight(oracle, rightStart, force), rebalance ? this.balanced(left, right) : (this.height = this.left.height + this.right.height, this.outdated = !1, this) } toString() { return this.left + (this.break ? " " : "-") + this.right } }; function mergeGaps(nodes, around) { let before, after; nodes[around] == null && (before = nodes[around - 1]) instanceof HeightMapGap && (after = nodes[around + 1]) instanceof HeightMapGap && nodes.splice(around - 1, 3, new HeightMapGap(before.length + 1 + after.length)) } var relevantWidgetHeight = 5, NodeBuilder = class _NodeBuilder { constructor(pos, oracle) { this.pos = pos; this.oracle = oracle; this.writtenTo = pos } pos; oracle; nodes = []; writtenTo; lineStart = -1; lineEnd = -1; covering = null; get isCovered() { return this.covering && this.nodes[this.nodes.length - 1] == this.covering } span(_from, to) { if (this.lineStart > -1) { let end = Math.min(to, this.lineEnd), last = this.nodes[this.nodes.length - 1]; last instanceof HeightMapText ? last.length += end - this.pos : (end > this.pos || !this.isCovered) && this.nodes.push(new HeightMapText(end - this.pos, -1, 0)), this.writtenTo = end, to > end && (this.nodes.push(null), this.writtenTo++, this.lineStart = -1) } this.pos = to } point(from, to, deco) { if (from < to || deco.heightRelevant) { let height = deco.widget ? deco.widget.estimatedHeight : 0, breaks = deco.widget ? deco.widget.lineBreaks : 0; height < 0 && (height = this.oracle.lineHeight); let len = to - from; deco.block ? this.addBlock(new HeightMapBlock(len, height, deco)) : (len || breaks || height >= relevantWidgetHeight) && this.addLineDeco(height, breaks, len) } else to > from && this.span(from, to); this.lineEnd > -1 && this.lineEnd < this.pos && (this.lineEnd = this.oracle.doc.lineAt(this.pos).to) } enterLine() { if (this.lineStart > -1) return; let { from, to } = this.oracle.doc.lineAt(this.pos); this.lineStart = from, this.lineEnd = to, this.writtenTo < from && ((this.writtenTo < from - 1 || this.nodes[this.nodes.length - 1] == null) && this.nodes.push(this.blankContent(this.writtenTo, from - 1)), this.nodes.push(null)), this.pos > from && this.nodes.push(new HeightMapText(this.pos - from, -1, 0)), this.writtenTo = this.pos } blankContent(from, to) { let gap = new HeightMapGap(to - from); return this.oracle.doc.lineAt(from).to == to && (gap.flags |= 4), gap } ensureLine() { this.enterLine(); let last = this.nodes.length ? this.nodes[this.nodes.length - 1] : null; if (last instanceof HeightMapText) return last; let line = new HeightMapText(0, -1, 0); return this.nodes.push(line), line } addBlock(block) { this.enterLine(); let deco = block.deco; deco && deco.startSide > 0 && !this.isCovered && this.ensureLine(), this.nodes.push(block), this.writtenTo = this.pos = this.pos + block.length, deco && deco.endSide > 0 && (this.covering = block) } addLineDeco(height, breaks, length) { let line = this.ensureLine(); line.length += length, line.collapsed += length, line.widgetHeight = Math.max(line.widgetHeight, height), line.breaks += breaks, this.writtenTo = this.pos = this.pos + length } finish(from) { let last = this.nodes.length == 0 ? null : this.nodes[this.nodes.length - 1]; this.lineStart > -1 && !(last instanceof HeightMapText) && !this.isCovered ? this.nodes.push(new HeightMapText(0, -1, 0)) : (this.writtenTo < this.pos || last == null) && this.nodes.push(this.blankContent(this.writtenTo, this.pos)); let pos = from; for (let node of this.nodes) node instanceof HeightMapText && node.updateHeight(this.oracle, pos), pos += node ? node.length : 1; return this.nodes } static build(oracle, decorations2, from, to) { let builder = new _NodeBuilder(from, oracle); return RangeSet.spans(decorations2, from, to, builder, 0), builder.finish(from) } }; function heightRelevantDecoChanges(a, b, diff) { let comp = new DecorationComparator2; return RangeSet.compare(a, b, diff, comp, 0), comp.changes } var DecorationComparator2 = class { changes = []; compareRange() { } comparePoint(from, to, a, b) { (from < to || a && a.heightRelevant || b && b.heightRelevant) && addRange(from, to, this.changes, 5) } }; function visiblePixelRange(dom, paddingTop) { let rect = dom.getBoundingClientRect(), doc2 = dom.ownerDocument, win = doc2.defaultView || window, left = Math.max(0, rect.left), right = Math.min(win.innerWidth, rect.right), top2 = Math.max(0, rect.top), bottom = Math.min(win.innerHeight, rect.bottom); for (let parent = dom.parentNode; parent && parent != doc2.body;)if (parent.nodeType == 1) { let elt = parent, style = window.getComputedStyle(elt); if ((elt.scrollHeight > elt.clientHeight || elt.scrollWidth > elt.clientWidth) && style.overflow != "visible") { let parentRect = elt.getBoundingClientRect(); left = Math.max(left, parentRect.left), right = Math.min(right, parentRect.right), top2 = Math.max(top2, parentRect.top), bottom = Math.min(parent == dom.parentNode ? win.innerHeight : bottom, parentRect.bottom) } parent = style.position == "absolute" || style.position == "fixed" ? elt.offsetParent : elt.parentNode } else if (parent.nodeType == 11) parent = parent.host; else break; return { left: left - rect.left, right: Math.max(left, right) - rect.left, top: top2 - (rect.top + paddingTop), bottom: Math.max(top2, bottom) - (rect.top + paddingTop) } } function inWindow(elt) { let rect = elt.getBoundingClientRect(), win = elt.ownerDocument.defaultView || window; return rect.left < win.innerWidth && rect.right > 0 && rect.top < win.innerHeight && rect.bottom > 0 } function fullPixelRange(dom, paddingTop) { let rect = dom.getBoundingClientRect(); return { left: 0, right: rect.right - rect.left, top: paddingTop, bottom: rect.bottom - (rect.top + paddingTop) } } var LineGap = class { constructor(from, to, size, displaySize) { this.from = from; this.to = to; this.size = size; this.displaySize = displaySize } from; to; size; displaySize; static same(a, b) { if (a.length != b.length) return !1; for (let i2 = 0; i2 < a.length; i2++) { let gA = a[i2], gB = b[i2]; if (gA.from != gB.from || gA.to != gB.to || gA.size != gB.size) return !1 } return !0 } draw(viewState, wrapping) { return Decoration.replace({ widget: new LineGapWidget(this.displaySize * (wrapping ? viewState.scaleY : viewState.scaleX), wrapping) }).range(this.from, this.to) } }, LineGapWidget = class extends WidgetType { constructor(size, vertical) { super(); this.size = size; this.vertical = vertical } size; vertical; eq(other) { return other.size == this.size && other.vertical == this.vertical } toDOM() { let elt = document.createElement("div"); return this.vertical ? elt.style.height = this.size + "px" : (elt.style.width = this.size + "px", elt.style.height = "2px", elt.style.display = "inline-block"), elt } get estimatedHeight() { return this.vertical ? this.size : -1 } }; var ViewState = class { constructor(view, state) { this.view = view; this.state = state; let guessWrapping = state.facet(contentAttributes).some(v => typeof v != "function" && v.class == "cm-lineWrapping"); this.heightOracle = new HeightOracle(guessWrapping), this.stateDeco = staticDeco(state), this.heightMap = HeightMap.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle.setDoc(state.doc), [new ChangedRange(0, 0, 0, state.doc.length)]); for (let i2 = 0; i2 < 2 && (this.viewport = this.getViewport(0, null), !!this.updateForViewport()); i2++); this.updateViewportLines(), this.lineGaps = this.ensureLineGaps([]), this.lineGapDeco = Decoration.set(this.lineGaps.map(gap => gap.draw(this, !1))), this.scrollParent = view.scrollDOM, this.computeVisibleRanges() } view; state; pixelViewport = { left: 0, right: window.innerWidth, top: 0, bottom: 0 }; inView = !0; paddingTop = 0; paddingBottom = 0; contentDOMWidth = 0; contentDOMHeight = 0; editorHeight = 0; editorWidth = 0; scaleX = 1; scaleY = 1; scrollParent; scrollOffset = 0; scrolledToBottom = !1; scrollAnchorPos = 0; scrollAnchorHeight = -1; heightOracle; heightMap; scaler = IdScaler; scrollTarget = null; printing = !1; mustMeasureContent = !0; stateDeco; defaultTextDirection = 0; visibleRanges = []; lineGaps; lineGapDeco; mustEnforceCursorAssoc = !1; updateForViewport() { let viewports = [this.viewport], { main } = this.state.selection; for (let i2 = 0; i2 <= 1; i2++) { let pos = i2 ? main.head : main.anchor; if (!viewports.some(({ from, to }) => pos >= from && pos <= to)) { let { from, to } = this.lineBlockAt(pos); viewports.push(new Viewport(from, to)) } } return this.viewports = viewports.sort((a, b) => a.from - b.from), this.updateScaler() } updateScaler() { let scaler = this.scaler; return this.scaler = this.heightMap.height <= 7e6 ? IdScaler : new BigScaler(this.heightOracle, this.heightMap, this.viewports), scaler.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, block => { this.viewportLines.push(scaleBlock(block, this.scaler)) }) } update(update, scrollTarget = null) { this.state = update.state; let prevDeco = this.stateDeco; this.stateDeco = staticDeco(this.state); let contentChanges = update.changedRanges, heightChanges = ChangedRange.extendWithRanges(contentChanges, heightRelevantDecoChanges(prevDeco, this.stateDeco, update ? update.changes : ChangeSet.empty(this.state.doc.length))), prevHeight = this.heightMap.height, scrollAnchor = this.scrolledToBottom ? null : this.scrollAnchorAt(this.scrollOffset); clearHeightChangeFlag(), this.heightMap = this.heightMap.applyChanges(this.stateDeco, update.startState.doc, this.heightOracle.setDoc(this.state.doc), heightChanges), (this.heightMap.height != prevHeight || heightChangeFlag) && (update.flags |= 2), scrollAnchor ? (this.scrollAnchorPos = update.changes.mapPos(scrollAnchor.from, -1), this.scrollAnchorHeight = scrollAnchor.top) : (this.scrollAnchorPos = -1, this.scrollAnchorHeight = prevHeight); let viewport = heightChanges.length ? this.mapViewport(this.viewport, update.changes) : this.viewport; (scrollTarget && (scrollTarget.range.head < viewport.from || scrollTarget.range.head > viewport.to) || !this.viewportIsAppropriate(viewport)) && (viewport = this.getViewport(0, scrollTarget)); let viewportChange = viewport.from != this.viewport.from || viewport.to != this.viewport.to; this.viewport = viewport, update.flags |= this.updateForViewport(), (viewportChange || !update.changes.empty || update.flags & 2) && this.updateViewportLines(), (this.lineGaps.length || this.viewport.to - this.viewport.from > 4e3) && this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps, update.changes))), update.flags |= this.computeVisibleRanges(update.changes), scrollTarget && (this.scrollTarget = scrollTarget), !this.mustEnforceCursorAssoc && (update.selectionSet || update.focusChanged) && update.view.lineWrapping && update.state.selection.main.empty && update.state.selection.main.assoc && !update.state.facet(nativeSelectionHidden) && (this.mustEnforceCursorAssoc = !0) } measure() { let { view } = this, dom = view.contentDOM, style = window.getComputedStyle(dom), oracle = this.heightOracle, whiteSpace = style.whiteSpace; this.defaultTextDirection = style.direction == "rtl" ? 1 : 0; let refresh = this.heightOracle.mustRefreshForWrapping(whiteSpace) || this.mustMeasureContent === "refresh", domRect = dom.getBoundingClientRect(), measureContent = refresh || this.mustMeasureContent || this.contentDOMHeight != domRect.height; this.contentDOMHeight = domRect.height, this.mustMeasureContent = !1; let result = 0, bias = 0; if (domRect.width && domRect.height) { let { scaleX, scaleY } = getScale(dom, domRect); (scaleX > .005 && Math.abs(this.scaleX - scaleX) > .005 || scaleY > .005 && Math.abs(this.scaleY - scaleY) > .005) && (this.scaleX = scaleX, this.scaleY = scaleY, result |= 16, refresh = measureContent = !0) } let paddingTop = (parseInt(style.paddingTop) || 0) * this.scaleY, paddingBottom = (parseInt(style.paddingBottom) || 0) * this.scaleY; (this.paddingTop != paddingTop || this.paddingBottom != paddingBottom) && (this.paddingTop = paddingTop, this.paddingBottom = paddingBottom, result |= 18), this.editorWidth != view.scrollDOM.clientWidth && (oracle.lineWrapping && (measureContent = !0), this.editorWidth = view.scrollDOM.clientWidth, result |= 16); let scrollParent = scrollableParents(this.view.contentDOM, !1).y; scrollParent != this.scrollParent && (this.scrollParent = scrollParent, this.scrollAnchorHeight = -1, this.scrollOffset = 0); let scrollOffset = this.getScrollOffset(); this.scrollOffset != scrollOffset && (this.scrollAnchorHeight = -1, this.scrollOffset = scrollOffset), this.scrolledToBottom = isScrolledToBottom(this.scrollParent || view.win); let pixelViewport = (this.printing ? fullPixelRange : visiblePixelRange)(dom, this.paddingTop), dTop = pixelViewport.top - this.pixelViewport.top, dBottom = pixelViewport.bottom - this.pixelViewport.bottom; this.pixelViewport = pixelViewport; let inView = this.pixelViewport.bottom > this.pixelViewport.top && this.pixelViewport.right > this.pixelViewport.left; if (inView != this.inView && (this.inView = inView, inView && (measureContent = !0)), !this.inView && !this.scrollTarget && !inWindow(view.dom)) return 0; let contentWidth = domRect.width; if ((this.contentDOMWidth != contentWidth || this.editorHeight != view.scrollDOM.clientHeight) && (this.contentDOMWidth = domRect.width, this.editorHeight = view.scrollDOM.clientHeight, result |= 16), measureContent) { let lineHeights = view.docView.measureVisibleLineHeights(this.viewport); if (oracle.mustRefreshForHeights(lineHeights) && (refresh = !0), refresh || oracle.lineWrapping && Math.abs(contentWidth - this.contentDOMWidth) > oracle.charWidth) { let { lineHeight, charWidth, textHeight } = view.docView.measureTextSize(); refresh = lineHeight > 0 && oracle.refresh(whiteSpace, lineHeight, charWidth, textHeight, Math.max(5, contentWidth / charWidth), lineHeights), refresh && (view.docView.minWidth = 0, result |= 16) } dTop > 0 && dBottom > 0 ? bias = Math.max(dTop, dBottom) : dTop < 0 && dBottom < 0 && (bias = Math.min(dTop, dBottom)), clearHeightChangeFlag(); for (let vp of this.viewports) { let heights = vp.from == this.viewport.from ? lineHeights : view.docView.measureVisibleLineHeights(vp); this.heightMap = (refresh ? HeightMap.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle, [new ChangedRange(0, 0, 0, view.state.doc.length)]) : this.heightMap).updateHeight(oracle, 0, refresh, new MeasuredHeights(vp.from, heights)) } heightChangeFlag && (result |= 2) } let viewportChange = !this.viewportIsAppropriate(this.viewport, bias) || this.scrollTarget && (this.scrollTarget.range.head < this.viewport.from || this.scrollTarget.range.head > this.viewport.to); return viewportChange && (result & 2 && (result |= this.updateScaler()), this.viewport = this.getViewport(bias, this.scrollTarget), result |= this.updateForViewport()), (result & 2 || viewportChange) && this.updateViewportLines(), (this.lineGaps.length || this.viewport.to - this.viewport.from > 4e3) && this.updateLineGaps(this.ensureLineGaps(refresh ? [] : this.lineGaps, view)), result |= this.computeVisibleRanges(), this.mustEnforceCursorAssoc && (this.mustEnforceCursorAssoc = !1, view.docView.enforceCursorAssoc()), result } get visibleTop() { return this.scaler.fromDOM(this.pixelViewport.top) } get visibleBottom() { return this.scaler.fromDOM(this.pixelViewport.bottom) } getViewport(bias, scrollTarget) { let marginTop = .5 - Math.max(-.5, Math.min(.5, bias / 1e3 / 2)), map = this.heightMap, oracle = this.heightOracle, { visibleTop, visibleBottom } = this, viewport = new Viewport(map.lineAt(visibleTop - marginTop * 1e3, 1, oracle, 0, 0).from, map.lineAt(visibleBottom + (1 - marginTop) * 1e3, 1, oracle, 0, 0).to); if (scrollTarget) { let { head } = scrollTarget.range; if (head < viewport.from || head > viewport.to) { let viewHeight = Math.min(this.editorHeight, this.pixelViewport.bottom - this.pixelViewport.top), block = map.lineAt(head, 0, oracle, 0, 0), topPos; scrollTarget.y == "center" ? topPos = (block.top + block.bottom) / 2 - viewHeight / 2 : scrollTarget.y == "start" || scrollTarget.y == "nearest" && head < viewport.from ? topPos = block.top : topPos = block.bottom - viewHeight, viewport = new Viewport(map.lineAt(topPos - 1e3 / 2, 1, oracle, 0, 0).from, map.lineAt(topPos + viewHeight + 1e3 / 2, 1, oracle, 0, 0).to) } } return viewport } mapViewport(viewport, changes) { let from = changes.mapPos(viewport.from, -1), to = changes.mapPos(viewport.to, 1); return new Viewport(this.heightMap.lineAt(from, 0, this.heightOracle, 0, 0).from, this.heightMap.lineAt(to, 0, this.heightOracle, 0, 0).to) } viewportIsAppropriate({ from, to }, bias = 0) { if (!this.inView) return !0; let { top: top2 } = this.heightMap.lineAt(from, 0, this.heightOracle, 0, 0), { bottom } = this.heightMap.lineAt(to, 0, this.heightOracle, 0, 0), { visibleTop, visibleBottom } = this; return (from == 0 || top2 <= visibleTop - Math.max(10, Math.min(-bias, 250))) && (to == this.state.doc.length || bottom >= visibleBottom + Math.max(10, Math.min(bias, 250))) && top2 > visibleTop - 2 * 1e3 && bottom < visibleBottom + 2 * 1e3 } mapLineGaps(gaps, changes) { if (!gaps.length || changes.empty) return gaps; let mapped = []; for (let gap of gaps) changes.touchesRange(gap.from, gap.to) || mapped.push(new LineGap(changes.mapPos(gap.from), changes.mapPos(gap.to), gap.size, gap.displaySize)); return mapped } ensureLineGaps(current, mayMeasure) { let wrapping = this.heightOracle.lineWrapping, margin = wrapping ? 1e4 : 2e3, halfMargin = margin >> 1, doubleMargin = margin << 1; if (this.defaultTextDirection != 0 && !wrapping) return []; let gaps = [], addGap = (from, to, line, structure) => { if (to - from < halfMargin) return; let sel = this.state.selection.main, avoid = [sel.from]; sel.empty || avoid.push(sel.to); for (let pos of avoid) if (pos > from && pos < to) { addGap(from, pos - 10, line, structure), addGap(pos + 10, to, line, structure); return } let gap = find(current, gap2 => gap2.from >= line.from && gap2.to <= line.to && Math.abs(gap2.from - from) < halfMargin && Math.abs(gap2.to - to) < halfMargin && !avoid.some(pos => gap2.from < pos && gap2.to > pos)); if (!gap) { if (to < line.to && mayMeasure && wrapping && mayMeasure.visibleRanges.some(r => r.from <= to && r.to >= to)) { let lineStart = mayMeasure.moveToLineBoundary(EditorSelection.cursor(to), !1, !0).head; lineStart > from && (to = lineStart) } let size = this.gapSize(line, from, to, structure), displaySize = wrapping || size < 2e6 ? size : 2e6; gap = new LineGap(from, to, size, displaySize) } gaps.push(gap) }, checkLine = line => { if (line.length < doubleMargin || line.type != 0) return; let structure = lineStructure(line.from, line.to, this.stateDeco); if (structure.total < doubleMargin) return; let target = this.scrollTarget ? this.scrollTarget.range.head : null, viewFrom, viewTo; if (wrapping) { let marginHeight = margin / this.heightOracle.lineLength * this.heightOracle.lineHeight, top2, bot; if (target != null) { let targetFrac = findFraction(structure, target), spaceFrac = ((this.visibleBottom - this.visibleTop) / 2 + marginHeight) / line.height; top2 = targetFrac - spaceFrac, bot = targetFrac + spaceFrac } else top2 = (this.visibleTop - line.top - marginHeight) / line.height, bot = (this.visibleBottom - line.top + marginHeight) / line.height; viewFrom = findPosition(structure, top2), viewTo = findPosition(structure, bot) } else { let totalWidth = structure.total * this.heightOracle.charWidth, marginWidth = margin * this.heightOracle.charWidth, horizOffset = 0; if (totalWidth > 2e6) for (let old of current) old.from >= line.from && old.from < line.to && old.size != old.displaySize && old.from * this.heightOracle.charWidth + horizOffset < this.pixelViewport.left && (horizOffset = old.size - old.displaySize); let pxLeft = this.pixelViewport.left + horizOffset, pxRight = this.pixelViewport.right + horizOffset, left, right; if (target != null) { let targetFrac = findFraction(structure, target), spaceFrac = ((pxRight - pxLeft) / 2 + marginWidth) / totalWidth; left = targetFrac - spaceFrac, right = targetFrac + spaceFrac } else left = (pxLeft - marginWidth) / totalWidth, right = (pxRight + marginWidth) / totalWidth; viewFrom = findPosition(structure, left), viewTo = findPosition(structure, right) } viewFrom > line.from && addGap(line.from, viewFrom, line, structure), viewTo < line.to && addGap(viewTo, line.to, line, structure) }; for (let line of this.viewportLines) Array.isArray(line.type) ? line.type.forEach(checkLine) : checkLine(line); return gaps } gapSize(line, from, to, structure) { let fraction = findFraction(structure, to) - findFraction(structure, from); return this.heightOracle.lineWrapping ? line.height * fraction : structure.total * this.heightOracle.charWidth * fraction } updateLineGaps(gaps) { LineGap.same(gaps, this.lineGaps) || (this.lineGaps = gaps, this.lineGapDeco = Decoration.set(gaps.map(gap => gap.draw(this, this.heightOracle.lineWrapping)))) } computeVisibleRanges(changes) { let deco = this.stateDeco; this.lineGaps.length && (deco = deco.concat(this.lineGapDeco)); let ranges = []; RangeSet.spans(deco, this.viewport.from, this.viewport.to, { span(from, to) { ranges.push({ from, to }) }, point() { } }, 20); let changed = 0; if (ranges.length != this.visibleRanges.length) changed = 12; else for (let i2 = 0; i2 < ranges.length && !(changed & 8); i2++) { let old = this.visibleRanges[i2], nw = ranges[i2]; (old.from != nw.from || old.to != nw.to) && (changed |= 4, changes && changes.mapPos(old.from, -1) == nw.from && changes.mapPos(old.to, 1) == nw.to || (changed |= 8)) } return this.visibleRanges = ranges, changed } lineBlockAt(pos) { return pos >= this.viewport.from && pos <= this.viewport.to && this.viewportLines.find(b => b.from <= pos && b.to >= pos) || scaleBlock(this.heightMap.lineAt(pos, 0, this.heightOracle, 0, 0), this.scaler) } lineBlockAtHeight(height) { return height >= this.viewportLines[0].top && height <= this.viewportLines[this.viewportLines.length - 1].bottom && this.viewportLines.find(l => l.top <= height && l.bottom >= height) || scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height), 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(scrollOffset) { let block = this.lineBlockAtHeight(scrollOffset + 8); return block.from >= this.viewport.from || this.viewportLines[0].top - scrollOffset > 200 ? block : this.viewportLines[0] } elementAtHeight(height) { return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height), this.heightOracle, 0, 0), this.scaler) } get docHeight() { return this.scaler.toDOM(this.heightMap.height) } get contentHeight() { return this.docHeight + this.paddingTop + this.paddingBottom } }, Viewport = class { constructor(from, to) { this.from = from; this.to = to } from; to }; function lineStructure(from, to, stateDeco) { let ranges = [], pos = from, total = 0; return RangeSet.spans(stateDeco, from, to, { span() { }, point(from2, to2) { from2 > pos && (ranges.push({ from: pos, to: from2 }), total += from2 - pos), pos = to2 } }, 20), pos < to && (ranges.push({ from: pos, to }), total += to - pos), { total, ranges } } function findPosition({ total, ranges }, ratio) { if (ratio <= 0) return ranges[0].from; if (ratio >= 1) return ranges[ranges.length - 1].to; let dist2 = Math.floor(total * ratio); for (let i2 = 0; ; i2++) { let { from, to } = ranges[i2], size = to - from; if (dist2 <= size) return from + dist2; dist2 -= size } } function findFraction(structure, pos) { let counted = 0; for (let { from, to } of structure.ranges) { if (pos <= to) { counted += pos - from; break } counted += to - from } return counted / structure.total } function find(array, f) { for (let val of array) if (f(val)) return val } var IdScaler = { toDOM(n) { return n }, fromDOM(n) { return n }, scale: 1, eq(other) { return other == this } }; function staticDeco(state) { let deco = state.facet(decorations).filter(d => typeof d != "function"), outer = state.facet(outerDecorations).filter(d => typeof d != "function"); return outer.length && deco.push(RangeSet.join(outer)), deco } var BigScaler = class _BigScaler { scale; viewports; constructor(oracle, heightMap, viewports) { let vpHeight = 0, base2 = 0, domBase = 0; this.viewports = viewports.map(({ from, to }) => { let top2 = heightMap.lineAt(from, 0, oracle, 0, 0).top, bottom = heightMap.lineAt(to, 0, oracle, 0, 0).bottom; return vpHeight += bottom - top2, { from, to, top: top2, bottom, domTop: 0, domBottom: 0 } }), this.scale = (7e6 - vpHeight) / (heightMap.height - vpHeight); for (let obj of this.viewports) obj.domTop = domBase + (obj.top - base2) * this.scale, domBase = obj.domBottom = obj.domTop + (obj.bottom - obj.top), base2 = obj.bottom } toDOM(n) { for (let i2 = 0, base2 = 0, domBase = 0; ; i2++) { let vp = i2 < this.viewports.length ? this.viewports[i2] : null; if (!vp || n < vp.top) return domBase + (n - base2) * this.scale; if (n <= vp.bottom) return vp.domTop + (n - vp.top); base2 = vp.bottom, domBase = vp.domBottom } } fromDOM(n) { for (let i2 = 0, base2 = 0, domBase = 0; ; i2++) { let vp = i2 < this.viewports.length ? this.viewports[i2] : null; if (!vp || n < vp.domTop) return base2 + (n - domBase) / this.scale; if (n <= vp.domBottom) return vp.top + (n - vp.domTop); base2 = vp.bottom, domBase = vp.domBottom } } eq(other) { return other instanceof _BigScaler ? this.scale == other.scale && this.viewports.length == other.viewports.length && this.viewports.every((vp, i2) => vp.from == other.viewports[i2].from && vp.to == other.viewports[i2].to) : !1 } }; function scaleBlock(block, scaler) { if (scaler.scale == 1) return block; let bTop = scaler.toDOM(block.top), bBottom = scaler.toDOM(block.bottom); return new BlockInfo(block.from, block.length, bTop, bBottom - bTop, Array.isArray(block._content) ? block._content.map(b => scaleBlock(b, scaler)) : block._content) } var theme = Facet.define({ combine: strs => strs.join(" ") }), darkTheme = Facet.define({ combine: values => values.indexOf(!0) > -1 }), baseThemeID = StyleModule.newName(), baseLightID = StyleModule.newName(), baseDarkID = StyleModule.newName(), lightDarkIDs = { "&light": "." + baseLightID, "&dark": "." + baseDarkID }; function buildTheme(main, spec, scopes) { return new StyleModule(spec, { finish(sel) { return /&/.test(sel) ? sel.replace(/&\w*/, m => { if (m == "&") return main; if (!scopes || !scopes[m]) throw new RangeError(`Unsupported selector: ${m}`); return scopes[m] }) : main + " " + sel } }) } var baseTheme = buildTheme("." + baseThemeID, { "&": { 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,')`, 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" } }, lightDarkIDs); var observeOptions = { childList: !0, characterData: !0, subtree: !0, attributes: !0, characterDataOldValue: !0 }, useCharData = browser_default.ie && browser_default.ie_version <= 11, DOMObserver = class { constructor(view) { this.view = view; this.dom = view.contentDOM, this.observer = new MutationObserver(mutations => { for (let mut of mutations) this.queue.push(mut); (browser_default.ie && browser_default.ie_version <= 11 || browser_default.ios && view.composing) && mutations.some(m => m.type == "childList" && m.removedNodes.length || m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length) ? this.flushSoon() : this.flush() }), window.EditContext && browser_default.android && view.constructor.EDIT_CONTEXT !== !1 && !(browser_default.chrome && browser_default.chrome_version < 126) && (this.editContext = new EditContextManager(view), view.state.facet(editable) && (view.contentDOM.editContext = this.editContext.editContext)), useCharData && (this.onCharData = event => { this.queue.push({ target: event.target, type: "characterData", oldValue: event.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(view.scrollDOM)), this.addWindowListeners(this.win = view.win), this.start(), typeof IntersectionObserver == "function" && (this.intersection = new IntersectionObserver(entries => { this.parentCheck < 0 && (this.parentCheck = setTimeout(this.listenForScroll.bind(this), 1e3)), entries.length > 0 && entries[entries.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(entries => { entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0 && this.onScrollChanged(document.createEvent("Event")) }, {})), this.listenForScroll(), this.readSelectionRange() } view; dom; win; observer; active = !1; editContext = null; selectionRange = new DOMSelectionState; selectionChanged = !1; delayedFlush = -1; resizeTimeout = -1; queue = []; delayedAndroidKey = null; flushingAndroidKey = -1; lastChange = 0; onCharData; scrollTargets = []; intersection = null; resizeScroll = null; intersecting = !1; gapIntersection = null; gaps = []; printQuery = null; parentCheck = -1; 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(event) { (event.type == "change" || !event.type) && !event.matches || (this.view.viewState.printing = !0, this.view.measure(), setTimeout(() => { this.view.viewState.printing = !1, this.view.requestMeasure() }, 500)) } updateGaps(gaps) { if (this.gapIntersection && (gaps.length != this.gaps.length || this.gaps.some((g, i2) => g != gaps[i2]))) { this.gapIntersection.disconnect(); for (let gap of gaps) this.gapIntersection.observe(gap); this.gaps = gaps } } onSelectionChange(event) { let wasChanged = this.selectionChanged; if (!this.readSelectionRange() || this.delayedAndroidKey) return; let { view } = this, sel = this.selectionRange; if (view.state.facet(editable) ? view.root.activeElement != this.dom : !hasSelection(this.dom, sel)) return; let context = sel.anchorNode && view.docView.tile.nearest(sel.anchorNode); if (context && context.isWidget() && context.widget.ignoreEvent(event)) { wasChanged || (this.selectionChanged = !1); return } (browser_default.ie && browser_default.ie_version <= 11 || browser_default.android && browser_default.chrome) && !view.state.selection.main.empty && sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset) ? this.flushSoon() : this.flush(!1) } readSelectionRange() { let { view } = this, selection = getSelection(view.root); if (!selection) return !1; let range = browser_default.safari && view.root.nodeType == 11 && view.root.activeElement == this.dom && safariSelectionRangeHack(this.view, selection) || selection; if (!range || this.selectionRange.eq(range)) return !1; let local = hasSelection(this.dom, range); return local && !this.selectionChanged && view.inputState.lastFocusTime > Date.now() - 200 && view.inputState.lastTouchTime < Date.now() - 300 && atElementStart(this.dom, range) ? (this.view.inputState.lastFocusTime = 0, view.docView.updateSelection(), !1) : (this.selectionRange.setRange(range), local && (this.selectionChanged = !0), !0) } setSelectionRange(anchor, head) { this.selectionRange.set(anchor.node, anchor.offset, head.node, head.offset), this.selectionChanged = !1 } clearSelectionRange() { this.selectionRange.set(null, 0, null, 0) } listenForScroll() { this.parentCheck = -1; let i2 = 0, changed = null; for (let dom = this.dom; dom;)if (dom.nodeType == 1) !changed && i2 < this.scrollTargets.length && this.scrollTargets[i2] == dom ? i2++ : changed || (changed = this.scrollTargets.slice(0, i2)), changed && changed.push(dom), dom = dom.assignedSlot || dom.parentNode; else if (dom.nodeType == 11) dom = dom.host; else break; if (i2 < this.scrollTargets.length && !changed && (changed = this.scrollTargets.slice(0, i2)), changed) { for (let dom of this.scrollTargets) dom.removeEventListener("scroll", this.onScroll); for (let dom of this.scrollTargets = changed) dom.addEventListener("scroll", this.onScroll) } } ignore(f) { if (!this.active) return f(); try { return this.stop(), f() } finally { this.start(), this.clear() } } start() { this.active || (this.observer.observe(this.dom, observeOptions), useCharData && this.dom.addEventListener("DOMCharacterDataModified", this.onCharData), this.active = !0) } stop() { this.active && (this.active = !1, this.observer.disconnect(), useCharData && this.dom.removeEventListener("DOMCharacterDataModified", this.onCharData)) } clear() { this.processRecords(), this.queue.length = 0, this.selectionChanged = !1 } delayAndroidKey(key, keyCode) { if (!this.delayedAndroidKey) { let flush = () => { let key2 = this.delayedAndroidKey; key2 && (this.clearDelayedAndroidKey(), this.view.inputState.lastKeyCode = key2.keyCode, this.view.inputState.lastKeyTime = Date.now(), !this.flush() && key2.force && dispatchKey(this.dom, key2.key, key2.keyCode)) }; this.flushingAndroidKey = this.view.win.requestAnimationFrame(flush) } (!this.delayedAndroidKey || key == "Enter") && (this.delayedAndroidKey = { key, keyCode, 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 mut of this.observer.takeRecords()) this.queue.push(mut); return this.queue } processRecords() { let records = this.pendingRecords(); records.length && (this.queue = []); let from = -1, to = -1, typeOver = !1; for (let record of records) { let range = this.readMutation(record); range && (range.typeOver && (typeOver = !0), from == -1 ? { from, to } = range : (from = Math.min(range.from, from), to = Math.max(range.to, to))) } return { from, to, typeOver } } readChange() { let { from, to, typeOver } = this.processRecords(), newSel = this.selectionChanged && hasSelection(this.dom, this.selectionRange); if (from < 0 && !newSel) return null; from > -1 && (this.lastChange = Date.now()), this.view.inputState.lastFocusTime = 0, this.selectionChanged = !1; let change = new DOMChange(this.view, from, to, typeOver); return this.view.docView.domChanged = { newSel: change.newSel ? change.newSel.main : null }, change } flush(readSelection = !0) { if (this.delayedFlush >= 0 || this.delayedAndroidKey) return !1; readSelection && this.readSelectionRange(); let domChange = this.readChange(); if (!domChange) return this.view.requestMeasure(), !1; let startState = this.view.state, handled = applyDOMChange(this.view, domChange); return this.view.state == startState && (domChange.domChanged || domChange.newSel && !sameSelPos(this.view.state.selection, domChange.newSel.main)) && this.view.update([]), handled } readMutation(rec) { let tile = this.view.docView.tile.nearest(rec.target); if (!tile || tile.isWidget()) return null; if (tile.markDirty(rec.type == "attributes"), rec.type == "childList") { let childBefore = findChild(tile, rec.previousSibling || rec.target.previousSibling, -1), childAfter = findChild(tile, rec.nextSibling || rec.target.nextSibling, 1); return { from: childBefore ? tile.posAfter(childBefore) : tile.posAtStart, to: childAfter ? tile.posBefore(childAfter) : tile.posAtEnd, typeOver: !1 } } else return rec.type == "characterData" ? { from: tile.posAtStart, to: tile.posAtEnd, typeOver: rec.target.nodeValue == rec.oldValue } : null } setWindow(win) { win != this.win && (this.removeWindowListeners(this.win), this.win = win, this.addWindowListeners(this.win)) } addWindowListeners(win) { win.addEventListener("resize", this.onResize), this.printQuery ? this.printQuery.addEventListener ? this.printQuery.addEventListener("change", this.onPrint) : this.printQuery.addListener(this.onPrint) : win.addEventListener("beforeprint", this.onPrint), win.addEventListener("scroll", this.onScroll), win.document.addEventListener("selectionchange", this.onSelectionChange) } removeWindowListeners(win) { win.removeEventListener("scroll", this.onScroll), win.removeEventListener("resize", this.onResize), this.printQuery ? this.printQuery.removeEventListener ? this.printQuery.removeEventListener("change", this.onPrint) : this.printQuery.removeListener(this.onPrint) : win.removeEventListener("beforeprint", this.onPrint), win.document.removeEventListener("selectionchange", this.onSelectionChange) } update(update) { this.editContext && (this.editContext.update(update), update.startState.facet(editable) != update.state.facet(editable) && (update.view.contentDOM.editContext = update.state.facet(editable) ? this.editContext.editContext : null)) } destroy() { this.stop(), this.intersection?.disconnect(), this.gapIntersection?.disconnect(), this.resizeScroll?.disconnect(); for (let dom of this.scrollTargets) dom.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 findChild(tile, dom, dir) { for (; dom;) { let curTile = Tile.get(dom); if (curTile && curTile.parent == tile) return curTile; let parent = dom.parentNode; dom = parent != tile.dom ? parent : dir > 0 ? dom.nextSibling : dom.previousSibling } return null } function buildSelectionRangeFromRange(view, range) { let anchorNode = range.startContainer, anchorOffset = range.startOffset, focusNode = range.endContainer, focusOffset = range.endOffset, curAnchor = view.docView.domAtPos(view.state.selection.main.anchor, 1); return isEquivalentPosition(curAnchor.node, curAnchor.offset, focusNode, focusOffset) && ([anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset]), { anchorNode, anchorOffset, focusNode, focusOffset } } function safariSelectionRangeHack(view, selection) { if (selection.getComposedRanges) { let range = selection.getComposedRanges(view.root)[0]; if (range) return buildSelectionRangeFromRange(view, range) } let found = null; function read(event) { event.preventDefault(), event.stopImmediatePropagation(), found = event.getTargetRanges()[0] } return view.contentDOM.addEventListener("beforeinput", read, !0), view.dom.ownerDocument.execCommand("indent"), view.contentDOM.removeEventListener("beforeinput", read, !0), found ? buildSelectionRangeFromRange(view, found) : null } var EditContextManager = class { + editContext; measureReq; from = 0; to = 0; pendingContextChange = null; handlers = Object.create(null); composing = null; constructor(view) { + this.resetRange(view.state); let context = this.editContext = new window.EditContext({ text: view.state.doc.sliceString(this.from, this.to), selectionStart: this.toContextPos(Math.max(this.from, Math.min(this.to, view.state.selection.main.anchor))), selectionEnd: this.toContextPos(view.state.selection.main.head) }); this.handlers.textupdate = e => { + let main = view.state.selection.main, { anchor, head } = main, from = this.toEditorPos(e.updateRangeStart), to = this.toEditorPos(e.updateRangeEnd); view.inputState.composing >= 0 && !this.composing && (this.composing = { contextBase: e.updateRangeStart, editorBase: from, drifted: !1 }); let deletes = to - from > e.text.length; from == this.from && anchor < this.from ? from = anchor : to == this.to && anchor > this.to && (to = anchor); let diff = findDiff(view.state.sliceDoc(from, to), e.text, (deletes ? main.from : main.to) - from, deletes ? "end" : null); if (!diff) { let newSel = EditorSelection.single(this.toEditorPos(e.selectionStart), this.toEditorPos(e.selectionEnd)); sameSelPos(newSel, main) || view.dispatch({ selection: newSel, userEvent: "select" }); return } let change = { + from: diff.from + from, to: diff.toA + from, insert: Text.of(e.text.slice(diff.from, diff.toB).split(` +`)) + }; if ((browser_default.mac || browser_default.android) && change.from == head - 1 && /^\. ?$/.test(e.text) && view.contentDOM.getAttribute("autocorrect") == "off" && (change = { from, to, insert: Text.of([e.text.replace(".", " ")]) }), this.pendingContextChange = change, !view.state.readOnly) { let newLen = this.to - this.from + (change.to - change.from + change.insert.length); applyDOMChangeInner(view, change, EditorSelection.single(this.toEditorPos(e.selectionStart, newLen), this.toEditorPos(e.selectionEnd, newLen))) } this.pendingContextChange && (this.revertPending(view.state), this.setSelection(view.state)), change.from < change.to && !change.insert.length && view.inputState.composing >= 0 && !/[\\p{Alphabetic}\\p{Number}_]/.test(context.text.slice(Math.max(0, e.updateRangeStart - 1), Math.min(context.text.length, e.updateRangeStart + 1))) && this.handlers.compositionend(e) + }, this.handlers.characterboundsupdate = e => { let rects = [], prev = null; for (let i2 = this.toEditorPos(e.rangeStart), end = this.toEditorPos(e.rangeEnd); i2 < end; i2++) { let rect = view.coordsForChar(i2); prev = rect && new DOMRect(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top) || prev || new DOMRect, rects.push(prev) } context.updateCharacterBounds(e.rangeStart, rects) }, this.handlers.textformatupdate = e => { let deco = []; for (let format of e.getTextFormats()) { let lineStyle = format.underlineStyle, thickness = format.underlineThickness; if (!/none/i.test(lineStyle) && !/none/i.test(thickness)) { let from = this.toEditorPos(format.rangeStart), to = this.toEditorPos(format.rangeEnd); if (from < to) { let style = `text-decoration: underline ${/^[a-z]/.test(lineStyle) ? lineStyle + " " : lineStyle == "Dashed" ? "dashed " : lineStyle == "Squiggle" ? "wavy " : ""}${/thin/i.test(thickness) ? 1 : 2}px`; deco.push(Decoration.mark({ attributes: { style } }).range(from, to)) } } } view.dispatch({ effects: setEditContextFormatting.of(Decoration.set(deco)) }) }, this.handlers.compositionstart = () => { view.inputState.composing < 0 && (view.inputState.composing = 0, view.inputState.compositionFirstChange = !0) }, this.handlers.compositionend = () => { if (view.inputState.composing = -1, view.inputState.compositionFirstChange = null, this.composing) { let { drifted } = this.composing; this.composing = null, drifted && this.reset(view.state) } }; for (let event in this.handlers) context.addEventListener(event, this.handlers[event]); this.measureReq = { read: view2 => { this.editContext.updateControlBounds(view2.contentDOM.getBoundingClientRect()); let sel = getSelection(view2.root); sel && sel.rangeCount && this.editContext.updateSelectionBounds(sel.getRangeAt(0).getBoundingClientRect()) } } + } applyEdits(update) { let off = 0, abort = !1, pending = this.pendingContextChange; return update.changes.iterChanges((fromA, toA, _fromB, _toB, insert2) => { if (abort) return; let dLen = insert2.length - (toA - fromA); if (pending && toA >= pending.to) if (pending.from == fromA && pending.to == toA && pending.insert.eq(insert2)) { pending = this.pendingContextChange = null, off += dLen, this.to += dLen; return } else pending = null, this.revertPending(update.state); if (fromA += off, toA += off, toA <= this.from) this.from += dLen, this.to += dLen; else if (fromA < this.to) { if (fromA < this.from || toA > this.to || this.to - this.from + insert2.length > 3e4) { abort = !0; return } this.editContext.updateText(this.toContextPos(fromA), this.toContextPos(toA), insert2.toString()), this.to += dLen } off += dLen }), pending && !abort && this.revertPending(update.state), !abort } update(update) { let reverted = this.pendingContextChange, startSel = update.startState.selection.main; this.composing && (this.composing.drifted || !update.changes.touchesRange(startSel.from, startSel.to) && update.transactions.some(tr => !tr.isUserEvent("input.type") && tr.changes.touchesRange(this.from, this.to))) ? (this.composing.drifted = !0, this.composing.editorBase = update.changes.mapPos(this.composing.editorBase)) : !this.applyEdits(update) || !this.rangeIsValid(update.state) ? (this.pendingContextChange = null, this.reset(update.state)) : (update.docChanged || update.selectionSet || reverted) && this.setSelection(update.state), (update.geometryChanged || update.docChanged || update.selectionSet) && update.view.requestMeasure(this.measureReq) } resetRange(state) { let { head } = state.selection.main; this.from = Math.max(0, head - 1e4), this.to = Math.min(state.doc.length, head + 1e4) } reset(state) { this.resetRange(state), this.editContext.updateText(0, this.editContext.text.length, state.doc.sliceString(this.from, this.to)), this.setSelection(state) } revertPending(state) { let pending = this.pendingContextChange; this.pendingContextChange = null, this.editContext.updateText(this.toContextPos(pending.from), this.toContextPos(pending.from + pending.insert.length), state.doc.sliceString(pending.from, pending.to)) } setSelection(state) { let { main } = state.selection, start = this.toContextPos(Math.max(this.from, Math.min(this.to, main.anchor))), end = this.toContextPos(main.head); (this.editContext.selectionStart != start || this.editContext.selectionEnd != end) && this.editContext.updateSelection(start, end) } rangeIsValid(state) { let { head } = state.selection.main; return !(this.from > 0 && head - this.from < 500 || this.to < state.doc.length && this.to - head < 500 || this.to - this.from > 1e4 * 3) } toEditorPos(contextPos, clipLen = this.to - this.from) { contextPos = Math.min(contextPos, clipLen); let c = this.composing; return c && c.drifted ? c.editorBase + (contextPos - c.contextBase) : contextPos + this.from } toContextPos(editorPos) { let c = this.composing; return c && c.drifted ? c.contextBase + (editorPos - c.editorBase) : editorPos - this.from } destroy() { for (let event in this.handlers) this.editContext.removeEventListener(event, this.handlers[event]) } +}; var EditorView = class _EditorView { 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 } dispatchTransactions; _root; get root() { return this._root } get win() { return this.dom.ownerDocument.defaultView || window } dom; scrollDOM; contentDOM; announceDOM; viewState; docView; plugins = []; pluginMap = new Map; editorAttrs = {}; contentAttrs = {}; bidiCache = []; destroyed = !1; updateState = 2; observer; measureScheduled = -1; measureRequests = []; constructor(config = {}) { 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), config.parent && config.parent.appendChild(this.dom); let { dispatch } = config; this.dispatchTransactions = config.dispatchTransactions || dispatch && (trs => trs.forEach(tr => dispatch(tr, this))) || (trs => this.update(trs)), this.dispatch = this.dispatch.bind(this), this._root = config.root || getRoot(config.parent) || document, this.viewState = new ViewState(this, config.state || EditorState.create(config)), config.scrollTo && config.scrollTo.is(scrollIntoView) && (this.viewState.scrollTarget = config.scrollTo.value.clip(this.viewState.state)), this.plugins = this.state.facet(viewPlugin).map(spec => new PluginInstance(spec)); for (let plugin2 of this.plugins) plugin2.update(this); this.observer = new DOMObserver(this), this.inputState = new InputState(this), this.inputState.ensureHandlers(this.plugins), this.docView = new DocView(this), this.mountStyles(), this.updateAttrs(), this.updateState = 0, this.requestMeasure(), document.fonts?.ready && document.fonts.ready.then(() => { this.viewState.mustMeasureContent = "refresh", this.requestMeasure() }) } dispatch(...input) { let trs = input.length == 1 && input[0] instanceof Transaction ? input : input.length == 1 && Array.isArray(input[0]) ? input[0] : [this.state.update(...input)]; this.dispatchTransactions(trs, this) } update(transactions) { if (this.updateState != 0) throw new Error("Calls to EditorView.update are not allowed while an update is in progress"); let redrawn = !1, attrsChanged = !1, update, state = this.state; for (let tr of transactions) { if (tr.startState != state) throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state."); state = tr.state } if (this.destroyed) { this.viewState.state = state; return } let focus = this.hasFocus, focusFlag = 0, dispatchFocus = null; transactions.some(tr => tr.annotation(isFocusChange)) ? (this.inputState.notifiedFocused = focus, focusFlag = 1) : focus != this.inputState.notifiedFocused && (this.inputState.notifiedFocused = focus, dispatchFocus = focusChangeTransaction(state, focus), dispatchFocus || (focusFlag = 1)); let pendingKey = this.observer.delayedAndroidKey, domChange = null; if (pendingKey ? (this.observer.clearDelayedAndroidKey(), domChange = this.observer.readChange(), (domChange && !this.state.doc.eq(state.doc) || !this.state.selection.eq(state.selection)) && (domChange = null)) : this.observer.clear(), state.facet(EditorState.phrases) != this.state.facet(EditorState.phrases)) return this.setState(state); update = ViewUpdate.create(this, state, transactions), update.flags |= focusFlag; let scrollTarget = this.viewState.scrollTarget; try { this.updateState = 2; for (let tr of transactions) { if (scrollTarget && (scrollTarget = scrollTarget.map(tr.changes)), tr.scrollIntoView) { let { main } = tr.state.selection, { x, y } = this.state.facet(_EditorView.cursorScrollMargin); scrollTarget = new ScrollTarget(main.empty ? main : EditorSelection.cursor(main.head, main.head > main.anchor ? -1 : 1), "nearest", "nearest", y, x) } for (let e of tr.effects) e.is(scrollIntoView) && (scrollTarget = e.value.clip(this.state)) } this.viewState.update(update, scrollTarget), this.bidiCache = CachedOrder.update(this.bidiCache, update.changes), update.empty || (this.updatePlugins(update), this.inputState.update(update)), redrawn = this.docView.update(update), this.state.facet(styleModule) != this.styleModules && this.mountStyles(), attrsChanged = this.updateAttrs(), this.showAnnouncements(transactions), this.docView.updateSelection(redrawn, transactions.some(tr => tr.isUserEvent("select.pointer"))) } finally { this.updateState = 0 } if (update.startState.facet(theme) != update.state.facet(theme) && (this.viewState.mustMeasureContent = !0), (redrawn || attrsChanged || scrollTarget || this.viewState.mustEnforceCursorAssoc || this.viewState.mustMeasureContent) && this.requestMeasure(), redrawn && this.docViewUpdate(), !update.empty) for (let listener of this.state.facet(updateListener)) try { listener(update) } catch (e) { logException(this.state, e, "update listener") } (dispatchFocus || domChange) && Promise.resolve().then(() => { dispatchFocus && this.state == dispatchFocus.startState && this.dispatch(dispatchFocus), domChange && !applyDOMChange(this, domChange) && pendingKey.force && dispatchKey(this.contentDOM, pendingKey.key, pendingKey.keyCode) }) } setState(newState) { 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 = newState; return } this.updateState = 2; let hadFocus = this.hasFocus; try { for (let plugin2 of this.plugins) plugin2.destroy(this); this.viewState = new ViewState(this, newState), this.plugins = newState.facet(viewPlugin).map(spec => new PluginInstance(spec)), this.pluginMap.clear(); for (let plugin2 of this.plugins) plugin2.update(this); this.docView.destroy(), this.docView = new DocView(this), this.inputState.ensureHandlers(this.plugins), this.mountStyles(), this.updateAttrs(), this.bidiCache = [] } finally { this.updateState = 0 } hadFocus && this.focus(), this.requestMeasure() } updatePlugins(update) { let prevSpecs = update.startState.facet(viewPlugin), specs = update.state.facet(viewPlugin); if (prevSpecs != specs) { let newPlugins = []; for (let spec of specs) { let found = prevSpecs.indexOf(spec); if (found < 0) newPlugins.push(new PluginInstance(spec)); else { let plugin2 = this.plugins[found]; plugin2.mustUpdate = update, newPlugins.push(plugin2) } } for (let plugin2 of this.plugins) plugin2.mustUpdate != update && plugin2.destroy(this); this.plugins = newPlugins, this.pluginMap.clear() } else for (let p of this.plugins) p.mustUpdate = update; for (let i2 = 0; i2 < this.plugins.length; i2++)this.plugins[i2].update(this); prevSpecs != specs && this.inputState.ensureHandlers(this.plugins) } docViewUpdate() { for (let plugin2 of this.plugins) { let val = plugin2.value; if (val && val.docViewUpdate) try { val.docViewUpdate(this) } catch (e) { logException(this.state, e, "doc view update listener") } } } measure(flush = !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, flush && this.observer.forceFlush(); let updated = null, scroll = this.viewState.scrollParent, scrollOffset = this.viewState.getScrollOffset(), { scrollAnchorPos, scrollAnchorHeight } = this.viewState; Math.abs(scrollOffset - this.viewState.scrollOffset) > 1 && (scrollAnchorHeight = -1), this.viewState.scrollAnchorHeight = -1; try { for (let i2 = 0; ; i2++) { if (scrollAnchorHeight < 0) if (isScrolledToBottom(scroll || this.win)) scrollAnchorPos = -1, scrollAnchorHeight = this.viewState.heightMap.height; else { let block = this.viewState.scrollAnchorAt(scrollOffset); scrollAnchorPos = block.from, scrollAnchorHeight = block.top } this.updateState = 1; let changed = this.viewState.measure(); if (!changed && !this.measureRequests.length && this.viewState.scrollTarget == null) break; if (i2 > 5) { console.warn(this.measureRequests.length ? "Measure loop restarted more than 5 times" : "Viewport failed to stabilize"); break } let measuring = []; changed & 4 || ([this.measureRequests, measuring] = [measuring, this.measureRequests]); let measured = measuring.map(m => { try { return m.read(this) } catch (e) { return logException(this.state, e), BadMeasure } }), update = ViewUpdate.create(this, this.state, []), redrawn = !1; update.flags |= changed, updated ? updated.flags |= changed : updated = update, this.updateState = 2, update.empty || (this.updatePlugins(update), this.inputState.update(update), this.updateAttrs(), redrawn = this.docView.update(update), redrawn && this.docViewUpdate()); for (let i3 = 0; i3 < measuring.length; i3++)if (measured[i3] != BadMeasure) try { let m = measuring[i3]; m.write && m.write(measured[i3], this) } catch (e) { logException(this.state, e) } if (redrawn && this.docView.updateSelection(!0), !update.viewportChanged && this.measureRequests.length == 0) { if (this.viewState.editorHeight) if (this.viewState.scrollTarget) { this.docView.scrollIntoView(this.viewState.scrollTarget), this.viewState.scrollTarget = null, scrollAnchorHeight = -1; continue } else { let diff = ((scrollAnchorPos < 0 ? this.viewState.heightMap.height : this.viewState.lineBlockAt(scrollAnchorPos).top) - scrollAnchorHeight) / this.scaleY; if ((diff > 1 || diff < -1) && (scroll == this.scrollDOM || this.hasFocus || Math.max(this.inputState.lastWheelEvent, this.inputState.lastTouchTime) > Date.now() - 100)) { scrollOffset = scrollOffset + diff, scroll ? scroll.scrollTop += diff : this.win.scrollBy(0, diff), scrollAnchorHeight = -1; continue } } break } } } finally { this.updateState = 0, this.measureScheduled = -1 } if (updated && !updated.empty) for (let listener of this.state.facet(updateListener)) listener(updated) } get themeClasses() { return baseThemeID + " " + (this.state.facet(darkTheme) ? baseDarkID : baseLightID) + " " + this.state.facet(theme) } updateAttrs() { let editorAttrs = attrsFromFacet(this, editorAttributes, { class: "cm-editor" + (this.hasFocus ? " cm-focused " : " ") + this.themeClasses }), contentAttrs = { spellcheck: "false", autocorrect: "off", autocapitalize: "off", writingsuggestions: "false", translate: "no", contenteditable: this.state.facet(editable) ? "true" : "false", class: "cm-content", style: `${browser_default.tabSize}: ${this.state.tabSize}`, role: "textbox", "aria-multiline": "true" }; this.state.readOnly && (contentAttrs["aria-readonly"] = "true"), attrsFromFacet(this, contentAttributes, contentAttrs); let changed = this.observer.ignore(() => { let changedContent = updateAttrs(this.contentDOM, this.contentAttrs, contentAttrs), changedEditor = updateAttrs(this.dom, this.editorAttrs, editorAttrs); return changedContent || changedEditor }); return this.editorAttrs = editorAttrs, this.contentAttrs = contentAttrs, changed } showAnnouncements(trs) { let first = !0; for (let tr of trs) for (let effect of tr.effects) if (effect.is(_EditorView.announce)) { first && (this.announceDOM.textContent = ""), first = !1; let div = this.announceDOM.appendChild(document.createElement("div")); div.textContent = effect.value } } mountStyles() { this.styleModules = this.state.facet(styleModule); let nonce = this.state.facet(_EditorView.cspNonce); StyleModule.mount(this.root, this.styleModules.concat(baseTheme).reverse(), nonce ? { nonce } : 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(request) { if (this.measureScheduled < 0 && (this.measureScheduled = this.win.requestAnimationFrame(() => this.measure())), request) { if (this.measureRequests.indexOf(request) > -1) return; if (request.key != null) { for (let i2 = 0; i2 < this.measureRequests.length; i2++)if (this.measureRequests[i2].key === request.key) { this.measureRequests[i2] = request; return } } this.measureRequests.push(request) } } plugin(plugin2) { let known = this.pluginMap.get(plugin2); return (known === void 0 || known && known.plugin != plugin2) && this.pluginMap.set(plugin2, known = this.plugins.find(p => p.plugin == plugin2) || null), known && known.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(height) { return this.readMeasured(), this.viewState.elementAtHeight(height) } lineBlockAtHeight(height) { return this.readMeasured(), this.viewState.lineBlockAtHeight(height) } get viewportLineBlocks() { return this.viewState.viewportLines } lineBlockAt(pos) { return this.viewState.lineBlockAt(pos) } get contentHeight() { return this.viewState.contentHeight } moveByChar(start, forward, by) { return skipAtoms(this, start, moveByChar(this, start, forward, by)) } moveByGroup(start, forward) { return skipAtoms(this, start, moveByChar(this, start, forward, initial => byGroup(this, start.head, initial))) } visualLineSide(line, end) { let order = this.bidiSpans(line), dir = this.textDirectionAt(line.from), span = order[end ? order.length - 1 : 0]; return EditorSelection.cursor(span.side(end, dir) + line.from, span.forward(!end, dir) ? 1 : -1) } moveToLineBoundary(start, forward, includeWrap = !0) { return moveToLineBoundary(this, start, forward, includeWrap) } moveVertically(start, forward, distance) { return skipAtoms(this, start, moveVertically(this, start, forward, distance)) } domAtPos(pos, side = 1) { return this.docView.domAtPos(pos, side) } posAtDOM(node, offset = 0) { return this.docView.posFromDOM(node, offset) } posAtCoords(coords, precise = !0) { this.readMeasured(); let found = posAtCoords(this, coords, precise); return found && found.pos } posAndSideAtCoords(coords, precise = !0) { return this.readMeasured(), posAtCoords(this, coords, precise) } coordsAtPos(pos, side = 1) { this.readMeasured(); let rect = this.docView.coordsAt(pos, side); if (!rect || rect.left == rect.right) return rect; let line = this.state.doc.lineAt(pos), order = this.bidiSpans(line), span = order[BidiSpan.find(order, pos - line.from, -1, side)]; return flattenRect(rect, span.dir == 0 == side > 0) } coordsForChar(pos) { return this.readMeasured(), this.docView.coordsForChar(pos) } get defaultCharacterWidth() { return this.viewState.heightOracle.charWidth } get defaultLineHeight() { return this.viewState.heightOracle.lineHeight } get textDirection() { return this.viewState.defaultTextDirection } textDirectionAt(pos) { return !this.state.facet(perLineTextDirection) || pos < this.viewport.from || pos > this.viewport.to ? this.textDirection : (this.readMeasured(), this.docView.textDirectionAt(pos)) } get lineWrapping() { return this.viewState.heightOracle.lineWrapping } bidiSpans(line) { if (line.length > MaxBidiLine) return trivialOrder(line.length); let dir = this.textDirectionAt(line.from), isolates; for (let entry of this.bidiCache) if (entry.from == line.from && entry.dir == dir && (entry.fresh || isolatesEq(entry.isolates, isolates = getIsolatedRanges(this, line)))) return entry.order; isolates || (isolates = getIsolatedRanges(this, line)); let order = computeOrder(line.text, dir, isolates); return this.bidiCache.push(new CachedOrder(line.from, line.to, dir, isolates, !0, order)), order } get hasFocus() { return (this.dom.ownerDocument.hasFocus() || browser_default.safari && this.inputState?.lastContextMenu > Date.now() - 3e4) && this.root.activeElement == this.contentDOM } focus() { this.observer.ignore(() => { focusPreventScroll(this.contentDOM), this.docView.updateSelection() }) } setRoot(root) { this._root != root && (this._root = root, this.observer.setWindow((root.nodeType == 9 ? root : root.ownerDocument).defaultView || window), this.mountStyles()) } destroy() { this.root.activeElement == this.contentDOM && this.contentDOM.blur(); for (let plugin2 of this.plugins) plugin2.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(pos, options = {}) { return scrollIntoView.of(new ScrollTarget(typeof pos == "number" ? EditorSelection.cursor(pos) : pos, options.y ?? "nearest", options.x ?? "nearest", options.yMargin ?? 5, options.xMargin ?? 5)) } scrollSnapshot() { let { scrollTop, scrollLeft } = this.scrollDOM, ref = this.viewState.scrollAnchorAt(scrollTop); return scrollIntoView.of(new ScrollTarget(EditorSelection.cursor(ref.from), "start", "start", ref.top - scrollTop, scrollLeft, !0)) } setTabFocusMode(to) { to == null ? this.inputState.tabFocusMode = this.inputState.tabFocusMode < 0 ? 0 : -1 : typeof to == "boolean" ? this.inputState.tabFocusMode = to ? 0 : -1 : this.inputState.tabFocusMode != 0 && (this.inputState.tabFocusMode = Date.now() + to) } static styleModule = styleModule; static domEventHandlers(handlers2) { return ViewPlugin.define(() => ({}), { eventHandlers: handlers2 }) } static domEventObservers(observers2) { return ViewPlugin.define(() => ({}), { eventObservers: observers2 }) } static inputHandler = inputHandler; static clipboardInputFilter = clipboardInputFilter; static clipboardOutputFilter = clipboardOutputFilter; static scrollHandler = scrollHandler; static focusChangeEffect = focusChangeEffect; static perLineTextDirection = perLineTextDirection; static exceptionSink = exceptionSink; static updateListener = updateListener; static editable = editable; static mouseSelectionStyle = mouseSelectionStyle; static dragMovesSelection = dragMovesSelection; static clickAddsSelectionRange = clickAddsSelectionRange; static decorations = decorations; static blockWrappers = blockWrappers; static outerDecorations = outerDecorations; static atomicRanges = atomicRanges; static bidiIsolatedRanges = bidiIsolatedRanges; static cursorScrollMargin = Facet.define({ combine: inputs => { let x = 5, y = 5; for (let i2 of inputs) typeof i2 == "number" ? x = y = i2 : { x, y } = i2; return { x, y } } }); static scrollMargins = scrollMargins; static theme(spec, options) { let prefix = StyleModule.newName(), result = [theme.of(prefix), styleModule.of(buildTheme(`.${prefix}`, spec))]; return options && options.dark && result.push(darkTheme.of(!0)), result } static darkTheme = darkTheme; static baseTheme(spec) { return Prec.lowest(styleModule.of(buildTheme("." + baseThemeID, spec, lightDarkIDs))) } static cspNonce = Facet.define({ combine: values => values.length ? values[0] : "" }); static contentAttributes = contentAttributes; static editorAttributes = editorAttributes; static lineWrapping = _EditorView.contentAttributes.of({ class: "cm-lineWrapping" }); static announce = StateEffect.define(); static findFromDOM(dom) { let content2 = dom.querySelector(".cm-content"); return (content2 && Tile.get(content2) || Tile.get(dom))?.root?.view || null } }, MaxBidiLine = 4096, BadMeasure = {}, CachedOrder = class _CachedOrder { constructor(from, to, dir, isolates, fresh, order) { this.from = from; this.to = to; this.dir = dir; this.isolates = isolates; this.fresh = fresh; this.order = order } from; to; dir; isolates; fresh; order; static update(cache, changes) { if (changes.empty && !cache.some(c => c.fresh)) return cache; let result = [], lastDir = cache.length ? cache[cache.length - 1].dir : 0; for (let i2 = Math.max(0, cache.length - 10); i2 < cache.length; i2++) { let entry = cache[i2]; entry.dir == lastDir && !changes.touchesRange(entry.from, entry.to) && result.push(new _CachedOrder(changes.mapPos(entry.from, 1), changes.mapPos(entry.to, -1), entry.dir, entry.isolates, !1, entry.order)) } return result } }; function attrsFromFacet(view, facet, base2) { for (let sources = view.state.facet(facet), i2 = sources.length - 1; i2 >= 0; i2--) { let source = sources[i2], value = typeof source == "function" ? source(view) : source; value && combineAttrs(value, base2) } return base2 } var base = { 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: "'" }, shift = { 48: ")", 49: "!", 50: "@", 51: "#", 52: "$", 53: "%", 54: "^", 55: "&", 56: "*", 57: "(", 59: ":", 61: "+", 173: "_", 186: ":", 187: "+", 188: "<", 189: "_", 190: ">", 191: "?", 192: "~", 219: "{", 220: "|", 221: "}", 222: '"' }, mac = typeof navigator < "u" && /Mac/.test(navigator.platform), ie2 = typeof navigator < "u" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); for (i = 0; i < 10; i++)base[48 + i] = base[96 + i] = String(i); var i; for (i = 1; i <= 24; i++)base[i + 111] = "F" + i; var i; for (i = 65; i <= 90; i++)base[i] = String.fromCharCode(i + 32), shift[i] = String.fromCharCode(i); var i; for (code in base) shift.hasOwnProperty(code) || (shift[code] = base[code]); var code; function keyName(event) { var ignoreKey = mac && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey || ie2 && event.shiftKey && event.key && event.key.length == 1 || event.key == "Unidentified", name2 = !ignoreKey && event.key || (event.shiftKey ? shift : base)[event.keyCode] || event.key || "Unidentified"; return name2 == "Esc" && (name2 = "Escape"), name2 == "Del" && (name2 = "Delete"), name2 == "Left" && (name2 = "ArrowLeft"), name2 == "Up" && (name2 = "ArrowUp"), name2 == "Right" && (name2 = "ArrowRight"), name2 == "Down" && (name2 = "ArrowDown"), name2 } var currentPlatform = browser_default.mac ? "mac" : browser_default.windows ? "win" : browser_default.linux ? "linux" : "key"; function normalizeKeyName(name2, platform) { let parts = name2.split(/-(?!$)/), result = parts[parts.length - 1]; result == "Space" && (result = " "); let alt, ctrl, shift2, meta2; for (let i2 = 0; i2 < parts.length - 1; ++i2) { let mod = parts[i2]; if (/^(cmd|meta|m)$/i.test(mod)) meta2 = !0; else if (/^a(lt)?$/i.test(mod)) alt = !0; else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = !0; else if (/^s(hift)?$/i.test(mod)) shift2 = !0; else if (/^mod$/i.test(mod)) platform == "mac" ? meta2 = !0 : ctrl = !0; else throw new Error("Unrecognized modifier name: " + mod) } return alt && (result = "Alt-" + result), ctrl && (result = "Ctrl-" + result), meta2 && (result = "Meta-" + result), shift2 && (result = "Shift-" + result), result } function modifiers(name2, event, shift2) { return event.altKey && (name2 = "Alt-" + name2), event.ctrlKey && (name2 = "Ctrl-" + name2), event.metaKey && (name2 = "Meta-" + name2), shift2 !== !1 && event.shiftKey && (name2 = "Shift-" + name2), name2 } var handleKeyEvents = Prec.default(EditorView.domEventHandlers({ keydown(event, view) { return runHandlers(getKeymap(view.state), event, view, "editor") } })), keymap = Facet.define({ enables: handleKeyEvents }), Keymaps = new WeakMap; function getKeymap(state) { let bindings = state.facet(keymap), map = Keymaps.get(bindings); return map || Keymaps.set(bindings, map = buildKeymap(bindings.reduce((a, b) => a.concat(b), []))), map } function runScopeHandlers(view, event, scope) { return runHandlers(getKeymap(view.state), event, view, scope) } var storedPrefix = null, PrefixTimeout = 4e3; function buildKeymap(bindings, platform = currentPlatform) { let bound = Object.create(null), isPrefix = Object.create(null), checkPrefix = (name2, is) => { let current = isPrefix[name2]; if (current == null) isPrefix[name2] = is; else if (current != is) throw new Error("Key binding " + name2 + " is used both as a regular binding and as a multi-stroke prefix") }, add2 = (scope, key, command2, preventDefault, stopPropagation) => { let scopeObj = bound[scope] || (bound[scope] = Object.create(null)), parts = key.split(/ (?!$)/).map(k => normalizeKeyName(k, platform)); for (let i2 = 1; i2 < parts.length; i2++) { let prefix = parts.slice(0, i2).join(" "); checkPrefix(prefix, !0), scopeObj[prefix] || (scopeObj[prefix] = { preventDefault: !0, stopPropagation: !1, run: [view => { let ourObj = storedPrefix = { view, prefix, scope }; return setTimeout(() => { storedPrefix == ourObj && (storedPrefix = null) }, PrefixTimeout), !0 }] }) } let full = parts.join(" "); checkPrefix(full, !1); let binding = scopeObj[full] || (scopeObj[full] = { preventDefault: !1, stopPropagation: !1, run: scopeObj._any?.run?.slice() || [] }); command2 && binding.run.push(command2), preventDefault && (binding.preventDefault = !0), stopPropagation && (binding.stopPropagation = !0) }; for (let b of bindings) { let scopes = b.scope ? b.scope.split(" ") : ["editor"]; if (b.any) for (let scope of scopes) { let scopeObj = bound[scope] || (bound[scope] = Object.create(null)); scopeObj._any || (scopeObj._any = { preventDefault: !1, stopPropagation: !1, run: [] }); let { any } = b; for (let key in scopeObj) scopeObj[key].run.push(view => any(view, currentKeyEvent)) } let name2 = b[platform] || b.key; if (name2) for (let scope of scopes) add2(scope, name2, b.run, b.preventDefault, b.stopPropagation), b.shift && add2(scope, "Shift-" + name2, b.shift, b.preventDefault, b.stopPropagation) } return bound } var currentKeyEvent = null; function runHandlers(map, event, view, scope) { currentKeyEvent = event; let name2 = keyName(event), charCode = codePointAt2(name2, 0), isChar = codePointSize2(charCode) == name2.length && name2 != " ", prefix = "", handled = !1, prevented = !1, stopPropagation = !1; storedPrefix && storedPrefix.view == view && storedPrefix.scope == scope && (prefix = storedPrefix.prefix + " ", modifierCodes.indexOf(event.keyCode) < 0 && (prevented = !0, storedPrefix = null)); let ran = new Set, runFor = binding => { if (binding) { for (let cmd2 of binding.run) if (!ran.has(cmd2) && (ran.add(cmd2), cmd2(view))) return binding.stopPropagation && (stopPropagation = !0), !0; binding.preventDefault && (binding.stopPropagation && (stopPropagation = !0), prevented = !0) } return !1 }, scopeObj = map[scope], baseName, shiftName; return scopeObj && (runFor(scopeObj[prefix + modifiers(name2, event, !isChar)]) ? handled = !0 : isChar && (event.altKey || event.metaKey || event.ctrlKey) && !(browser_default.windows && event.ctrlKey && event.altKey) && !(browser_default.mac && event.altKey && !(event.ctrlKey || event.metaKey)) && (baseName = base[event.keyCode]) && baseName != name2 ? (runFor(scopeObj[prefix + modifiers(baseName, event, !0)]) || event.shiftKey && (shiftName = shift[event.keyCode]) != name2 && shiftName != baseName && runFor(scopeObj[prefix + modifiers(shiftName, event, !1)])) && (handled = !0) : isChar && event.shiftKey && runFor(scopeObj[prefix + modifiers(name2, event, !0)]) && (handled = !0), !handled && runFor(scopeObj._any) && (handled = !0)), prevented && (handled = !0), handled && stopPropagation && event.stopPropagation(), currentKeyEvent = null, handled } var RectangleMarker = class _RectangleMarker { constructor(className, left, top2, width, height) { this.className = className; this.left = left; this.top = top2; this.width = width; this.height = height } className; left; top; width; height; draw() { let elt = document.createElement("div"); return elt.className = this.className, this.adjust(elt), elt } update(elt, prev) { return prev.className != this.className ? !1 : (this.adjust(elt), !0) } adjust(elt) { elt.style.left = this.left + "px", elt.style.top = this.top + "px", this.width != null && (elt.style.width = this.width + "px"), elt.style.height = this.height + "px" } eq(p) { return this.left == p.left && this.top == p.top && this.width == p.width && this.height == p.height && this.className == p.className } static forRange(view, className, range) { if (range.empty) { let pos = view.coordsAtPos(range.head, range.assoc || 1); if (!pos) return []; let base2 = getBase(view); return [new _RectangleMarker(className, pos.left - base2.left, pos.top - base2.top, null, pos.bottom - pos.top)] } else return rectanglesForRange(view, className, range) } }; function getBase(view) { let rect = view.scrollDOM.getBoundingClientRect(); return { left: (view.textDirection == 0 ? rect.left : rect.right - view.scrollDOM.clientWidth * view.scaleX) - view.scrollDOM.scrollLeft * view.scaleX, top: rect.top - view.scrollDOM.scrollTop * view.scaleY } } function wrappedLine(view, pos, side, inside) { let coords = view.coordsAtPos(pos, side * 2); if (!coords) return inside; let editorRect = view.dom.getBoundingClientRect(), y = (coords.top + coords.bottom) / 2, left = view.posAtCoords({ x: editorRect.left + 1, y }), right = view.posAtCoords({ x: editorRect.right - 1, y }); return left == null || right == null ? inside : { from: Math.max(inside.from, Math.min(left, right)), to: Math.min(inside.to, Math.max(left, right)) } } function rectanglesForRange(view, className, range) { if (range.to <= view.viewport.from || range.from >= view.viewport.to) return []; let from = Math.max(range.from, view.viewport.from), to = Math.min(range.to, view.viewport.to), ltr = view.textDirection == 0, content2 = view.contentDOM, contentRect = content2.getBoundingClientRect(), base2 = getBase(view), lineElt = content2.querySelector(".cm-line"), lineStyle = lineElt && window.getComputedStyle(lineElt), leftSide = contentRect.left + (lineStyle ? parseInt(lineStyle.paddingLeft) + Math.min(0, parseInt(lineStyle.textIndent)) : 0), rightSide = contentRect.right - (lineStyle ? parseInt(lineStyle.paddingRight) : 0), startBlock = blockAt(view, from, 1), endBlock = blockAt(view, to, -1), visualStart = startBlock.type == 0 ? startBlock : null, visualEnd = endBlock.type == 0 ? endBlock : null; if (visualStart && (view.lineWrapping || startBlock.widgetLineBreaks) && (visualStart = wrappedLine(view, from, 1, visualStart)), visualEnd && (view.lineWrapping || endBlock.widgetLineBreaks) && (visualEnd = wrappedLine(view, to, -1, visualEnd)), visualStart && visualEnd && visualStart.from == visualEnd.from && visualStart.to == visualEnd.to) return pieces(drawForLine(range.from, range.to, visualStart)); { let top2 = visualStart ? drawForLine(range.from, null, visualStart) : drawForWidget(startBlock, !1), bottom = visualEnd ? drawForLine(null, range.to, visualEnd) : drawForWidget(endBlock, !0), between = []; return (visualStart || startBlock).to < (visualEnd || endBlock).from - (visualStart && visualEnd ? 1 : 0) || startBlock.widgetLineBreaks > 1 && top2.bottom + view.defaultLineHeight / 2 < bottom.top ? between.push(piece(leftSide, top2.bottom, rightSide, bottom.top)) : top2.bottom < bottom.top && view.elementAtHeight((top2.bottom + bottom.top) / 2).type == 0 && (top2.bottom = bottom.top = (top2.bottom + bottom.top) / 2), pieces(top2).concat(between).concat(pieces(bottom)) } function piece(left, top2, right, bottom) { return new RectangleMarker(className, left - base2.left, top2 - base2.top, Math.max(0, right - left), bottom - top2) } function pieces({ top: top2, bottom, horizontal }) { let pieces2 = []; for (let i2 = 0; i2 < horizontal.length; i2 += 2)pieces2.push(piece(horizontal[i2], top2, horizontal[i2 + 1], bottom)); return pieces2 } function drawForLine(from2, to2, line) { let top2 = 1e9, bottom = -1e9, horizontal = []; function addSpan(from3, fromOpen, to3, toOpen, dir) { let fromCoords = view.coordsAtPos(from3, from3 == line.to ? -2 : 2), toCoords = view.coordsAtPos(to3, to3 == line.from ? 2 : -2); !fromCoords || !toCoords || (top2 = Math.min(fromCoords.top, toCoords.top, top2), bottom = Math.max(fromCoords.bottom, toCoords.bottom, bottom), dir == 0 ? horizontal.push(ltr && fromOpen ? leftSide : fromCoords.left, ltr && toOpen ? rightSide : toCoords.right) : horizontal.push(!ltr && toOpen ? leftSide : toCoords.left, !ltr && fromOpen ? rightSide : fromCoords.right)) } let start = from2 ?? line.from, end = to2 ?? line.to; for (let r of view.visibleRanges) if (r.to > start && r.from < end) for (let pos = Math.max(r.from, start), endPos = Math.min(r.to, end); ;) { let docLine = view.state.doc.lineAt(pos); for (let span of view.bidiSpans(docLine)) { let spanFrom = span.from + docLine.from, spanTo = span.to + docLine.from; if (spanFrom >= endPos) break; spanTo > pos && addSpan(Math.max(spanFrom, pos), from2 == null && spanFrom <= start, Math.min(spanTo, endPos), to2 == null && spanTo >= end, span.dir) } if (pos = docLine.to + 1, pos >= endPos) break } return horizontal.length == 0 && addSpan(start, from2 == null, end, to2 == null, view.textDirection), { top: top2, bottom, horizontal } } function drawForWidget(block, top2) { let y = contentRect.top + (top2 ? block.top : block.bottom); return { top: y, bottom: y, horizontal: [] } } } function sameMarker(a, b) { return a.constructor == b.constructor && a.eq(b) } var LayerView = class { constructor(view, layer2) { this.view = view; this.layer = layer2; this.measureReq = { read: this.measure.bind(this), write: this.draw.bind(this) }, this.dom = view.scrollDOM.appendChild(document.createElement("div")), this.dom.classList.add("cm-layer"), layer2.above && this.dom.classList.add("cm-layer-above"), layer2.class && this.dom.classList.add(layer2.class), this.scale(), this.dom.setAttribute("aria-hidden", "true"), this.setOrder(view.state), view.requestMeasure(this.measureReq), layer2.mount && layer2.mount(this.dom, view) } view; layer; measureReq; dom; drawn = []; scaleX = 1; scaleY = 1; update(update) { update.startState.facet(layerOrder) != update.state.facet(layerOrder) && this.setOrder(update.state), (this.layer.update(update, this.dom) || update.geometryChanged) && (this.scale(), update.view.requestMeasure(this.measureReq)) } docViewUpdate(view) { this.layer.updateOnDocViewUpdate !== !1 && view.requestMeasure(this.measureReq) } setOrder(state) { let pos = 0, order = state.facet(layerOrder); for (; pos < order.length && order[pos] != this.layer;)pos++; this.dom.style.zIndex = String((this.layer.above ? 150 : -1) - pos) } measure() { return this.layer.markers(this.view) } scale() { let { scaleX, scaleY } = this.view; (scaleX != this.scaleX || scaleY != this.scaleY) && (this.scaleX = scaleX, this.scaleY = scaleY, this.dom.style.transform = `scale(${1 / scaleX}, ${1 / scaleY})`) } draw(markers) { if (markers.length != this.drawn.length || markers.some((p, i2) => !sameMarker(p, this.drawn[i2]))) { let old = this.dom.firstChild, oldI = 0; for (let marker of markers) marker.update && old && marker.constructor && this.drawn[oldI].constructor && marker.update(old, this.drawn[oldI]) ? (old = old.nextSibling, oldI++) : this.dom.insertBefore(marker.draw(), old); for (; old;) { let next = old.nextSibling; old.remove(), old = next } this.drawn = markers, browser_default.webkit && (this.dom.style.display = this.dom.firstChild ? "" : "none") } } destroy() { this.layer.destroy && this.layer.destroy(this.dom, this.view), this.dom.remove() } }, layerOrder = Facet.define(); function layer(config) { return [ViewPlugin.define(v => new LayerView(v, config)), layerOrder.of(config)] } var selectionConfig = Facet.define({ combine(configs) { return combineConfig(configs, { cursorBlinkRate: 1200, drawRangeCursor: !0, iosSelectionHandles: !0 }, { cursorBlinkRate: (a, b) => Math.min(a, b), drawRangeCursor: (a, b) => a || b }) } }); function drawSelection(config = {}) { return [selectionConfig.of(config), cursorLayer, selectionLayer, hideNativeSelection, nativeSelectionHidden.of(!0)] } function getDrawSelectionConfig(state) { return state.facet(selectionConfig) } function configChanged(update) { return update.startState.facet(selectionConfig) != update.state.facet(selectionConfig) } var cursorLayer = layer({ above: !0, markers(view) { let { state } = view, conf = state.facet(selectionConfig), cursors = []; for (let r of state.selection.ranges) { let prim = r == state.selection.main; if (r.empty || conf.drawRangeCursor && !(prim && browser_default.ios && conf.iosSelectionHandles)) { let className = prim ? "cm-cursor cm-cursor-primary" : "cm-cursor cm-cursor-secondary", cursor = r.empty ? r : EditorSelection.cursor(r.head, r.assoc); for (let piece of RectangleMarker.forRange(view, className, cursor)) cursors.push(piece) } } return cursors }, update(update, dom) { update.transactions.some(tr => tr.selection) && (dom.style.animationName = dom.style.animationName == "cm-blink" ? "cm-blink2" : "cm-blink"); let confChange = configChanged(update); return confChange && setBlinkRate(update.state, dom), update.docChanged || update.selectionSet || confChange }, mount(dom, view) { setBlinkRate(view.state, dom) }, class: "cm-cursorLayer" }); function setBlinkRate(state, dom) { dom.style.animationDuration = state.facet(selectionConfig).cursorBlinkRate + "ms" } var selectionLayer = layer({ above: !1, markers(view) { let markers = [], { main, ranges } = view.state.selection; for (let r of ranges) if (!r.empty) for (let marker of RectangleMarker.forRange(view, "cm-selectionBackground", r)) markers.push(marker); if (browser_default.ios && !main.empty && view.state.facet(selectionConfig).iosSelectionHandles) { for (let piece of RectangleMarker.forRange(view, "cm-selectionHandle cm-selectionHandle-start", EditorSelection.cursor(main.from, 1))) markers.push(piece); for (let piece of RectangleMarker.forRange(view, "cm-selectionHandle cm-selectionHandle-end", EditorSelection.cursor(main.to, 1))) markers.push(piece) } return markers }, update(update, dom) { return update.docChanged || update.selectionSet || update.viewportChanged || configChanged(update) }, class: "cm-selectionLayer" }), hideNativeSelection = Prec.highest(EditorView.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 setDropCursorPos = StateEffect.define({ map(pos, mapping) { return pos == null ? null : mapping.mapPos(pos) } }), dropCursorPos = StateField.define({ create() { return null }, update(pos, tr) { return pos != null && (pos = tr.changes.mapPos(pos)), tr.effects.reduce((pos2, e) => e.is(setDropCursorPos) ? e.value : pos2, pos) } }), drawDropCursor = ViewPlugin.fromClass(class { constructor(view) { this.view = view; this.measureReq = { read: this.readPos.bind(this), write: this.drawCursor.bind(this) } } view; cursor = null; measureReq; update(update) { let cursorPos = update.state.field(dropCursorPos); cursorPos == null ? this.cursor != null && (this.cursor?.remove(), this.cursor = null) : (this.cursor || (this.cursor = this.view.scrollDOM.appendChild(document.createElement("div")), this.cursor.className = "cm-dropCursor"), (update.startState.field(dropCursorPos) != cursorPos || update.docChanged || update.geometryChanged) && this.view.requestMeasure(this.measureReq)) } readPos() { let { view } = this, pos = view.state.field(dropCursorPos), rect = pos != null && view.coordsAtPos(pos); if (!rect) return null; let outer = view.scrollDOM.getBoundingClientRect(); return { left: rect.left - outer.left + view.scrollDOM.scrollLeft * view.scaleX, top: rect.top - outer.top + view.scrollDOM.scrollTop * view.scaleY, height: rect.bottom - rect.top } } drawCursor(pos) { if (this.cursor) { let { scaleX, scaleY } = this.view; pos ? (this.cursor.style.left = pos.left / scaleX + "px", this.cursor.style.top = pos.top / scaleY + "px", this.cursor.style.height = pos.height / scaleY + "px") : this.cursor.style.left = "-100000px" } } destroy() { this.cursor && this.cursor.remove() } setDropPos(pos) { this.view.state.field(dropCursorPos) != pos && this.view.dispatch({ effects: setDropCursorPos.of(pos) }) } }, { eventObservers: { dragover(event) { this.setDropPos(this.view.posAtCoords({ x: event.clientX, y: event.clientY })) }, dragleave(event) { (event.target == this.view.contentDOM || !this.view.contentDOM.contains(event.relatedTarget)) && this.setDropPos(null) }, dragend() { this.setDropPos(null) }, drop() { this.setDropPos(null) } } }); function dropCursor() { return [dropCursorPos, drawDropCursor] } function iterMatches(doc2, re, from, to, f) { re.lastIndex = 0; for (let cursor = doc2.iterRange(from, to), pos = from, m; !cursor.next().done; pos += cursor.value.length)if (!cursor.lineBreak) for (; m = re.exec(cursor.value);)f(pos + m.index, m) } function matchRanges(view, maxLength) { let visible = view.visibleRanges; if (visible.length == 1 && visible[0].from == view.viewport.from && visible[0].to == view.viewport.to) return visible; let result = []; for (let { from, to } of visible) from = Math.max(view.state.doc.lineAt(from).from, from - maxLength), to = Math.min(view.state.doc.lineAt(to).to, to + maxLength), result.length && result[result.length - 1].to >= from ? result[result.length - 1].to = to : result.push({ from, to }); return result } var MatchDecorator = class { regexp; addMatch; boundary; maxLength; constructor(config) { let { regexp, decoration, decorate, boundary, maxLength = 1e3 } = config; if (!regexp.global) throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set"); if (this.regexp = regexp, decorate) this.addMatch = (match, view, from, add2) => decorate(add2, from, from + match[0].length, match, view); else if (typeof decoration == "function") this.addMatch = (match, view, from, add2) => { let deco = decoration(match, view, from); deco && add2(from, from + match[0].length, deco) }; else if (decoration) this.addMatch = (match, _view, from, add2) => add2(from, from + match[0].length, decoration); else throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator"); this.boundary = boundary, this.maxLength = maxLength } createDeco(view) { let build = new RangeSetBuilder, add2 = build.add.bind(build); for (let { from, to } of matchRanges(view, this.maxLength)) iterMatches(view.state.doc, this.regexp, from, to, (from2, m) => this.addMatch(m, view, from2, add2)); return build.finish() } updateDeco(update, deco) { let changeFrom = 1e9, changeTo = -1; return update.docChanged && update.changes.iterChanges((_f, _t, from, to) => { to >= update.view.viewport.from && from <= update.view.viewport.to && (changeFrom = Math.min(from, changeFrom), changeTo = Math.max(to, changeTo)) }), update.viewportMoved || changeTo - changeFrom > 1e3 ? this.createDeco(update.view) : changeTo > -1 ? this.updateRange(update.view, deco.map(update.changes), changeFrom, changeTo) : deco } updateRange(view, deco, updateFrom, updateTo) { for (let r of view.visibleRanges) { let from = Math.max(r.from, updateFrom), to = Math.min(r.to, updateTo); if (to >= from) { let fromLine = view.state.doc.lineAt(from), toLine = fromLine.to < to ? view.state.doc.lineAt(to) : fromLine, start = Math.max(r.from, fromLine.from), end = Math.min(r.to, toLine.to); if (this.boundary) { for (; from > fromLine.from; from--)if (this.boundary.test(fromLine.text[from - 1 - fromLine.from])) { start = from; break } for (; to < toLine.to; to++)if (this.boundary.test(toLine.text[to - toLine.from])) { end = to; break } } let ranges = [], m, add2 = (from2, to2, deco2) => ranges.push(deco2.range(from2, to2)); if (fromLine == toLine) for (this.regexp.lastIndex = start - fromLine.from; (m = this.regexp.exec(fromLine.text)) && m.index < end - fromLine.from;)this.addMatch(m, view, m.index + fromLine.from, add2); else iterMatches(view.state.doc, this.regexp, start, end, (from2, m2) => this.addMatch(m2, view, from2, add2)); deco = deco.update({ filterFrom: start, filterTo: end, filter: (from2, to2) => from2 < start || to2 > end, add: ranges }) } } return deco } }; var UnicodeRegexpSupport = /x/.unicode != null ? "gu" : "g", Specials = new RegExp(`[\0-\b +-\x7F-\x9F\xAD\u061C\u200B\u200E\u200F\u2028\u2029\u202D\u202E\u2066\u2067\u2069\uFEFF\uFFF9-\uFFFC]`, UnicodeRegexpSupport), Names = { 0: "null", 7: "bell", 8: "backspace", 10: "newline", 11: "vertical tab", 13: "carriage return", 27: "escape", 8203: "zero width space", 8204: "zero width non-joiner", 8205: "zero width joiner", 8206: "left-to-right mark", 8207: "right-to-left mark", 8232: "line separator", 8237: "left-to-right override", 8238: "right-to-left override", 8294: "left-to-right isolate", 8295: "right-to-left isolate", 8297: "pop directional isolate", 8233: "paragraph separator", 65279: "zero width no-break space", 65532: "object replacement" }, _supportsTabSize = null; function supportsTabSize() { if (_supportsTabSize == null && typeof document < "u" && document.body) { let styles = document.body.style; _supportsTabSize = (styles.tabSize ?? styles.MozTabSize) != null } return _supportsTabSize || !1 } var specialCharConfig = Facet.define({ combine(configs) { let config = combineConfig(configs, { render: null, specialChars: Specials, addSpecialChars: null }); return (config.replaceTabs = !supportsTabSize()) && (config.specialChars = new RegExp(" |" + config.specialChars.source, UnicodeRegexpSupport)), config.addSpecialChars && (config.specialChars = new RegExp(config.specialChars.source + "|" + config.addSpecialChars.source, UnicodeRegexpSupport)), config } }); function highlightSpecialChars(config = {}) { return [specialCharConfig.of(config), specialCharPlugin()] } var _plugin = null; function specialCharPlugin() { return _plugin || (_plugin = ViewPlugin.fromClass(class { constructor(view) { this.view = view; this.decorator = this.makeDecorator(view.state.facet(specialCharConfig)), this.decorations = this.decorator.createDeco(view) } view; decorations = Decoration.none; decorationCache = Object.create(null); decorator; makeDecorator(conf) { return new MatchDecorator({ regexp: conf.specialChars, decoration: (m, view, pos) => { let { doc: doc2 } = view.state, code2 = codePointAt2(m[0], 0); if (code2 == 9) { let line = doc2.lineAt(pos), size = view.state.tabSize, col = countColumn(line.text, size, pos - line.from); return Decoration.replace({ widget: new TabWidget((size - col % size) * this.view.defaultCharacterWidth / this.view.scaleX) }) } return this.decorationCache[code2] || (this.decorationCache[code2] = Decoration.replace({ widget: new SpecialCharWidget(conf, code2) })) }, boundary: conf.replaceTabs ? void 0 : /[^]/ }) } update(update) { let conf = update.state.facet(specialCharConfig); update.startState.facet(specialCharConfig) != conf ? (this.decorator = this.makeDecorator(conf), this.decorations = this.decorator.createDeco(update.view)) : this.decorations = this.decorator.updateDeco(update, this.decorations) } }, { decorations: v => v.decorations })) } var DefaultPlaceholder = "\u2022"; function placeholder(code2) { return code2 >= 32 ? DefaultPlaceholder : code2 == 10 ? "\u2424" : String.fromCharCode(9216 + code2) } var SpecialCharWidget = class extends WidgetType { constructor(options, code2) { super(); this.options = options; this.code = code2 } options; code; eq(other) { return other.code == this.code } toDOM(view) { let ph = placeholder(this.code), desc = view.state.phrase("Control character") + " " + (Names[this.code] || "0x" + this.code.toString(16)), custom = this.options.render && this.options.render(this.code, desc, ph); if (custom) return custom; let span = document.createElement("span"); return span.textContent = ph, span.title = desc, span.setAttribute("aria-label", desc), span.className = "cm-specialChar", span } ignoreEvent() { return !1 } }, TabWidget = class extends WidgetType { constructor(width) { super(); this.width = width } width; eq(other) { return other.width == this.width } toDOM() { let span = document.createElement("span"); return span.textContent = " ", span.className = "cm-tab", span.style.width = this.width + "px", span } ignoreEvent() { return !1 } }; var plugin = ViewPlugin.fromClass(class { height = 1e3; attrs = { style: "padding-bottom: 1000px" }; update(update) { let { view } = update, height = view.viewState.editorHeight - view.defaultLineHeight - view.documentPadding.top - .5; height >= 0 && height != this.height && (this.height = height, this.attrs = { style: `padding-bottom: ${height}px` }) } }); function scrollPastEnd() { return [plugin, contentAttributes.of(view => view.plugin(plugin)?.attrs || null)] } function highlightActiveLine() { return activeLineHighlighter } var lineDeco = Decoration.line({ class: "cm-activeLine" }), activeLineHighlighter = ViewPlugin.fromClass(class { decorations; constructor(view) { this.decorations = this.getDeco(view) } update(update) { (update.docChanged || update.selectionSet) && (this.decorations = this.getDeco(update.view)) } getDeco(view) { let lastLineStart = -1, deco = []; for (let r of view.state.selection.ranges) { let line = view.lineBlockAt(r.head); line.from > lastLineStart && (deco.push(lineDeco.range(line.from)), lastLineStart = line.from) } return Decoration.set(deco) } }, { decorations: v => v.decorations }); var Placeholder = class extends WidgetType { constructor(content2) { super(); this.content = content2 } content; toDOM(view) { let wrap = document.createElement("span"); return wrap.className = "cm-placeholder", wrap.style.pointerEvents = "none", wrap.appendChild(typeof this.content == "string" ? document.createTextNode(this.content) : typeof this.content == "function" ? this.content(view) : this.content.cloneNode(!0)), wrap.setAttribute("aria-hidden", "true"), wrap } coordsAt(dom) { let rects = dom.firstChild ? clientRectsFor(dom.firstChild) : []; if (!rects.length) return null; let style = window.getComputedStyle(dom.parentNode), rect = flattenRect(rects[0], style.direction != "rtl"), lineHeight = parseInt(style.lineHeight); return rect.bottom - rect.top > lineHeight * 1.5 ? { left: rect.left, right: rect.right, top: rect.top, bottom: rect.top + lineHeight } : rect } ignoreEvent() { return !1 } }; function placeholder2(content2) { let plugin2 = ViewPlugin.fromClass(class { constructor(view) { this.view = view; this.placeholder = content2 ? Decoration.set([Decoration.widget({ widget: new Placeholder(content2), side: 1 }).range(0)]) : Decoration.none } view; placeholder; get decorations() { return this.view.state.doc.length ? Decoration.none : this.placeholder } }, { decorations: v => v.decorations }); return typeof content2 == "string" ? [plugin2, EditorView.contentAttributes.of({ "aria-placeholder": content2 })] : plugin2 } var MaxOff = 2e3; function rectangleFor(state, a, b) { let startLine = Math.min(a.line, b.line), endLine = Math.max(a.line, b.line), ranges = []; if (a.off > MaxOff || b.off > MaxOff || a.col < 0 || b.col < 0) { let startOff = Math.min(a.off, b.off), endOff = Math.max(a.off, b.off); for (let i2 = startLine; i2 <= endLine; i2++) { let line = state.doc.line(i2); line.length <= endOff && ranges.push(EditorSelection.range(line.from + startOff, line.to + endOff)) } } else { let startCol = Math.min(a.col, b.col), endCol = Math.max(a.col, b.col); for (let i2 = startLine; i2 <= endLine; i2++) { let line = state.doc.line(i2), start = findColumn(line.text, startCol, state.tabSize, !0); if (start < 0) ranges.push(EditorSelection.cursor(line.to)); else { let end = findColumn(line.text, endCol, state.tabSize); ranges.push(EditorSelection.range(line.from + start, line.from + end)) } } } return ranges } function absoluteColumn(view, x) { let ref = view.coordsAtPos(view.viewport.from); return ref ? Math.round(Math.abs((ref.left - x) / view.defaultCharacterWidth)) : -1 } function getPos(view, event) { let offset = view.posAtCoords({ x: event.clientX, y: event.clientY }, !1), line = view.state.doc.lineAt(offset), off = offset - line.from, col = off > MaxOff ? -1 : off == line.length ? absoluteColumn(view, event.clientX) : countColumn(line.text, view.state.tabSize, offset - line.from); return { line: line.number, col, off } } function rectangleSelectionStyle(view, event) { let start = getPos(view, event), startSel = view.state.selection; return start ? { update(update) { if (update.docChanged) { let newStart = update.changes.mapPos(update.startState.doc.line(start.line).from), newLine = update.state.doc.lineAt(newStart); start = { line: newLine.number, col: start.col, off: Math.min(start.off, newLine.length) }, startSel = startSel.map(update.changes) } }, get(event2, _extend, multiple) { let cur = getPos(view, event2); if (!cur) return startSel; let ranges = rectangleFor(view.state, start, cur); return ranges.length ? multiple ? EditorSelection.create(ranges.concat(startSel.ranges)) : EditorSelection.create(ranges) : startSel } } : null } function rectangularSelection(options) { let filter = options?.eventFilter || (e => e.altKey && e.button == 0); return EditorView.mouseSelectionStyle.of((view, event) => filter(event) ? rectangleSelectionStyle(view, event) : null) } var keys = { Alt: [18, e => !!e.altKey], Control: [17, e => !!e.ctrlKey], Shift: [16, e => !!e.shiftKey], Meta: [91, e => !!e.metaKey] }, showCrosshair = { style: "cursor: crosshair" }; function crosshairCursor(options = {}) { let [code2, getter] = keys[options.key || "Alt"], plugin2 = ViewPlugin.fromClass(class { constructor(view) { this.view = view } view; isDown = !1; set(isDown) { this.isDown != isDown && (this.isDown = isDown, this.view.update([])) } }, { eventObservers: { keydown(e) { this.set(e.keyCode == code2 || getter(e)) }, keyup(e) { (e.keyCode == code2 || !getter(e)) && this.set(!1) }, mousemove(e) { this.set(getter(e)) } } }); return [plugin2, EditorView.contentAttributes.of(view => view.plugin(plugin2)?.isDown ? showCrosshair : null)] } var Outside = "-10000px"; var TooltipViewManager = class { constructor(view, facet, createTooltipView, removeTooltipView) { this.facet = facet; this.createTooltipView = createTooltipView; this.removeTooltipView = removeTooltipView; this.input = view.state.facet(facet), this.tooltips = this.input.filter(t2 => t2); let prev = null; this.tooltipViews = this.tooltips.map(t2 => prev = createTooltipView(t2, prev)) } facet; createTooltipView; removeTooltipView; input; tooltips; tooltipViews; update(update, above) { let input = update.state.facet(this.facet), tooltips2 = input.filter(x => x); if (input === this.input) { for (let t2 of this.tooltipViews) t2.update && t2.update(update); return !1 } let tooltipViews = [], newAbove = above ? [] : null; for (let i2 = 0; i2 < tooltips2.length; i2++) { let tip = tooltips2[i2], known = -1; if (tip) { for (let i3 = 0; i3 < this.tooltips.length; i3++) { let other = this.tooltips[i3]; other && other.create == tip.create && (known = i3) } if (known < 0) tooltipViews[i2] = this.createTooltipView(tip, i2 ? tooltipViews[i2 - 1] : null), newAbove && (newAbove[i2] = !!tip.above); else { let tooltipView = tooltipViews[i2] = this.tooltipViews[known]; newAbove && (newAbove[i2] = above[known]), tooltipView.update && tooltipView.update(update) } } } for (let t2 of this.tooltipViews) tooltipViews.indexOf(t2) < 0 && (this.removeTooltipView(t2), t2.destroy?.()); return above && (newAbove.forEach((val, i2) => above[i2] = val), above.length = newAbove.length), this.input = input, this.tooltips = tooltips2, this.tooltipViews = tooltipViews, !0 } }; function tooltips(config = {}) { return tooltipConfig.of(config) } function windowSpace(view) { let docElt = view.dom.ownerDocument.documentElement; return { top: 0, left: 0, bottom: docElt.clientHeight, right: docElt.clientWidth } } var tooltipConfig = Facet.define({ combine: values => ({ position: browser_default.ios ? "absolute" : values.find(conf => conf.position)?.position || "fixed", parent: values.find(conf => conf.parent)?.parent || null, tooltipSpace: values.find(conf => conf.tooltipSpace)?.tooltipSpace || windowSpace }) }), knownHeight = new WeakMap, tooltipPlugin = ViewPlugin.fromClass(class { constructor(view) { this.view = view; let config = view.state.facet(tooltipConfig); this.position = config.position, this.parent = config.parent, this.classes = view.themeClasses, this.createContainer(), this.measureReq = { read: this.readMeasure.bind(this), write: this.writeMeasure.bind(this), key: this }, this.resizeObserver = typeof ResizeObserver == "function" ? new ResizeObserver(() => this.measureSoon()) : null, this.manager = new TooltipViewManager(view, showTooltip, (t2, p) => this.createTooltip(t2, p), t2 => { this.resizeObserver && this.resizeObserver.unobserve(t2.dom), t2.dom.remove() }), this.above = this.manager.tooltips.map(t2 => !!t2.above), this.intersectionObserver = typeof IntersectionObserver == "function" ? new IntersectionObserver(entries => { Date.now() > this.lastTransaction - 50 && entries.length > 0 && entries[entries.length - 1].intersectionRatio < 1 && this.measureSoon() }, { threshold: [1] }) : null, this.observeIntersection(), view.win.addEventListener("resize", this.measureSoon = this.measureSoon.bind(this)), this.maybeMeasure() } view; manager; above = []; measureReq; inView = !0; position; madeAbsolute = !1; parent; classes; intersectionObserver; resizeObserver; lastTransaction = 0; measureTimeout = -1; createContainer() { this.parent ? (this.container = document.createElement("div"), this.container.style.position = "relative", this.container.className = this.view.themeClasses, this.parent.appendChild(this.container)) : this.container = this.view.dom } observeIntersection() { if (this.intersectionObserver) { this.intersectionObserver.disconnect(); for (let tooltip of this.manager.tooltipViews) this.intersectionObserver.observe(tooltip.dom) } } measureSoon() { this.measureTimeout < 0 && (this.measureTimeout = setTimeout(() => { this.measureTimeout = -1, this.maybeMeasure() }, 50)) } update(update) { update.transactions.length && (this.lastTransaction = Date.now()); let updated = this.manager.update(update, this.above); updated && this.observeIntersection(); let shouldMeasure = updated || update.geometryChanged, newConfig = update.state.facet(tooltipConfig); if (newConfig.position != this.position && !this.madeAbsolute) { this.position = newConfig.position; for (let t2 of this.manager.tooltipViews) t2.dom.style.position = this.position; shouldMeasure = !0 } if (newConfig.parent != this.parent) { this.parent && this.container.remove(), this.parent = newConfig.parent, this.createContainer(); for (let t2 of this.manager.tooltipViews) this.container.appendChild(t2.dom); shouldMeasure = !0 } else this.parent && this.view.themeClasses != this.classes && (this.classes = this.container.className = this.view.themeClasses); shouldMeasure && this.maybeMeasure() } createTooltip(tooltip, prev) { let tooltipView = tooltip.create(this.view), before = prev ? prev.dom : null; if (tooltipView.dom.classList.add("cm-tooltip"), tooltip.arrow && !tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")) { let arrow = document.createElement("div"); arrow.className = "cm-tooltip-arrow", tooltipView.dom.appendChild(arrow) } return tooltipView.dom.style.position = this.position, tooltipView.dom.style.top = Outside, tooltipView.dom.style.left = "0px", this.container.insertBefore(tooltipView.dom, before), tooltipView.mount && tooltipView.mount(this.view), this.resizeObserver && this.resizeObserver.observe(tooltipView.dom), tooltipView } destroy() { this.view.win.removeEventListener("resize", this.measureSoon); for (let tooltipView of this.manager.tooltipViews) tooltipView.dom.remove(), tooltipView.destroy?.(); this.parent && this.container.remove(), this.resizeObserver?.disconnect(), this.intersectionObserver?.disconnect(), clearTimeout(this.measureTimeout) } readMeasure() { let scaleX = 1, scaleY = 1, makeAbsolute = !1; if (this.position == "fixed" && this.manager.tooltipViews.length) { let { dom } = this.manager.tooltipViews[0]; if (browser_default.safari) { let rect = dom.getBoundingClientRect(); makeAbsolute = Math.abs(rect.top + 1e4) > 1 || Math.abs(rect.left) > 1 } else makeAbsolute = !!dom.offsetParent && dom.offsetParent != this.container.ownerDocument.body } if (makeAbsolute || this.position == "absolute") if (this.parent) { let rect = this.parent.getBoundingClientRect(); rect.width && rect.height && (scaleX = rect.width / this.parent.offsetWidth, scaleY = rect.height / this.parent.offsetHeight) } else ({ scaleX, scaleY } = this.view.viewState); let visible = this.view.scrollDOM.getBoundingClientRect(), margins = getScrollMargins(this.view); return { visible: { left: visible.left + margins.left, top: visible.top + margins.top, right: visible.right - margins.right, bottom: visible.bottom - margins.bottom }, parent: this.parent ? this.container.getBoundingClientRect() : this.view.dom.getBoundingClientRect(), pos: this.manager.tooltips.map((t2, i2) => { let tv = this.manager.tooltipViews[i2]; return tv.getCoords ? tv.getCoords(t2.pos) : this.view.coordsAtPos(t2.pos) }), size: this.manager.tooltipViews.map(({ dom }) => dom.getBoundingClientRect()), space: this.view.state.facet(tooltipConfig).tooltipSpace(this.view), scaleX, scaleY, makeAbsolute } } writeMeasure(measured) { if (measured.makeAbsolute) { this.madeAbsolute = !0, this.position = "absolute"; for (let t2 of this.manager.tooltipViews) t2.dom.style.position = "absolute" } let { visible, space, scaleX, scaleY } = measured, others = []; for (let i2 = 0; i2 < this.manager.tooltips.length; i2++) { let tooltip = this.manager.tooltips[i2], tView = this.manager.tooltipViews[i2], { dom } = tView, pos = measured.pos[i2], size = measured.size[i2]; if (!pos || tooltip.clip !== !1 && (pos.bottom <= Math.max(visible.top, space.top) || pos.top >= Math.min(visible.bottom, space.bottom) || pos.right < Math.max(visible.left, space.left) - .1 || pos.left > Math.min(visible.right, space.right) + .1)) { dom.style.top = Outside; continue } let arrow = tooltip.arrow ? tView.dom.querySelector(".cm-tooltip-arrow") : null, arrowHeight = arrow ? 7 : 0, width = size.right - size.left, height = knownHeight.get(tView) ?? size.bottom - size.top, offset = tView.offset || noOffset, ltr = this.view.textDirection == 0, left = size.width > space.right - space.left ? ltr ? space.left : space.right - size.width : ltr ? Math.max(space.left, Math.min(pos.left - (arrow ? 14 : 0) + offset.x, space.right - width)) : Math.min(Math.max(space.left, pos.left - width + (arrow ? 14 : 0) - offset.x), space.right - width), above = this.above[i2]; !tooltip.strictSide && (above ? pos.top - height - arrowHeight - offset.y < space.top : pos.bottom + height + arrowHeight + offset.y > space.bottom) && above == space.bottom - pos.bottom > pos.top - space.top && (above = this.above[i2] = !above); let spaceVert = (above ? pos.top - space.top : space.bottom - pos.bottom) - arrowHeight; if (spaceVert < height && tView.resize !== !1) { if (spaceVert < this.view.defaultLineHeight) { dom.style.top = Outside; continue } knownHeight.set(tView, height), dom.style.height = (height = spaceVert) / scaleY + "px" } else dom.style.height && (dom.style.height = ""); let top2 = above ? pos.top - height - arrowHeight - offset.y : pos.bottom + arrowHeight + offset.y, right = left + width; if (tView.overlap !== !0) for (let r of others) r.left < right && r.right > left && r.top < top2 + height && r.bottom > top2 && (top2 = above ? r.top - height - 2 - arrowHeight : r.bottom + arrowHeight + 2); if (this.position == "absolute" ? (dom.style.top = (top2 - measured.parent.top) / scaleY + "px", setLeftStyle(dom, (left - measured.parent.left) / scaleX)) : (dom.style.top = top2 / scaleY + "px", setLeftStyle(dom, left / scaleX)), arrow) { let arrowLeft = pos.left + (ltr ? offset.x : -offset.x) - (left + 14 - 7); arrow.style.left = arrowLeft / scaleX + "px" } tView.overlap !== !0 && others.push({ left, top: top2, right, bottom: top2 + height }), dom.classList.toggle("cm-tooltip-above", above), dom.classList.toggle("cm-tooltip-below", !above), tView.positioned && tView.positioned(measured.space) } } maybeMeasure() { if (this.manager.tooltips.length && (this.view.inView && this.view.requestMeasure(this.measureReq), this.inView != this.view.inView && (this.inView = this.view.inView, !this.inView))) for (let tv of this.manager.tooltipViews) tv.dom.style.top = Outside } }, { eventObservers: { scroll() { this.maybeMeasure() } } }); function setLeftStyle(elt, value) { let current = parseInt(elt.style.left, 10); (isNaN(current) || Math.abs(value - current) > 1) && (elt.style.left = value + "px") } var baseTheme2 = EditorView.baseTheme({ ".cm-tooltip": { zIndex: 500, boxSizing: "border-box" }, "&light .cm-tooltip": { border: "1px solid #bbb", backgroundColor: "#f5f5f5" }, "&light .cm-tooltip-section:not(:first-child)": { borderTop: "1px solid #bbb" }, "&dark .cm-tooltip": { backgroundColor: "#333338", color: "white" }, ".cm-tooltip-arrow": { height: "7px", width: "14px", position: "absolute", zIndex: -1, overflow: "hidden", "&:before, &:after": { content: "''", position: "absolute", width: 0, height: 0, borderLeft: "7px solid transparent", borderRight: "7px solid transparent" }, ".cm-tooltip-above &": { bottom: "-7px", "&:before": { borderTop: "7px solid #bbb" }, "&:after": { borderTop: "7px solid #f5f5f5", bottom: "1px" } }, ".cm-tooltip-below &": { top: "-7px", "&:before": { borderBottom: "7px solid #bbb" }, "&:after": { borderBottom: "7px solid #f5f5f5", top: "1px" } } }, "&dark .cm-tooltip .cm-tooltip-arrow": { "&:before": { borderTopColor: "#333338", borderBottomColor: "#333338" }, "&:after": { borderTopColor: "transparent", borderBottomColor: "transparent" } } }), noOffset = { x: 0, y: 0 }, showTooltip = Facet.define({ enables: [tooltipPlugin, baseTheme2] }), showHoverTooltip = Facet.define({ combine: inputs => inputs.reduce((a, i2) => a.concat(i2), []) }), HoverTooltipHost = class _HoverTooltipHost { constructor(view) { this.view = view; this.dom = document.createElement("div"), this.dom.classList.add("cm-tooltip-hover"), this.manager = new TooltipViewManager(view, showHoverTooltip, (t2, p) => this.createHostedView(t2, p), t2 => t2.dom.remove()) } view; manager; dom; mounted = !1; static create(view) { return new _HoverTooltipHost(view) } createHostedView(tooltip, prev) { let hostedView = tooltip.create(this.view); return hostedView.dom.classList.add("cm-tooltip-section"), this.dom.insertBefore(hostedView.dom, prev ? prev.dom.nextSibling : this.dom.firstChild), this.mounted && hostedView.mount && hostedView.mount(this.view), hostedView } mount(view) { for (let hostedView of this.manager.tooltipViews) hostedView.mount && hostedView.mount(view); this.mounted = !0 } positioned(space) { for (let hostedView of this.manager.tooltipViews) hostedView.positioned && hostedView.positioned(space) } update(update) { this.manager.update(update) } destroy() { for (let t2 of this.manager.tooltipViews) t2.destroy?.() } passProp(name2) { let value; for (let view of this.manager.tooltipViews) { let given = view[name2]; if (given !== void 0) { if (value === void 0) value = given; else if (value !== given) return } } return value } get offset() { return this.passProp("offset") } get getCoords() { return this.passProp("getCoords") } get overlap() { return this.passProp("overlap") } get resize() { return this.passProp("resize") } }, showHoverTooltipHost = showTooltip.compute([showHoverTooltip], state => { let tooltips2 = state.facet(showHoverTooltip); return tooltips2.length === 0 ? null : { pos: Math.min(...tooltips2.map(t2 => t2.pos)), end: Math.max(...tooltips2.map(t2 => t2.end ?? t2.pos)), create: HoverTooltipHost.create, above: tooltips2[0].above, arrow: tooltips2.some(t2 => t2.arrow) } }); var HoverPlugin = class { constructor(view, source, field, setHover, hoverTime) { this.view = view; this.source = source; this.field = field; this.setHover = setHover; this.hoverTime = hoverTime; this.lastMove = { x: 0, y: 0, target: view.dom, time: 0 }, this.checkHover = this.checkHover.bind(this), view.dom.addEventListener("mouseleave", this.mouseleave = this.mouseleave.bind(this)), view.dom.addEventListener("mousemove", this.mousemove = this.mousemove.bind(this)) } view; source; field; setHover; hoverTime; lastMove; hoverTimeout = -1; restartTimeout = -1; pending = null; update() { this.pending && (this.pending = null, clearTimeout(this.restartTimeout), this.restartTimeout = setTimeout(() => this.startHover(), 20)) } get active() { return this.view.state.field(this.field) } checkHover() { if (this.hoverTimeout = -1, this.active.length) return; let hovered = Date.now() - this.lastMove.time; hovered < this.hoverTime ? this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime - hovered) : this.startHover() } startHover() { clearTimeout(this.restartTimeout); let { view, lastMove } = this, tile = view.docView.tile.nearest(lastMove.target); if (!tile) return; let pos, side = 1; if (tile.isWidget()) pos = tile.posAtStart; else { if (pos = view.posAtCoords(lastMove), pos == null) return; let posCoords = view.coordsAtPos(pos); if (!posCoords || lastMove.y < posCoords.top || lastMove.y > posCoords.bottom || lastMove.x < posCoords.left - view.defaultCharacterWidth || lastMove.x > posCoords.right + view.defaultCharacterWidth) return; let bidi = view.bidiSpans(view.state.doc.lineAt(pos)).find(s => s.from <= pos && s.to >= pos), rtl = bidi && bidi.dir == 1 ? -1 : 1; side = lastMove.x < posCoords.left ? -rtl : rtl } let open = this.source(view, pos, side); if (open?.then) { let pending = this.pending = { pos }; open.then(result => { this.pending == pending && (this.pending = null, result && !(Array.isArray(result) && !result.length) && view.dispatch({ effects: this.setHover.of(Array.isArray(result) ? result : [result]) })) }, e => logException(view.state, e, "hover tooltip")) } else open && !(Array.isArray(open) && !open.length) && view.dispatch({ effects: this.setHover.of(Array.isArray(open) ? open : [open]) }) } get tooltip() { let plugin2 = this.view.plugin(tooltipPlugin), index = plugin2 ? plugin2.manager.tooltips.findIndex(t2 => t2.create == HoverTooltipHost.create) : -1; return index > -1 ? plugin2.manager.tooltipViews[index] : null } mousemove(event) { this.lastMove = { x: event.clientX, y: event.clientY, target: event.target, time: Date.now() }, this.hoverTimeout < 0 && (this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime)); let { active, tooltip } = this; if (active.length && tooltip && !isInTooltip(tooltip.dom, event) || this.pending) { let { pos } = active[0] || this.pending, end = active[0]?.end ?? pos; (pos == end ? this.view.posAtCoords(this.lastMove) != pos : !isOverRange(this.view, pos, end, event.clientX, event.clientY, 6)) && (this.view.dispatch({ effects: this.setHover.of([]) }), this.pending = null) } } mouseleave(event) { clearTimeout(this.hoverTimeout), this.hoverTimeout = -1; let { active } = this; if (active.length) { let { tooltip } = this; tooltip && tooltip.dom.contains(event.relatedTarget) ? this.watchTooltipLeave(tooltip.dom) : this.view.dispatch({ effects: this.setHover.of([]) }) } } watchTooltipLeave(tooltip) { let watch = event => { tooltip.removeEventListener("mouseleave", watch), this.active.length && !this.view.dom.contains(event.relatedTarget) && this.view.dispatch({ effects: this.setHover.of([]) }) }; tooltip.addEventListener("mouseleave", watch) } destroy() { clearTimeout(this.hoverTimeout), clearTimeout(this.restartTimeout), this.view.dom.removeEventListener("mouseleave", this.mouseleave), this.view.dom.removeEventListener("mousemove", this.mousemove) } }, tooltipMargin = 4; function isInTooltip(tooltip, event) { let { left, right, top: top2, bottom } = tooltip.getBoundingClientRect(), arrow; if (arrow = tooltip.querySelector(".cm-tooltip-arrow")) { let arrowRect = arrow.getBoundingClientRect(); top2 = Math.min(arrowRect.top, top2), bottom = Math.max(arrowRect.bottom, bottom) } return event.clientX >= left - tooltipMargin && event.clientX <= right + tooltipMargin && event.clientY >= top2 - tooltipMargin && event.clientY <= bottom + tooltipMargin } function isOverRange(view, from, to, x, y, margin) { let rect = view.scrollDOM.getBoundingClientRect(), docBottom = view.documentTop + view.documentPadding.top + view.contentHeight; if (rect.left > x || rect.right < x || rect.top > y || Math.min(rect.bottom, docBottom) < y) return !1; let pos = view.posAtCoords({ x, y }, !1); return pos >= from && pos <= to } function hoverTooltip(source, options = {}) { let setHover = StateEffect.define(), hoverState = StateField.define({ create() { return [] }, update(value, tr) { if (value.length && (options.hideOnChange && (tr.docChanged || tr.selection) ? value = [] : options.hideOn && (value = value.filter(v => !options.hideOn(tr, v))), tr.docChanged)) { let mapped = []; for (let tooltip of value) { let newPos = tr.changes.mapPos(tooltip.pos, -1, 1); if (newPos != null) { let copy = Object.assign(Object.create(null), tooltip); copy.pos = newPos, copy.end != null && (copy.end = tr.changes.mapPos(copy.end)), mapped.push(copy) } } value = mapped } for (let effect of tr.effects) effect.is(setHover) && (value = effect.value), effect.is(closeHoverTooltipEffect) && (value = []); return value }, provide: f => showHoverTooltip.from(f) }); return { active: hoverState, extension: [hoverState, ViewPlugin.define(view => new HoverPlugin(view, source, hoverState, setHover, options.hoverTime || 300)), showHoverTooltipHost] } } function getTooltip(view, tooltip) { let plugin2 = view.plugin(tooltipPlugin); if (!plugin2) return null; let found = plugin2.manager.tooltips.indexOf(tooltip); return found < 0 ? null : plugin2.manager.tooltipViews[found] } function hasHoverTooltips(state) { return state.facet(showHoverTooltip).some(x => x) } var closeHoverTooltipEffect = StateEffect.define(), closeHoverTooltips = closeHoverTooltipEffect.of(null); function repositionTooltips(view) { let plugin2 = view.plugin(tooltipPlugin); plugin2 && plugin2.maybeMeasure() } var panelConfig = Facet.define({ combine(configs) { let topContainer, bottomContainer; for (let c of configs) topContainer = topContainer || c.topContainer, bottomContainer = bottomContainer || c.bottomContainer; return { topContainer, bottomContainer } } }); function panels(config) { return config ? [panelConfig.of(config)] : [] } function getPanel(view, panel) { let plugin2 = view.plugin(panelPlugin), index = plugin2 ? plugin2.specs.indexOf(panel) : -1; return index > -1 ? plugin2.panels[index] : null } var panelPlugin = ViewPlugin.fromClass(class { input; specs; panels; top; bottom; constructor(view) { this.input = view.state.facet(showPanel), this.specs = this.input.filter(s => s), this.panels = this.specs.map(spec => spec(view)); let conf = view.state.facet(panelConfig); this.top = new PanelGroup(view, !0, conf.topContainer), this.bottom = new PanelGroup(view, !1, conf.bottomContainer), this.top.sync(this.panels.filter(p => p.top)), this.bottom.sync(this.panels.filter(p => !p.top)); for (let p of this.panels) p.dom.classList.add("cm-panel"), p.mount && p.mount() } update(update) { let conf = update.state.facet(panelConfig); this.top.container != conf.topContainer && (this.top.sync([]), this.top = new PanelGroup(update.view, !0, conf.topContainer)), this.bottom.container != conf.bottomContainer && (this.bottom.sync([]), this.bottom = new PanelGroup(update.view, !1, conf.bottomContainer)), this.top.syncClasses(), this.bottom.syncClasses(); let input = update.state.facet(showPanel); if (input != this.input) { let specs = input.filter(x => x), panels2 = [], top2 = [], bottom = [], mount = []; for (let spec of specs) { let known = this.specs.indexOf(spec), panel; known < 0 ? (panel = spec(update.view), mount.push(panel)) : (panel = this.panels[known], panel.update && panel.update(update)), panels2.push(panel), (panel.top ? top2 : bottom).push(panel) } this.specs = specs, this.panels = panels2, this.top.sync(top2), this.bottom.sync(bottom); for (let p of mount) p.dom.classList.add("cm-panel"), p.mount && p.mount() } else for (let p of this.panels) p.update && p.update(update) } destroy() { this.top.sync([]), this.bottom.sync([]) } }, { provide: plugin2 => EditorView.scrollMargins.of(view => { let value = view.plugin(plugin2); return value && { top: value.top.scrollMargin(), bottom: value.bottom.scrollMargin() } }) }), PanelGroup = class { constructor(view, top2, container) { this.view = view; this.top = top2; this.container = container; this.syncClasses() } view; top; container; dom = void 0; classes = ""; panels = []; sync(panels2) { for (let p of this.panels) p.destroy && panels2.indexOf(p) < 0 && p.destroy(); this.panels = panels2, this.syncDOM() } syncDOM() { if (this.panels.length == 0) { this.dom && (this.dom.remove(), this.dom = void 0); return } if (!this.dom) { this.dom = document.createElement("div"), this.dom.className = this.top ? "cm-panels cm-panels-top" : "cm-panels cm-panels-bottom", this.dom.style[this.top ? "top" : "bottom"] = "0"; let parent = this.container || this.view.dom; parent.insertBefore(this.dom, this.top ? parent.firstChild : null) } let curDOM = this.dom.firstChild; for (let panel of this.panels) if (panel.dom.parentNode == this.dom) { for (; curDOM != panel.dom;)curDOM = rm2(curDOM); curDOM = curDOM.nextSibling } else this.dom.insertBefore(panel.dom, curDOM); for (; curDOM;)curDOM = rm2(curDOM) } scrollMargin() { return !this.dom || this.container ? 0 : Math.max(0, this.top ? this.dom.getBoundingClientRect().bottom - Math.max(0, this.view.scrollDOM.getBoundingClientRect().top) : Math.min(innerHeight, this.view.scrollDOM.getBoundingClientRect().bottom) - this.dom.getBoundingClientRect().top) } syncClasses() { if (!(!this.container || this.classes == this.view.themeClasses)) { for (let cls of this.classes.split(" ")) cls && this.container.classList.remove(cls); for (let cls of (this.classes = this.view.themeClasses).split(" ")) cls && this.container.classList.add(cls) } } }; function rm2(node) { let next = node.nextSibling; return node.remove(), next } var showPanel = Facet.define({ enables: panelPlugin }); function crelt() { var elt = arguments[0]; typeof elt == "string" && (elt = document.createElement(elt)); var i2 = 1, next = arguments[1]; if (next && typeof next == "object" && next.nodeType == null && !Array.isArray(next)) { for (var name2 in next) if (Object.prototype.hasOwnProperty.call(next, name2)) { var value = next[name2]; typeof value == "string" ? elt.setAttribute(name2, value) : value != null && (elt[name2] = value) } i2++ } for (; i2 < arguments.length; i2++)add(elt, arguments[i2]); return elt } function add(elt, child) { if (typeof child == "string") elt.appendChild(document.createTextNode(child)); else if (child != null) if (child.nodeType != null) elt.appendChild(child); else if (Array.isArray(child)) for (var i2 = 0; i2 < child.length; i2++)add(elt, child[i2]); else throw new RangeError("Unsupported child node: " + child) } function showDialog(view, config) { let resolve, promise = new Promise(r => resolve = r), panelCtor = view2 => createDialog(view2, config, resolve); view.state.field(dialogField, !1) ? view.dispatch({ effects: openDialogEffect.of(panelCtor) }) : view.dispatch({ effects: StateEffect.appendConfig.of(dialogField.init(() => [panelCtor])) }); let close = closeDialogEffect.of(panelCtor); return { close, result: promise.then(form => ((view.win.queueMicrotask || (f => view.win.setTimeout(f, 10)))(() => { view.state.field(dialogField).indexOf(panelCtor) > -1 && view.dispatch({ effects: close }) }), form)) } } function getDialog(view, className) { let dialogs = view.state.field(dialogField, !1) || []; for (let open of dialogs) { let panel = getPanel(view, open); if (panel && panel.dom.classList.contains(className)) return panel } return null } var dialogField = StateField.define({ create() { return [] }, update(dialogs, tr) { for (let e of tr.effects) e.is(openDialogEffect) ? dialogs = [e.value].concat(dialogs) : e.is(closeDialogEffect) && (dialogs = dialogs.filter(d => d != e.value)); return dialogs }, provide: f => showPanel.computeN([f], state => state.field(f)) }), openDialogEffect = StateEffect.define(), closeDialogEffect = StateEffect.define(); function createDialog(view, config, result) { let content2 = config.content ? config.content(view, () => done(null)) : null; if (!content2) { if (content2 = crelt("form"), config.input) { let input = crelt("input", config.input); /^(text|password|number|email|tel|url)$/.test(input.type) && input.classList.add("cm-textfield"), input.name || (input.name = "input"), content2.appendChild(crelt("label", (config.label || "") + ": ", input)) } else content2.appendChild(document.createTextNode(config.label || "")); content2.appendChild(document.createTextNode(" ")), content2.appendChild(crelt("button", { class: "cm-button", type: "submit" }, config.submitLabel || "OK")) } let forms = content2.nodeName == "FORM" ? [content2] : content2.querySelectorAll("form"); for (let i2 = 0; i2 < forms.length; i2++) { let form = forms[i2]; form.addEventListener("keydown", event => { event.keyCode == 27 ? (event.preventDefault(), done(null)) : event.keyCode == 13 && (event.preventDefault(), done(form)) }), form.addEventListener("submit", event => { event.preventDefault(), done(form) }) } let panel = crelt("div", content2, crelt("button", { onclick: () => done(null), "aria-label": view.state.phrase("close"), class: "cm-dialog-close", type: "button" }, ["\xD7"])); config.class && (panel.className = config.class), panel.classList.add("cm-dialog"); function done(form) { panel.contains(panel.ownerDocument.activeElement) && view.focus(), result(form) } return { dom: panel, top: config.top, mount: () => { if (config.focus) { let focus; typeof config.focus == "string" ? focus = content2.querySelector(config.focus) : focus = content2.querySelector("input") || content2.querySelector("button"), focus && "select" in focus ? focus.select() : focus && "focus" in focus && focus.focus() } } } } var GutterMarker = class extends RangeValue { compare(other) { return this == other || this.constructor == other.constructor && this.eq(other) } eq(other) { return !1 } destroy(dom) { } }; GutterMarker.prototype.elementClass = ""; GutterMarker.prototype.toDOM = void 0; GutterMarker.prototype.mapMode = 2; GutterMarker.prototype.startSide = GutterMarker.prototype.endSide = -1; GutterMarker.prototype.point = !0; var gutterLineClass = Facet.define(), gutterWidgetClass = Facet.define(), defaults = { class: "", renderEmptyElements: !1, elementStyle: "", markers: () => RangeSet.empty, lineMarker: () => null, widgetMarker: () => null, lineMarkerChange: null, initialSpacer: null, updateSpacer: null, domEventHandlers: {}, side: "before" }, activeGutters = Facet.define(); function gutter(config) { return [gutters(), activeGutters.of({ ...defaults, ...config })] } var unfixGutters = Facet.define({ combine: values => values.some(x => x) }); function gutters(config) { let result = [gutterView]; return config && config.fixed === !1 && result.push(unfixGutters.of(!0)), result } var gutterView = ViewPlugin.fromClass(class { constructor(view) { this.view = view; this.prevViewport = view.viewport, this.dom = document.createElement("div"), this.dom.className = "cm-gutters cm-gutters-before", this.dom.setAttribute("aria-hidden", "true"), this.dom.style.minHeight = this.view.contentHeight / this.view.scaleY + "px", this.gutters = view.state.facet(activeGutters).map(conf => new SingleGutterView(view, conf)), this.fixed = !view.state.facet(unfixGutters); for (let gutter2 of this.gutters) gutter2.config.side == "after" ? this.getDOMAfter().appendChild(gutter2.dom) : this.dom.appendChild(gutter2.dom); this.fixed && (this.dom.style.position = "sticky"), this.syncGutters(!1), view.scrollDOM.insertBefore(this.dom, view.contentDOM) } view; gutters; dom; domAfter = null; fixed; prevViewport; getDOMAfter() { return this.domAfter || (this.domAfter = document.createElement("div"), this.domAfter.className = "cm-gutters cm-gutters-after", this.domAfter.setAttribute("aria-hidden", "true"), this.domAfter.style.minHeight = this.view.contentHeight / this.view.scaleY + "px", this.domAfter.style.position = this.fixed ? "sticky" : "", this.view.scrollDOM.appendChild(this.domAfter)), this.domAfter } update(update) { if (this.updateGutters(update)) { let vpA = this.prevViewport, vpB = update.view.viewport, vpOverlap = Math.min(vpA.to, vpB.to) - Math.max(vpA.from, vpB.from); this.syncGutters(vpOverlap < (vpB.to - vpB.from) * .8) } if (update.geometryChanged) { let min = this.view.contentHeight / this.view.scaleY + "px"; this.dom.style.minHeight = min, this.domAfter && (this.domAfter.style.minHeight = min) } this.view.state.facet(unfixGutters) != !this.fixed && (this.fixed = !this.fixed, this.dom.style.position = this.fixed ? "sticky" : "", this.domAfter && (this.domAfter.style.position = this.fixed ? "sticky" : "")), this.prevViewport = update.view.viewport } syncGutters(detach) { let after = this.dom.nextSibling; detach && (this.dom.remove(), this.domAfter && this.domAfter.remove()); let lineClasses = RangeSet.iter(this.view.state.facet(gutterLineClass), this.view.viewport.from), classSet = [], contexts = this.gutters.map(gutter2 => new UpdateContext(gutter2, this.view.viewport, -this.view.documentPadding.top)); for (let line of this.view.viewportLineBlocks) if (classSet.length && (classSet = []), Array.isArray(line.type)) { let first = !0; for (let b of line.type) if (b.type == 0 && first) { advanceCursor(lineClasses, classSet, b.from); for (let cx of contexts) cx.line(this.view, b, classSet); first = !1 } else if (b.widget) for (let cx of contexts) cx.widget(this.view, b) } else if (line.type == 0) { advanceCursor(lineClasses, classSet, line.from); for (let cx of contexts) cx.line(this.view, line, classSet) } else if (line.widget) for (let cx of contexts) cx.widget(this.view, line); for (let cx of contexts) cx.finish(); detach && (this.view.scrollDOM.insertBefore(this.dom, after), this.domAfter && this.view.scrollDOM.appendChild(this.domAfter)) } updateGutters(update) { let prev = update.startState.facet(activeGutters), cur = update.state.facet(activeGutters), change = update.docChanged || update.heightChanged || update.viewportChanged || !RangeSet.eq(update.startState.facet(gutterLineClass), update.state.facet(gutterLineClass), update.view.viewport.from, update.view.viewport.to); if (prev == cur) for (let gutter2 of this.gutters) gutter2.update(update) && (change = !0); else { change = !0; let gutters2 = []; for (let conf of cur) { let known = prev.indexOf(conf); known < 0 ? gutters2.push(new SingleGutterView(this.view, conf)) : (this.gutters[known].update(update), gutters2.push(this.gutters[known])) } for (let g of this.gutters) g.dom.remove(), gutters2.indexOf(g) < 0 && g.destroy(); for (let g of gutters2) g.config.side == "after" ? this.getDOMAfter().appendChild(g.dom) : this.dom.appendChild(g.dom); this.gutters = gutters2 } return change } destroy() { for (let view of this.gutters) view.destroy(); this.dom.remove(), this.domAfter && this.domAfter.remove() } }, { provide: plugin2 => EditorView.scrollMargins.of(view => { let value = view.plugin(plugin2); if (!value || value.gutters.length == 0 || !value.fixed) return null; let before = value.dom.offsetWidth * view.scaleX, after = value.domAfter ? value.domAfter.offsetWidth * view.scaleX : 0; return view.textDirection == 0 ? { left: before, right: after } : { right: before, left: after } }) }); function asArray2(val) { return Array.isArray(val) ? val : [val] } function advanceCursor(cursor, collect, pos) { for (; cursor.value && cursor.from <= pos;)cursor.from == pos && collect.push(cursor.value), cursor.next() } var UpdateContext = class { constructor(gutter2, viewport, height) { this.gutter = gutter2; this.height = height; this.cursor = RangeSet.iter(gutter2.markers, viewport.from) } gutter; height; cursor; i = 0; addElement(view, block, markers) { let { gutter: gutter2 } = this, above = (block.top - this.height) / view.scaleY, height = block.height / view.scaleY; if (this.i == gutter2.elements.length) { let newElt = new GutterElement(view, height, above, markers); gutter2.elements.push(newElt), gutter2.dom.appendChild(newElt.dom) } else gutter2.elements[this.i].update(view, height, above, markers); this.height = block.bottom, this.i++ } line(view, line, extraMarkers) { let localMarkers = []; advanceCursor(this.cursor, localMarkers, line.from), extraMarkers.length && (localMarkers = localMarkers.concat(extraMarkers)); let forLine = this.gutter.config.lineMarker(view, line, localMarkers); forLine && localMarkers.unshift(forLine); let gutter2 = this.gutter; localMarkers.length == 0 && !gutter2.config.renderEmptyElements || this.addElement(view, line, localMarkers) } widget(view, block) { let marker = this.gutter.config.widgetMarker(view, block.widget, block), markers = marker ? [marker] : null; for (let cls of view.state.facet(gutterWidgetClass)) { let marker2 = cls(view, block.widget, block); marker2 && (markers || (markers = [])).push(marker2) } markers && this.addElement(view, block, markers) } finish() { let gutter2 = this.gutter; for (; gutter2.elements.length > this.i;) { let last = gutter2.elements.pop(); gutter2.dom.removeChild(last.dom), last.destroy() } } }, SingleGutterView = class { constructor(view, config) { this.view = view; this.config = config; this.dom = document.createElement("div"), this.dom.className = "cm-gutter" + (this.config.class ? " " + this.config.class : ""); for (let prop in config.domEventHandlers) this.dom.addEventListener(prop, event => { let target = event.target, y; if (target != this.dom && this.dom.contains(target)) { for (; target.parentNode != this.dom;)target = target.parentNode; let rect = target.getBoundingClientRect(); y = (rect.top + rect.bottom) / 2 } else y = event.clientY; let line = view.lineBlockAtHeight(y - view.documentTop); config.domEventHandlers[prop](view, line, event) && event.preventDefault() }); this.markers = asArray2(config.markers(view)), config.initialSpacer && (this.spacer = new GutterElement(view, 0, 0, [config.initialSpacer(view)]), this.dom.appendChild(this.spacer.dom), this.spacer.dom.style.cssText += "visibility: hidden; pointer-events: none") } view; config; dom; elements = []; markers; spacer = null; update(update) { let prevMarkers = this.markers; if (this.markers = asArray2(this.config.markers(update.view)), this.spacer && this.config.updateSpacer) { let updated = this.config.updateSpacer(this.spacer.markers[0], update); updated != this.spacer.markers[0] && this.spacer.update(update.view, 0, 0, [updated]) } let vp = update.view.viewport; return !RangeSet.eq(this.markers, prevMarkers, vp.from, vp.to) || (this.config.lineMarkerChange ? this.config.lineMarkerChange(update) : !1) } destroy() { for (let elt of this.elements) elt.destroy() } }, GutterElement = class { dom; height = -1; above = 0; markers = []; constructor(view, height, above, markers) { this.dom = document.createElement("div"), this.dom.className = "cm-gutterElement", this.update(view, height, above, markers) } update(view, height, above, markers) { this.height != height && (this.height = height, this.dom.style.height = height + "px"), this.above != above && (this.dom.style.marginTop = (this.above = above) ? above + "px" : ""), sameMarkers(this.markers, markers) || this.setMarkers(view, markers) } setMarkers(view, markers) { let cls = "cm-gutterElement", domPos = this.dom.firstChild; for (let iNew = 0, iOld = 0; ;) { let skipTo = iOld, marker = iNew < markers.length ? markers[iNew++] : null, matched = !1; if (marker) { let c = marker.elementClass; c && (cls += " " + c); for (let i2 = iOld; i2 < this.markers.length; i2++)if (this.markers[i2].compare(marker)) { skipTo = i2, matched = !0; break } } else skipTo = this.markers.length; for (; iOld < skipTo;) { let next = this.markers[iOld++]; if (next.toDOM) { next.destroy(domPos); let after = domPos.nextSibling; domPos.remove(), domPos = after } } if (!marker) break; marker.toDOM && (matched ? domPos = domPos.nextSibling : this.dom.insertBefore(marker.toDOM(view), domPos)), matched && iOld++ } this.dom.className = cls, this.markers = markers } destroy() { this.setMarkers(null, []) } }; function sameMarkers(a, b) { if (a.length != b.length) return !1; for (let i2 = 0; i2 < a.length; i2++)if (!a[i2].compare(b[i2])) return !1; return !0 } var lineNumberMarkers = Facet.define(), lineNumberWidgetMarker = Facet.define(), lineNumberConfig = Facet.define({ combine(values) { return combineConfig(values, { formatNumber: String, domEventHandlers: {} }, { domEventHandlers(a, b) { let result = Object.assign({}, a); for (let event in b) { let exists = result[event], add2 = b[event]; result[event] = exists ? (view, line, event2) => exists(view, line, event2) || add2(view, line, event2) : add2 } return result } }) } }), NumberMarker = class extends GutterMarker { constructor(number2) { super(); this.number = number2 } number; eq(other) { return this.number == other.number } toDOM() { return document.createTextNode(this.number) } }; function formatNumber(view, number2) { return view.state.facet(lineNumberConfig).formatNumber(number2, view.state) } var lineNumberGutter = activeGutters.compute([lineNumberConfig], state => ({ class: "cm-lineNumbers", renderEmptyElements: !1, markers(view) { return view.state.facet(lineNumberMarkers) }, lineMarker(view, line, others) { return others.some(m => m.toDOM) ? null : new NumberMarker(formatNumber(view, view.state.doc.lineAt(line.from).number)) }, widgetMarker: (view, widget, block) => { for (let m of view.state.facet(lineNumberWidgetMarker)) { let result = m(view, widget, block); if (result) return result } return null }, lineMarkerChange: update => update.startState.facet(lineNumberConfig) != update.state.facet(lineNumberConfig), initialSpacer(view) { return new NumberMarker(formatNumber(view, maxLineNumber(view.state.doc.lines))) }, updateSpacer(spacer, update) { let max = formatNumber(update.view, maxLineNumber(update.view.state.doc.lines)); return max == spacer.number ? spacer : new NumberMarker(max) }, domEventHandlers: state.facet(lineNumberConfig).domEventHandlers, side: "before" })); function lineNumbers(config = {}) { return [lineNumberConfig.of(config), gutters(), lineNumberGutter] } function maxLineNumber(lines) { let last = 9; for (; last < lines;)last = last * 10 + 9; return last } var activeLineGutterMarker = new class extends GutterMarker { elementClass = "cm-activeLineGutter" }, activeLineGutterHighlighter = gutterLineClass.compute(["selection"], state => { let marks = [], last = -1; for (let range of state.selection.ranges) { let linePos = state.doc.lineAt(range.head).from; linePos > last && (last = linePos, marks.push(activeLineGutterMarker.range(linePos))) } return RangeSet.of(marks) }); function highlightActiveLineGutter() { return activeLineGutterHighlighter } function matcher(decorator) { return ViewPlugin.define(view => ({ decorations: decorator.createDeco(view), update(u) { this.decorations = decorator.updateDeco(u, this.decorations) } }), { decorations: v => v.decorations }) } var tabDeco = Decoration.mark({ class: "cm-highlightTab" }), spaceDeco = Decoration.mark({ class: "cm-highlightSpace" }), whitespaceHighlighter = matcher(new MatchDecorator({ regexp: /\t| /g, decoration: match => match[0] == " " ? tabDeco : spaceDeco, boundary: /\S/ })); function highlightWhitespace() { return whitespaceHighlighter } var trailingHighlighter = matcher(new MatchDecorator({ regexp: /\s+$/g, decoration: Decoration.mark({ class: "cm-trailingSpace" }) })); function highlightTrailingWhitespace() { return trailingHighlighter } var __test = { HeightMap, HeightOracle, MeasuredHeights, QueryType, ChangedRange, computeOrder, moveVisually, clearHeightChangeFlag, getHeightChangeFlag: () => heightChangeFlag }; var DefaultBufferLength = 1024, nextPropID = 0, Range4 = class { constructor(from, to) { this.from = from; this.to = to } }, NodeProp = class _NodeProp { constructor(config = {}) { this.id = nextPropID++, this.perNode = !!config.perNode, this.deserialize = config.deserialize || (() => { throw new Error("This node type doesn't define a deserialize function") }), this.combine = config.combine || null } add(match) { if (this.perNode) throw new RangeError("Can't add per-node props to node types"); return typeof match != "function" && (match = NodeType.match(match)), type => { let result = match(type); return result === void 0 ? null : [this, result] } } static { this.closedBy = new _NodeProp({ deserialize: str => str.split(" ") }) } static { this.openedBy = new _NodeProp({ deserialize: str => str.split(" ") }) } static { this.group = new _NodeProp({ deserialize: str => str.split(" ") }) } static { this.isolate = new _NodeProp({ deserialize: value => { if (value && value != "rtl" && value != "ltr" && value != "auto") throw new RangeError("Invalid value for isolate: " + value); return value || "auto" } }) } static { this.contextHash = new _NodeProp({ perNode: !0 }) } static { this.lookAhead = new _NodeProp({ perNode: !0 }) } static { this.mounted = new _NodeProp({ perNode: !0 }) } }, MountedTree = class { constructor(tree, overlay, parser, bracketed = !1) { this.tree = tree; this.overlay = overlay; this.parser = parser; this.bracketed = bracketed } static get(tree) { return tree && tree.props && tree.props[NodeProp.mounted.id] } }; var noProps = Object.create(null), NodeType = class _NodeType { constructor(name2, props, id, flags = 0) { this.name = name2; this.props = props; this.id = id; this.flags = flags } static define(spec) { let props = spec.props && spec.props.length ? Object.create(null) : noProps, flags = (spec.top ? 1 : 0) | (spec.skipped ? 2 : 0) | (spec.error ? 4 : 0) | (spec.name == null ? 8 : 0), type = new _NodeType(spec.name || "", props, spec.id, flags); if (spec.props) { for (let src of spec.props) if (Array.isArray(src) || (src = src(type)), src) { if (src[0].perNode) throw new RangeError("Can't store a per-node prop on a node type"); props[src[0].id] = src[1] } } return type } prop(prop) { return this.props[prop.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(name2) { if (typeof name2 == "string") { if (this.name == name2) return !0; let group = this.prop(NodeProp.group); return group ? group.indexOf(name2) > -1 : !1 } return this.id == name2 } static { this.none = new _NodeType("", Object.create(null), 0, 8) } static match(map) { let direct = Object.create(null); for (let prop in map) for (let name2 of prop.split(" ")) direct[name2] = map[prop]; return node => { for (let groups = node.prop(NodeProp.group), i2 = -1; i2 < (groups ? groups.length : 0); i2++) { let found = direct[i2 < 0 ? node.name : groups[i2]]; if (found) return found } } } }, NodeSet = class _NodeSet { constructor(types2) { this.types = types2; for (let i2 = 0; i2 < types2.length; i2++)if (types2[i2].id != i2) throw new RangeError("Node type ids should correspond to array positions when creating a node set") } extend(...props) { let newTypes = []; for (let type of this.types) { let newProps = null; for (let source of props) { let add2 = source(type); if (add2) { newProps || (newProps = Object.assign({}, type.props)); let value = add2[1], prop = add2[0]; prop.combine && prop.id in newProps && (value = prop.combine(newProps[prop.id], value)), newProps[prop.id] = value } } newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type) } return new _NodeSet(newTypes) } }, CachedNode = new WeakMap, CachedInnerNode = new WeakMap; var Tree = class _Tree { constructor(type, children, positions, length, props) { this.type = type; this.children = children; this.positions = positions; this.length = length; this.props = null; if (props && props.length) { this.props = Object.create(null); for (let [prop, value] of props) this.props[typeof prop == "number" ? prop : prop.id] = value } } toString() { let mounted = MountedTree.get(this); if (mounted && !mounted.overlay) return mounted.tree.toString(); let children = ""; for (let ch of this.children) { let str = ch.toString(); str && (children && (children += ","), children += str) } return this.type.name ? (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + (children.length ? "(" + children + ")" : "") : children } static { this.empty = new _Tree(NodeType.none, [], [], 0) } cursor(mode = 0) { return new TreeCursor(this.topNode, mode) } cursorAt(pos, side = 0, mode = 0) { let scope = CachedNode.get(this) || this.topNode, cursor = new TreeCursor(scope); return cursor.moveTo(pos, side), CachedNode.set(this, cursor._tree), cursor } get topNode() { return new TreeNode(this, 0, 0, null) } resolve(pos, side = 0) { let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, !1); return CachedNode.set(this, node), node } resolveInner(pos, side = 0) { let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, !0); return CachedInnerNode.set(this, node), node } resolveStack(pos, side = 0) { return stackIterator(this, pos, side) } iterate(spec) { let { enter, leave, from = 0, to = this.length } = spec, mode = spec.mode || 0, anon = (mode & 2) > 0; for (let c = this.cursor(mode | 2); ;) { let entered = !1; if (c.from <= to && c.to >= from && (!anon && c.type.isAnonymous || enter(c) !== !1)) { if (c.firstChild()) continue; entered = !0 } for (; entered && leave && (anon || !c.type.isAnonymous) && leave(c), !c.nextSibling();) { if (!c.parent()) return; entered = !0 } } } prop(prop) { return prop.perNode ? this.props ? this.props[prop.id] : void 0 : this.type.prop(prop) } get propValues() { let result = []; if (this.props) for (let id in this.props) result.push([+id, this.props[id]]); return result } balance(config = {}) { return this.children.length <= 8 ? this : balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new _Tree(this.type, children, positions, length, this.propValues), config.makeTree || ((children, positions, length) => new _Tree(NodeType.none, children, positions, length))) } static build(data) { return buildTree(data) } }, FlatBufferCursor = class _FlatBufferCursor { constructor(buffer, index) { this.buffer = buffer; this.index = index } 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 _FlatBufferCursor(this.buffer, this.index) } }, TreeBuffer = class _TreeBuffer { constructor(buffer, length, set) { this.buffer = buffer; this.length = length; this.set = set } get type() { return NodeType.none } toString() { let result = []; for (let index = 0; index < this.buffer.length;)result.push(this.childString(index)), index = this.buffer[index + 3]; return result.join(",") } childString(index) { let id = this.buffer[index], endIndex = this.buffer[index + 3], type = this.set.types[id], result = type.name; if (/\W/.test(result) && !type.isError && (result = JSON.stringify(result)), index += 4, endIndex == index) return result; let children = []; for (; index < endIndex;)children.push(this.childString(index)), index = this.buffer[index + 3]; return result + "(" + children.join(",") + ")" } findChild(startIndex, endIndex, dir, pos, side) { let { buffer } = this, pick = -1; for (let i2 = startIndex; i2 != endIndex && !(checkSide(side, pos, buffer[i2 + 1], buffer[i2 + 2]) && (pick = i2, dir > 0)); i2 = buffer[i2 + 3]); return pick } slice(startI, endI, from) { let b = this.buffer, copy = new Uint16Array(endI - startI), len = 0; for (let i2 = startI, j = 0; i2 < endI;) { copy[j++] = b[i2++], copy[j++] = b[i2++] - from; let to = copy[j++] = b[i2++] - from; copy[j++] = b[i2++] - startI, len = Math.max(len, to) } return new _TreeBuffer(copy, len, this.set) } }; function checkSide(side, pos, from, to) { switch (side) { case -2: return from < pos; case -1: return to >= pos && from < pos; case 0: return from < pos && to > pos; case 1: return from <= pos && to > pos; case 2: return to > pos; case 4: return !0 } } function resolveNode(node, pos, side, overlays) { for (; node.from == node.to || (side < 1 ? node.from >= pos : node.from > pos) || (side > -1 ? node.to <= pos : node.to < pos);) { let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent; if (!parent) return node; node = parent } let mode = overlays ? 0 : 8; if (overlays) for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent)scan instanceof TreeNode && scan.index < 0 && parent.enter(pos, side, mode)?.from != scan.from && (node = parent); for (; ;) { let inner = node.enter(pos, side, mode); if (!inner) return node; node = inner } } var BaseNode = class { cursor(mode = 0) { return new TreeCursor(this, mode) } getChild(type, before = null, after = null) { let r = getChildren(this, type, before, after); return r.length ? r[0] : null } getChildren(type, before = null, after = null) { return getChildren(this, type, before, after) } resolve(pos, side = 0) { return resolveNode(this, pos, side, !1) } resolveInner(pos, side = 0) { return resolveNode(this, pos, side, !0) } matchContext(context) { return matchNodeContext(this.parent, context) } enterUnfinishedNodesBefore(pos) { let scan = this.childBefore(pos), node = this; for (; scan;) { let last = scan.lastChild; if (!last || last.to != scan.to) break; last.type.isError && last.from == last.to ? (node = scan, scan = last.prevSibling) : scan = last } return node } get node() { return this } get next() { return this.parent } }, TreeNode = class _TreeNode extends BaseNode { constructor(_tree, from, index, _parent) { super(); this._tree = _tree; this.from = from; this.index = index; this._parent = _parent } get type() { return this._tree.type } get name() { return this._tree.type.name } get to() { return this.from + this._tree.length } nextChild(i2, dir, pos, side, mode = 0) { for (let parent = this; ;) { for (let { children, positions } = parent._tree, e = dir > 0 ? children.length : -1; i2 != e; i2 += dir) { let next = children[i2], start = positions[i2] + parent.from, mounted; if (!(!(mode & 16 && next instanceof Tree && (mounted = MountedTree.get(next)) && !mounted.overlay && mounted.bracketed && pos >= start && pos <= start + next.length) && !checkSide(side, pos, start, start + next.length))) { if (next instanceof TreeBuffer) { if (mode & 1) continue; let index = next.findChild(0, next.buffer.length, dir, pos - start, side); if (index > -1) return new BufferNode(new BufferContext(parent, next, i2, start), null, index) } else if (mode & 2 || !next.type.isAnonymous || hasChild(next)) { let mounted2; if (!(mode & 4) && (mounted2 = MountedTree.get(next)) && !mounted2.overlay) return new _TreeNode(mounted2.tree, start, i2, parent); let inner = new _TreeNode(next, start, i2, parent); return mode & 2 || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side, mode) } } } if (mode & 2 || !parent.type.isAnonymous || (parent.index >= 0 ? i2 = parent.index + dir : i2 = dir < 0 ? -1 : parent._parent._tree.children.length, parent = parent._parent, !parent)) 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(pos) { return this.nextChild(0, 1, pos, 2) } childBefore(pos) { return this.nextChild(this._tree.children.length - 1, -1, pos, -2) } prop(prop) { return this._tree.prop(prop) } enter(pos, side, mode = 0) { let mounted; if (!(mode & 8) && (mounted = MountedTree.get(this._tree)) && mounted.overlay) { let rPos = pos - this.from, enterBracketed = mode & 16 && mounted.bracketed; for (let { from, to } of mounted.overlay) if ((side > 0 || enterBracketed ? from <= rPos : from < rPos) && (side < 0 || enterBracketed ? to >= rPos : to > rPos)) return new _TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this) } return this.nextChild(0, 1, pos, side, mode) } nextSignificantParent() { let val = this; for (; val.type.isAnonymous && val._parent;)val = val._parent; return val } 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 getChildren(node, type, before, after) { let cur = node.cursor(), result = []; if (!cur.firstChild()) return result; if (before != null) { for (let found = !1; !found;)if (found = cur.type.is(before), !cur.nextSibling()) return result } for (; ;) { if (after != null && cur.type.is(after)) return result; if (cur.type.is(type) && result.push(cur.node), !cur.nextSibling()) return after == null ? result : [] } } function matchNodeContext(node, context, i2 = context.length - 1) { for (let p = node; i2 >= 0; p = p.parent) { if (!p) return !1; if (!p.type.isAnonymous) { if (context[i2] && context[i2] != p.name) return !1; i2-- } } return !0 } var BufferContext = class { constructor(parent, buffer, index, start) { this.parent = parent; this.buffer = buffer; this.index = index; this.start = start } }, BufferNode = class _BufferNode extends BaseNode { constructor(context, _parent, index) { super(); this.context = context; this._parent = _parent; this.index = index; this.type = context.buffer.set.types[context.buffer.buffer[index]] } 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(dir, pos, side) { let { buffer } = this.context, index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side); return index < 0 ? null : new _BufferNode(this.context, this, index) } get firstChild() { return this.child(1, 0, 4) } get lastChild() { return this.child(-1, 0, 4) } childAfter(pos) { return this.child(1, pos, 2) } childBefore(pos) { return this.child(-1, pos, -2) } prop(prop) { return this.type.prop(prop) } enter(pos, side, mode = 0) { if (mode & 1) return null; let { buffer } = this.context, index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side); return index < 0 ? null : new _BufferNode(this.context, this, index) } get parent() { return this._parent || this.context.parent.nextSignificantParent() } externalSibling(dir) { return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4) } get nextSibling() { let { buffer } = this.context, after = buffer.buffer[this.index + 3]; return after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length) ? new _BufferNode(this.context, this._parent, after) : this.externalSibling(1) } get prevSibling() { let { buffer } = this.context, parentStart = this._parent ? this._parent.index + 4 : 0; return this.index == parentStart ? this.externalSibling(-1) : new _BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4)) } get tree() { return null } toTree() { let children = [], positions = [], { buffer } = this.context, startI = this.index + 4, endI = buffer.buffer[this.index + 3]; if (endI > startI) { let from = buffer.buffer[this.index + 1]; children.push(buffer.slice(startI, endI, from)), positions.push(0) } return new Tree(this.type, children, positions, this.to - this.from) } toString() { return this.context.buffer.childString(this.index) } }; function iterStack(heads) { if (!heads.length) return null; let pick = 0, picked = heads[0]; for (let i2 = 1; i2 < heads.length; i2++) { let node = heads[i2]; (node.from > picked.from || node.to < picked.to) && (picked = node, pick = i2) } let next = picked instanceof TreeNode && picked.index < 0 ? null : picked.parent, newHeads = heads.slice(); return next ? newHeads[pick] = next : newHeads.splice(pick, 1), new StackIterator(newHeads, picked) } var StackIterator = class { constructor(heads, node) { this.heads = heads; this.node = node } get next() { return iterStack(this.heads) } }; function stackIterator(tree, pos, side) { let inner = tree.resolveInner(pos, side), layers = null; for (let scan = inner instanceof TreeNode ? inner : inner.context.parent; scan; scan = scan.parent)if (scan.index < 0) { let parent = scan.parent; (layers || (layers = [inner])).push(parent.resolve(pos, side)), scan = parent } else { let mount = MountedTree.get(scan.tree); if (mount && mount.overlay && mount.overlay[0].from <= pos && mount.overlay[mount.overlay.length - 1].to >= pos) { let root = new TreeNode(mount.tree, mount.overlay[0].from + scan.from, -1, scan); (layers || (layers = [inner])).push(resolveNode(root, pos, side, !1)) } } return layers ? iterStack(layers) : inner } var TreeCursor = class { constructor(node, mode = 0) { this.buffer = null; this.stack = []; this.index = 0; this.bufferNode = null; if (this.mode = mode & -17, node instanceof TreeNode) this.yieldNode(node); else { this._tree = node.context.parent, this.buffer = node.context; for (let n = node._parent; n; n = n._parent)this.stack.unshift(n.index); this.bufferNode = node, this.yieldBuf(node.index) } } get name() { return this.type.name } yieldNode(node) { return node ? (this._tree = node, this.type = node.type, this.from = node.from, this.to = node.to, !0) : !1 } yieldBuf(index, type) { this.index = index; let { start, buffer } = this.buffer; return this.type = type || buffer.set.types[buffer.buffer[index]], this.from = start + buffer.buffer[index + 1], this.to = start + buffer.buffer[index + 2], !0 } yield(node) { return node ? node instanceof TreeNode ? (this.buffer = null, this.yieldNode(node)) : (this.buffer = node.context, this.yieldBuf(node.index, node.type)) : !1 } toString() { return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString() } enterChild(dir, pos, side) { if (!this.buffer) return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode)); let { buffer } = this.buffer, index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side); return index < 0 ? !1 : (this.stack.push(this.index), this.yieldBuf(index)) } firstChild() { return this.enterChild(1, 0, 4) } lastChild() { return this.enterChild(-1, 0, 4) } childAfter(pos) { return this.enterChild(1, pos, 2) } childBefore(pos) { return this.enterChild(-1, pos, -2) } enter(pos, side, mode = this.mode) { return this.buffer ? mode & 1 ? !1 : this.enterChild(1, pos, side) : this.yield(this._tree.enter(pos, side, mode)) } 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 parent = this.mode & 2 ? this.buffer.parent : this.buffer.parent.nextSignificantParent(); return this.buffer = null, this.yieldNode(parent) } sibling(dir) { if (!this.buffer) return this._tree._parent ? this.yield(this._tree.index < 0 ? null : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4, this.mode)) : !1; let { buffer } = this.buffer, d = this.stack.length - 1; if (dir < 0) { let parentStart = d < 0 ? 0 : this.stack[d] + 4; if (this.index != parentStart) return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4)) } else { let after = buffer.buffer[this.index + 3]; if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3])) return this.yieldBuf(after) } return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4, this.mode)) : !1 } nextSibling() { return this.sibling(1) } prevSibling() { return this.sibling(-1) } atLastNode(dir) { let index, parent, { buffer } = this; if (buffer) { if (dir > 0) { if (this.index < buffer.buffer.buffer.length) return !1 } else for (let i2 = 0; i2 < this.index; i2++)if (buffer.buffer.buffer[i2 + 3] < this.index) return !1; ({ index, parent } = buffer) } else ({ index, _parent: parent } = this._tree); for (; parent; { index, _parent: parent } = parent)if (index > -1) for (let i2 = index + dir, e = dir < 0 ? -1 : parent._tree.children.length; i2 != e; i2 += dir) { let child = parent._tree.children[i2]; if (this.mode & 2 || child instanceof TreeBuffer || !child.type.isAnonymous || hasChild(child)) return !1 } return !0 } move(dir, enter) { if (enter && this.enterChild(dir, 0, 4)) return !0; for (; ;) { if (this.sibling(dir)) return !0; if (this.atLastNode(dir) || !this.parent()) return !1 } } next(enter = !0) { return this.move(1, enter) } prev(enter = !0) { return this.move(-1, enter) } moveTo(pos, side = 0) { for (; (this.from == this.to || (side < 1 ? this.from >= pos : this.from > pos) || (side > -1 ? this.to <= pos : this.to < pos)) && this.parent();); for (; this.enterChild(1, pos, side);); return this } get node() { if (!this.buffer) return this._tree; let cache = this.bufferNode, result = null, depth2 = 0; if (cache && cache.context == this.buffer) scan: for (let index = this.index, d = this.stack.length; d >= 0;) { for (let c = cache; c; c = c._parent)if (c.index == index) { if (index == this.index) return c; result = c, depth2 = d + 1; break scan } index = this.stack[--d] } for (let i2 = depth2; i2 < this.stack.length; i2++)result = new BufferNode(this.buffer, result, this.stack[i2]); return this.bufferNode = new BufferNode(this.buffer, result, this.index) } get tree() { return this.buffer ? null : this._tree._tree } iterate(enter, leave) { for (let depth2 = 0; ;) { let mustLeave = !1; if (this.type.isAnonymous || enter(this) !== !1) { if (this.firstChild()) { depth2++; continue } this.type.isAnonymous || (mustLeave = !0) } for (; ;) { if (mustLeave && leave && leave(this), mustLeave = this.type.isAnonymous, !depth2) return; if (this.nextSibling()) break; this.parent(), depth2--, mustLeave = !0 } } } matchContext(context) { if (!this.buffer) return matchNodeContext(this.node.parent, context); let { buffer } = this.buffer, { types: types2 } = buffer.set; for (let i2 = context.length - 1, d = this.stack.length - 1; i2 >= 0; d--) { if (d < 0) return matchNodeContext(this._tree, context, i2); let type = types2[buffer.buffer[this.stack[d]]]; if (!type.isAnonymous) { if (context[i2] && context[i2] != type.name) return !1; i2-- } } return !0 } }; function hasChild(tree) { return tree.children.some(ch => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch)) } function buildTree(data) { let { buffer, nodeSet: nodeSet2, maxBufferLength = DefaultBufferLength, reused = [], minRepeatType = nodeSet2.types.length } = data, cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer, types2 = nodeSet2.types, contextHash = 0, lookAhead = 0; function takeNode(parentStart, minPos, children2, positions2, inRepeat, depth2) { let { id, start, end, size } = cursor, lookAheadAtStart = lookAhead, contextAtStart = contextHash; if (size < 0) if (cursor.next(), size == -1) { let node2 = reused[id]; children2.push(node2), positions2.push(start - parentStart); return } else if (size == -3) { contextHash = id; return } else if (size == -4) { lookAhead = id; return } else throw new RangeError(`Unrecognized record size: ${size}`); let type = types2[id], node, buffer2, startPos = start - parentStart; if (end - start <= maxBufferLength && (buffer2 = findBufferSize(cursor.pos - minPos, inRepeat))) { let data2 = new Uint16Array(buffer2.size - buffer2.skip), endPos = cursor.pos - buffer2.size, index = data2.length; for (; cursor.pos > endPos;)index = copyToBuffer(buffer2.start, data2, index); node = new TreeBuffer(data2, end - buffer2.start, nodeSet2), startPos = buffer2.start - parentStart } else { let endPos = cursor.pos - size; cursor.next(); let localChildren = [], localPositions = [], localInRepeat = id >= minRepeatType ? id : -1, lastGroup = 0, lastEnd = end; for (; cursor.pos > endPos;)localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0 ? (cursor.end <= lastEnd - maxBufferLength && (makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart, contextAtStart), lastGroup = localChildren.length, lastEnd = cursor.end), cursor.next()) : depth2 > 2500 ? takeFlatNode(start, endPos, localChildren, localPositions) : takeNode(start, endPos, localChildren, localPositions, localInRepeat, depth2 + 1); if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length && makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart, contextAtStart), localChildren.reverse(), localPositions.reverse(), localInRepeat > -1 && lastGroup > 0) { let make = makeBalanced(type, contextAtStart); node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make) } else node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end, contextAtStart) } children2.push(node), positions2.push(startPos) } function takeFlatNode(parentStart, minPos, children2, positions2) { let nodes = [], nodeCount = 0, stopAt = -1; for (; cursor.pos > minPos;) { let { id, start, end, size } = cursor; if (size > 4) cursor.next(); else { if (stopAt > -1 && start < stopAt) break; stopAt < 0 && (stopAt = end - maxBufferLength), nodes.push(id, start, end), nodeCount++, cursor.next() } } if (nodeCount) { let buffer2 = new Uint16Array(nodeCount * 4), start = nodes[nodes.length - 2]; for (let i2 = nodes.length - 3, j = 0; i2 >= 0; i2 -= 3)buffer2[j++] = nodes[i2], buffer2[j++] = nodes[i2 + 1] - start, buffer2[j++] = nodes[i2 + 2] - start, buffer2[j++] = j; children2.push(new TreeBuffer(buffer2, nodes[2] - start, nodeSet2)), positions2.push(start - parentStart) } } function makeBalanced(type, contextHash2) { return (children2, positions2, length2) => { let lookAhead2 = 0, lastI = children2.length - 1, last, lookAheadProp; if (lastI >= 0 && (last = children2[lastI]) instanceof Tree) { if (!lastI && last.type == type && last.length == length2) return last; (lookAheadProp = last.prop(NodeProp.lookAhead)) && (lookAhead2 = positions2[lastI] + last.length + lookAheadProp) } return makeTree(type, children2, positions2, length2, lookAhead2, contextHash2) } } function makeRepeatLeaf(children2, positions2, base2, i2, from, to, type, lookAhead2, contextHash2) { let localChildren = [], localPositions = []; for (; children2.length > i2;)localChildren.push(children2.pop()), localPositions.push(positions2.pop() + base2 - from); children2.push(makeTree(nodeSet2.types[type], localChildren, localPositions, to - from, lookAhead2 - to, contextHash2)), positions2.push(from - base2) } function makeTree(type, children2, positions2, length2, lookAhead2, contextHash2, props) { if (contextHash2) { let pair = [NodeProp.contextHash, contextHash2]; props = props ? [pair].concat(props) : [pair] } if (lookAhead2 > 25) { let pair = [NodeProp.lookAhead, lookAhead2]; props = props ? [pair].concat(props) : [pair] } return new Tree(type, children2, positions2, length2, props) } function findBufferSize(maxSize, inRepeat) { let fork = cursor.fork(), size = 0, start = 0, skip = 0, minStart = fork.end - maxBufferLength, result = { size: 0, start: 0, skip: 0 }; scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos;) { let nodeSize2 = fork.size; if (fork.id == inRepeat && nodeSize2 >= 0) { result.size = size, result.start = start, result.skip = skip, skip += 4, size += 4, fork.next(); continue } let startPos = fork.pos - nodeSize2; if (nodeSize2 < 0 || startPos < minPos || fork.start < minStart) break; let localSkipped = fork.id >= minRepeatType ? 4 : 0, nodeStart = fork.start; for (fork.next(); fork.pos > startPos;) { if (fork.size < 0) if (fork.size == -3 || fork.size == -4) localSkipped += 4; else break scan; else fork.id >= minRepeatType && (localSkipped += 4); fork.next() } start = nodeStart, size += nodeSize2, skip += localSkipped } return (inRepeat < 0 || size == maxSize) && (result.size = size, result.start = start, result.skip = skip), result.size > 4 ? result : void 0 } function copyToBuffer(bufferStart, buffer2, index) { let { id, start, end, size } = cursor; if (cursor.next(), size >= 0 && id < minRepeatType) { let startIndex = index; if (size > 4) { let endPos = cursor.pos - (size - 4); for (; cursor.pos > endPos;)index = copyToBuffer(bufferStart, buffer2, index) } buffer2[--index] = startIndex, buffer2[--index] = end - bufferStart, buffer2[--index] = start - bufferStart, buffer2[--index] = id } else size == -3 ? contextHash = id : size == -4 && (lookAhead = id); return index } let children = [], positions = []; for (; cursor.pos > 0;)takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1, 0); let length = data.length ?? (children.length ? positions[0] + children[0].length : 0); return new Tree(types2[data.topID], children.reverse(), positions.reverse(), length) } var nodeSizeCache = new WeakMap; function nodeSize(balanceType, node) { if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType) return 1; let size = nodeSizeCache.get(node); if (size == null) { size = 1; for (let child of node.children) { if (child.type != balanceType || !(child instanceof Tree)) { size = 1; break } size += nodeSize(balanceType, child) } nodeSizeCache.set(node, size) } return size } function balanceRange(balanceType, children, positions, from, to, start, length, mkTop, mkTree) { let total = 0; for (let i2 = from; i2 < to; i2++)total += nodeSize(balanceType, children[i2]); let maxChild = Math.ceil(total * 1.5 / 8), localChildren = [], localPositions = []; function divide(children2, positions2, from2, to2, offset) { for (let i2 = from2; i2 < to2;) { let groupFrom = i2, groupStart = positions2[i2], groupSize = nodeSize(balanceType, children2[i2]); for (i2++; i2 < to2; i2++) { let nextSize = nodeSize(balanceType, children2[i2]); if (groupSize + nextSize >= maxChild) break; groupSize += nextSize } if (i2 == groupFrom + 1) { if (groupSize > maxChild) { let only = children2[groupFrom]; divide(only.children, only.positions, 0, only.children.length, positions2[groupFrom] + offset); continue } localChildren.push(children2[groupFrom]) } else { let length2 = positions2[i2 - 1] + children2[i2 - 1].length - groupStart; localChildren.push(balanceRange(balanceType, children2, positions2, groupFrom, i2, groupStart, length2, null, mkTree)) } localPositions.push(groupStart + offset - start) } } return divide(children, positions, from, to, 0), (mkTop || mkTree)(localChildren, localPositions, length) } var TreeFragment = class _TreeFragment { constructor(from, to, tree, offset, openStart = !1, openEnd = !1) { this.from = from; this.to = to; this.tree = tree; this.offset = offset; this.open = (openStart ? 1 : 0) | (openEnd ? 2 : 0) } get openStart() { return (this.open & 1) > 0 } get openEnd() { return (this.open & 2) > 0 } static addTree(tree, fragments = [], partial = !1) { let result = [new _TreeFragment(0, tree.length, tree, 0, !1, partial)]; for (let f of fragments) f.to > tree.length && result.push(f); return result } static applyChanges(fragments, changes, minGap = 128) { if (!changes.length) return fragments; let result = [], fI = 1, nextF = fragments.length ? fragments[0] : null; for (let cI = 0, pos = 0, off = 0; ; cI++) { let nextC = cI < changes.length ? changes[cI] : null, nextPos = nextC ? nextC.fromA : 1e9; if (nextPos - pos >= minGap) for (; nextF && nextF.from < nextPos;) { let cut = nextF; if (pos >= cut.from || nextPos <= cut.to || off) { let fFrom = Math.max(cut.from, pos) - off, fTo = Math.min(cut.to, nextPos) - off; cut = fFrom >= fTo ? null : new _TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, cI > 0, !!nextC) } if (cut && result.push(cut), nextF.to > nextPos) break; nextF = fI < fragments.length ? fragments[fI++] : null } if (!nextC) break; pos = nextC.toA, off = nextC.toA - nextC.toB } return result } }, Parser = class { startParse(input, fragments, ranges) { return typeof input == "string" && (input = new StringInput(input)), ranges = ranges ? ranges.length ? ranges.map(r => new Range4(r.from, r.to)) : [new Range4(0, 0)] : [new Range4(0, input.length)], this.createParse(input, fragments || [], ranges) } parse(input, fragments, ranges) { let parse = this.startParse(input, fragments, ranges); for (; ;) { let done = parse.advance(); if (done) return done } } }, StringInput = class { constructor(string2) { this.string = string2 } get length() { return this.string.length } chunk(from) { return this.string.slice(from) } get lineChunks() { return !1 } read(from, to) { return this.string.slice(from, to) } }; var stoppedInner = new NodeProp({ perNode: !0 }); var languageDataProp = new NodeProp; function defineLanguageFacet(baseData) { return Facet.define({ combine: baseData ? values => values.concat(baseData) : void 0 }) } var sublanguageProp = new NodeProp, Language = class { constructor(data, parser, extraExtensions = [], name2 = "") { this.data = data; this.name = name2; EditorState.prototype.hasOwnProperty("tree") || Object.defineProperty(EditorState.prototype, "tree", { get() { return syntaxTree(this) } }), this.parser = parser, this.extension = [language.of(this), EditorState.languageData.of((state, pos, side) => { let top2 = topNodeAt(state, pos, side), data2 = top2.type.prop(languageDataProp); if (!data2) return []; let base2 = state.facet(data2), sub = top2.type.prop(sublanguageProp); if (sub) { let innerNode = top2.resolve(pos - top2.from, side); for (let sublang of sub) if (sublang.test(innerNode, state)) { let data3 = state.facet(sublang.facet); return sublang.type == "replace" ? data3 : data3.concat(base2) } } return base2 })].concat(extraExtensions) } data; name; extension; parser; isActiveAt(state, pos, side = -1) { return topNodeAt(state, pos, side).type.prop(languageDataProp) == this.data } findRegions(state) { let lang = state.facet(language); if (lang?.data == this.data) return [{ from: 0, to: state.doc.length }]; if (!lang || !lang.allowsNesting) return []; let result = [], explore = (tree, from) => { if (tree.prop(languageDataProp) == this.data) { result.push({ from, to: from + tree.length }); return } let mount = tree.prop(NodeProp.mounted); if (mount) { if (mount.tree.prop(languageDataProp) == this.data) { if (mount.overlay) for (let r of mount.overlay) result.push({ from: r.from + from, to: r.to + from }); else result.push({ from, to: from + tree.length }); return } else if (mount.overlay) { let size = result.length; if (explore(mount.tree, mount.overlay[0].from + from), result.length > size) return } } for (let i2 = 0; i2 < tree.children.length; i2++) { let ch = tree.children[i2]; ch instanceof Tree && explore(ch, tree.positions[i2] + from) } }; return explore(syntaxTree(state), 0), result } get allowsNesting() { return !0 } static state; static setState = StateEffect.define() }; function topNodeAt(state, pos, side) { let topLang = state.facet(language), tree = syntaxTree(state).topNode; if (!topLang || topLang.allowsNesting) for (let node = tree; node; node = node.enter(pos, side, 17))node.type.isTop && (tree = node); return tree } function syntaxTree(state) { let field = state.field(Language.state, !1); return field ? field.tree : Tree.empty } var DocInput = class { constructor(doc2) { this.doc = doc2; this.cursor = doc2.iter() } doc; cursor; cursorPos = 0; string = ""; get length() { return this.doc.length } syncTo(pos) { return this.string = this.cursor.next(pos - this.cursorPos).value, this.cursorPos = pos + this.string.length, this.cursorPos - this.string.length } chunk(pos) { return this.syncTo(pos), this.string } get lineChunks() { return !0 } read(from, to) { let stringStart = this.cursorPos - this.string.length; return from < stringStart || to >= this.cursorPos ? this.doc.sliceString(from, to) : this.string.slice(from - stringStart, to - stringStart) } }; var currentContext = null, ParseContext = class _ParseContext { constructor(parser, state, fragments = [], tree, treeLen, viewport, skipped, scheduleOn) { this.parser = parser; this.state = state; this.fragments = fragments; this.tree = tree; this.treeLen = treeLen; this.viewport = viewport; this.skipped = skipped; this.scheduleOn = scheduleOn } parser; state; fragments; tree; treeLen; viewport; skipped; scheduleOn; parse = null; tempSkipped = []; static create(parser, state, viewport) { return new _ParseContext(parser, state, [], Tree.empty, 0, viewport, [], null) } startParse() { return this.parser.startParse(new DocInput(this.state.doc), this.fragments) } work(until, upto) { return upto != null && upto >= this.state.doc.length && (upto = void 0), this.tree != Tree.empty && this.isDone(upto ?? this.state.doc.length) ? (this.takeTree(), !0) : this.withContext(() => { if (typeof until == "number") { let endTime = Date.now() + until; until = () => Date.now() > endTime } for (this.parse || (this.parse = this.startParse()), upto != null && (this.parse.stoppedAt == null || this.parse.stoppedAt > upto) && upto < this.state.doc.length && this.parse.stopAt(upto); ;) { let done = this.parse.advance(); if (done) if (this.fragments = this.withoutTempSkipped(TreeFragment.addTree(done, this.fragments, this.parse.stoppedAt != null)), this.treeLen = this.parse.stoppedAt ?? this.state.doc.length, this.tree = done, this.parse = null, this.treeLen < (upto ?? this.state.doc.length)) this.parse = this.startParse(); else return !0; if (until()) return !1 } }) } takeTree() { let pos, tree; this.parse && (pos = this.parse.parsedPos) >= this.treeLen && ((this.parse.stoppedAt == null || this.parse.stoppedAt > pos) && this.parse.stopAt(pos), this.withContext(() => { for (; !(tree = this.parse.advance());); }), this.treeLen = pos, this.tree = tree, this.fragments = this.withoutTempSkipped(TreeFragment.addTree(this.tree, this.fragments, !0)), this.parse = null) } withContext(f) { let prev = currentContext; currentContext = this; try { return f() } finally { currentContext = prev } } withoutTempSkipped(fragments) { for (let r; r = this.tempSkipped.pop();)fragments = cutFragments(fragments, r.from, r.to); return fragments } changes(changes, newState) { let { fragments, tree, treeLen, viewport, skipped } = this; if (this.takeTree(), !changes.empty) { let ranges = []; if (changes.iterChangedRanges((fromA, toA, fromB, toB) => ranges.push({ fromA, toA, fromB, toB })), fragments = TreeFragment.applyChanges(fragments, ranges), tree = Tree.empty, treeLen = 0, viewport = { from: changes.mapPos(viewport.from, -1), to: changes.mapPos(viewport.to, 1) }, this.skipped.length) { skipped = []; for (let r of this.skipped) { let from = changes.mapPos(r.from, 1), to = changes.mapPos(r.to, -1); from < to && skipped.push({ from, to }) } } } return new _ParseContext(this.parser, newState, fragments, tree, treeLen, viewport, skipped, this.scheduleOn) } updateViewport(viewport) { if (this.viewport.from == viewport.from && this.viewport.to == viewport.to) return !1; this.viewport = viewport; let startLen = this.skipped.length; for (let i2 = 0; i2 < this.skipped.length; i2++) { let { from, to } = this.skipped[i2]; from < viewport.to && to > viewport.from && (this.fragments = cutFragments(this.fragments, from, to), this.skipped.splice(i2--, 1)) } return this.skipped.length >= startLen ? !1 : (this.reset(), !0) } reset() { this.parse && (this.takeTree(), this.parse = null) } skipUntilInView(from, to) { this.skipped.push({ from, to }) } static getSkippingParser(until) { return new class extends Parser { createParse(input, fragments, ranges) { let from = ranges[0].from, to = ranges[ranges.length - 1].to; return { parsedPos: from, advance() { let cx = currentContext; if (cx) { for (let r of ranges) cx.tempSkipped.push(r); until && (cx.scheduleOn = cx.scheduleOn ? Promise.all([cx.scheduleOn, until]) : until) } return this.parsedPos = to, new Tree(NodeType.none, [], [], to - from) }, stoppedAt: null, stopAt() { } } } } } isDone(upto) { upto = Math.min(upto, this.state.doc.length); let frags = this.fragments; return this.treeLen >= upto && frags.length && frags[0].from == 0 && frags[0].to >= upto } static get() { return currentContext } }; function cutFragments(fragments, from, to) { return TreeFragment.applyChanges(fragments, [{ fromA: from, toA: to, fromB: from, toB: to }]) } var LanguageState = class _LanguageState { constructor(context) { this.context = context; this.tree = context.tree } context; tree; apply(tr) { if (!tr.docChanged && this.tree == this.context.tree) return this; let newCx = this.context.changes(tr.changes, tr.state), upto = this.context.treeLen == tr.startState.doc.length ? void 0 : Math.max(tr.changes.mapPos(this.context.treeLen), newCx.viewport.to); return newCx.work(20, upto) || newCx.takeTree(), new _LanguageState(newCx) } static init(state) { let vpTo = Math.min(3e3, state.doc.length), parseState = ParseContext.create(state.facet(language).parser, state, { from: 0, to: vpTo }); return parseState.work(20, vpTo) || parseState.takeTree(), new _LanguageState(parseState) } }; Language.state = StateField.define({ create: LanguageState.init, update(value, tr) { for (let e of tr.effects) if (e.is(Language.setState)) return e.value; return tr.startState.facet(language) != tr.state.facet(language) ? LanguageState.init(tr.state) : value.apply(tr) } }); var requestIdle = callback => { let timeout = setTimeout(() => callback(), 500); return () => clearTimeout(timeout) }; typeof requestIdleCallback < "u" && (requestIdle = callback => { let idle = -1, timeout = setTimeout(() => { idle = requestIdleCallback(callback, { timeout: 400 }) }, 100); return () => idle < 0 ? clearTimeout(timeout) : cancelIdleCallback(idle) }); var isInputPending = typeof navigator < "u" && navigator.scheduling?.isInputPending ? () => navigator.scheduling.isInputPending() : null, parseWorker = ViewPlugin.fromClass(class { constructor(view) { this.view = view; this.work = this.work.bind(this), this.scheduleWork() } view; working = null; workScheduled = 0; chunkEnd = -1; chunkBudget = -1; update(update) { let cx = this.view.state.field(Language.state).context; (cx.updateViewport(update.view.viewport) || this.view.viewport.to > cx.treeLen) && this.scheduleWork(), (update.docChanged || update.selectionSet) && (this.view.hasFocus && (this.chunkBudget += 50), this.scheduleWork()), this.checkAsyncSchedule(cx) } scheduleWork() { if (this.working) return; let { state } = this.view, field = state.field(Language.state); (field.tree != field.context.tree || !field.context.isDone(state.doc.length)) && (this.working = requestIdle(this.work)) } work(deadline) { this.working = null; let now = Date.now(); if (this.chunkEnd < now && (this.chunkEnd < 0 || this.view.hasFocus) && (this.chunkEnd = now + 3e4, this.chunkBudget = 3e3), this.chunkBudget <= 0) return; let { state, viewport: { to: vpTo } } = this.view, field = state.field(Language.state); if (field.tree == field.context.tree && field.context.isDone(vpTo + 1e5)) return; let endTime = Date.now() + Math.min(this.chunkBudget, 100, deadline && !isInputPending ? Math.max(25, deadline.timeRemaining() - 5) : 1e9), viewportFirst = field.context.treeLen < vpTo && state.doc.length > vpTo + 1e3, done = field.context.work(() => isInputPending && isInputPending() || Date.now() > endTime, vpTo + (viewportFirst ? 0 : 1e5)); this.chunkBudget -= Date.now() - now, (done || this.chunkBudget <= 0) && (field.context.takeTree(), this.view.dispatch({ effects: Language.setState.of(new LanguageState(field.context)) })), this.chunkBudget > 0 && !(done && !viewportFirst) && this.scheduleWork(), this.checkAsyncSchedule(field.context) } checkAsyncSchedule(cx) { cx.scheduleOn && (this.workScheduled++, cx.scheduleOn.then(() => this.scheduleWork()).catch(err => logException(this.view.state, err)).then(() => this.workScheduled--), cx.scheduleOn = null) } destroy() { this.working && this.working() } isWorking() { return !!(this.working || this.workScheduled > 0) } }, { eventHandlers: { focus() { this.scheduleWork() } } }), language = Facet.define({ combine(languages) { return languages.length ? languages[0] : null }, enables: language2 => [Language.state, parseWorker, EditorView.contentAttributes.compute([language2], state => { let lang = state.facet(language2); return lang && lang.name ? { "data-language": lang.name } : {} })] }), LanguageSupport = class { constructor(language2, support = []) { this.language = language2; this.support = support; this.extension = [language2, support] } language; support; extension }; var indentService = Facet.define(), indentUnit = Facet.define({ combine: values => { if (!values.length) return " "; let unit = values[0]; if (!unit || /\S/.test(unit) || Array.from(unit).some(e => e != unit[0])) throw new Error("Invalid indent unit: " + JSON.stringify(values[0])); return unit } }); function getIndentUnit(state) { let unit = state.facet(indentUnit); return unit.charCodeAt(0) == 9 ? state.tabSize * unit.length : unit.length } function indentString(state, cols) { let result = "", ts = state.tabSize, ch = state.facet(indentUnit)[0]; if (ch == " ") { for (; cols >= ts;)result += " ", cols -= ts; ch = " " } for (let i2 = 0; i2 < cols; i2++)result += ch; return result } function getIndentation(context, pos) { context instanceof EditorState && (context = new IndentContext(context)); for (let service of context.state.facet(indentService)) { let result = service(context, pos); if (result !== void 0) return result } let tree = syntaxTree(context.state); return tree.length >= pos ? syntaxIndentation(context, tree, pos) : null } var IndentContext = class { constructor(state, options = {}) { this.state = state; this.options = options; this.unit = getIndentUnit(state) } state; options; unit; lineAt(pos, bias = 1) { let line = this.state.doc.lineAt(pos), { simulateBreak, simulateDoubleBreak } = this.options; return simulateBreak != null && simulateBreak >= line.from && simulateBreak <= line.to ? simulateDoubleBreak && simulateBreak == pos ? { text: "", from: pos } : (bias < 0 ? simulateBreak < pos : simulateBreak <= pos) ? { text: line.text.slice(simulateBreak - line.from), from: simulateBreak } : { text: line.text.slice(0, simulateBreak - line.from), from: line.from } : line } textAfterPos(pos, bias = 1) { if (this.options.simulateDoubleBreak && pos == this.options.simulateBreak) return ""; let { text, from } = this.lineAt(pos, bias); return text.slice(pos - from, Math.min(text.length, pos + 100 - from)) } column(pos, bias = 1) { let { text, from } = this.lineAt(pos, bias), result = this.countColumn(text, pos - from), override = this.options.overrideIndentation ? this.options.overrideIndentation(from) : -1; return override > -1 && (result += override - this.countColumn(text, text.search(/\S|$/))), result } countColumn(line, pos = line.length) { return countColumn(line, this.state.tabSize, pos) } lineIndent(pos, bias = 1) { let { text, from } = this.lineAt(pos, bias), override = this.options.overrideIndentation; if (override) { let overriden = override(from); if (overriden > -1) return overriden } return this.countColumn(text, text.search(/\S|$/)) } get simulatedBreak() { return this.options.simulateBreak || null } }, indentNodeProp = new NodeProp; function syntaxIndentation(cx, ast, pos) { let stack = ast.resolveStack(pos), inner = ast.resolveInner(pos, -1).resolve(pos, 0).enterUnfinishedNodesBefore(pos); if (inner != stack.node) { let add2 = []; for (let cur = inner; cur && !(cur.from < stack.node.from || cur.to > stack.node.to || cur.from == stack.node.from && cur.type == stack.node.type); cur = cur.parent)add2.push(cur); for (let i2 = add2.length - 1; i2 >= 0; i2--)stack = { node: add2[i2], next: stack } } return indentFor(stack, cx, pos) } function indentFor(stack, cx, pos) { for (let cur = stack; cur; cur = cur.next) { let strategy = indentStrategy(cur.node); if (strategy) return strategy(TreeIndentContext.create(cx, pos, cur)) } return 0 } function ignoreClosed(cx) { return cx.pos == cx.options.simulateBreak && cx.options.simulateDoubleBreak } function indentStrategy(tree) { let strategy = tree.type.prop(indentNodeProp); if (strategy) return strategy; let first = tree.firstChild, close; if (first && (close = first.type.prop(NodeProp.closedBy))) { let last = tree.lastChild, closed = last && close.indexOf(last.name) > -1; return cx => delimitedStrategy(cx, !0, 1, void 0, closed && !ignoreClosed(cx) ? last.from : void 0) } return tree.parent == null ? topIndent : null } function topIndent() { return 0 } var TreeIndentContext = class _TreeIndentContext extends IndentContext { constructor(base2, pos, context) { super(base2.state, base2.options); this.base = base2; this.pos = pos; this.context = context } base; pos; context; get node() { return this.context.node } static create(base2, pos, context) { return new _TreeIndentContext(base2, pos, context) } get textAfter() { return this.textAfterPos(this.pos) } get baseIndent() { return this.baseIndentFor(this.node) } baseIndentFor(node) { let line = this.state.doc.lineAt(node.from); for (; ;) { let atBreak = node.resolve(line.from); for (; atBreak.parent && atBreak.parent.from == atBreak.from;)atBreak = atBreak.parent; if (isParent(atBreak, node)) break; line = this.state.doc.lineAt(atBreak.from) } return this.lineIndent(line.from) } continue() { return indentFor(this.context.next, this.base, this.pos) } }; function isParent(parent, of) { for (let cur = of; cur; cur = cur.parent)if (parent == cur) return !0; return !1 } function bracketedAligned(context) { let tree = context.node, openToken = tree.childAfter(tree.from), last = tree.lastChild; if (!openToken) return null; let sim = context.options.simulateBreak, openLine = context.state.doc.lineAt(openToken.from), lineEnd = sim == null || sim <= openLine.from ? openLine.to : Math.min(openLine.to, sim); for (let pos = openToken.to; ;) { let next = tree.childAfter(pos); if (!next || next == last) return null; if (!next.type.isSkipped) { if (next.from >= lineEnd) return null; let space = /^ */.exec(openLine.text.slice(openToken.to - openLine.from))[0].length; return { from: openToken.from, to: openToken.to + space } } pos = next.to } } function delimitedStrategy(context, align, units, closing, closedAt) { let after = context.textAfter, space = after.match(/^\s*/)[0].length, closed = closing && after.slice(space, space + closing.length) == closing || closedAt == context.pos + space, aligned = align ? bracketedAligned(context) : null; return aligned ? closed ? context.column(aligned.from) : context.column(aligned.to) : context.baseIndent + (closed ? 0 : context.unit * units) } var foldService = Facet.define(), foldNodeProp = new NodeProp; function syntaxFolding(state, start, end) { let tree = syntaxTree(state); if (tree.length < end) return null; let stack = tree.resolveStack(end, 1), found = null; for (let iter = stack; iter; iter = iter.next) { let cur = iter.node; if (cur.to <= end || cur.from > end) continue; if (found && cur.from < start) break; let prop = cur.type.prop(foldNodeProp); if (prop && (cur.to < tree.length - 50 || tree.length == state.doc.length || !isUnfinished(cur))) { let value = prop(cur, state); value && value.from <= end && value.from >= start && value.to > end && (found = value) } } return found } function isUnfinished(node) { let ch = node.lastChild; return ch && ch.to == node.to && ch.type.isError } function foldable(state, lineStart, lineEnd) { for (let service of state.facet(foldService)) { let result = service(state, lineStart, lineEnd); if (result) return result } return syntaxFolding(state, lineStart, lineEnd) } function mapRange(range, mapping) { let from = mapping.mapPos(range.from, 1), to = mapping.mapPos(range.to, -1); return from >= to ? void 0 : { from, to } } var foldEffect = StateEffect.define({ map: mapRange }), unfoldEffect = StateEffect.define({ map: mapRange }); function selectedLines(view) { let lines = []; for (let { head } of view.state.selection.ranges) lines.some(l => l.from <= head && l.to >= head) || lines.push(view.lineBlockAt(head)); return lines } var foldState = StateField.define({ create() { return Decoration.none }, update(folded, tr) { tr.isUserEvent("delete") && tr.changes.iterChangedRanges((fromA, toA) => folded = clearTouchedFolds(folded, fromA, toA)), folded = folded.map(tr.changes); for (let e of tr.effects) if (e.is(foldEffect) && !foldExists(folded, e.value.from, e.value.to)) { let { preparePlaceholder } = tr.state.facet(foldConfig), widget = preparePlaceholder ? Decoration.replace({ widget: new PreparedFoldWidget(preparePlaceholder(tr.state, e.value)) }) : foldWidget; folded = folded.update({ add: [widget.range(e.value.from, e.value.to)] }) } else e.is(unfoldEffect) && (folded = folded.update({ filter: (from, to) => e.value.from != from || e.value.to != to, filterFrom: e.value.from, filterTo: e.value.to })); return tr.selection && (folded = clearTouchedFolds(folded, tr.selection.main.head)), folded }, provide: f => EditorView.decorations.from(f), toJSON(folded, state) { let ranges = []; return folded.between(0, state.doc.length, (from, to) => { ranges.push(from, to) }), ranges }, fromJSON(value) { if (!Array.isArray(value) || value.length % 2) throw new RangeError("Invalid JSON for fold state"); let ranges = []; for (let i2 = 0; i2 < value.length;) { let from = value[i2++], to = value[i2++]; if (typeof from != "number" || typeof to != "number") throw new RangeError("Invalid JSON for fold state"); ranges.push(foldWidget.range(from, to)) } return Decoration.set(ranges, !0) } }); function clearTouchedFolds(folded, from, to = from) { let touched = !1; return folded.between(from, to, (a, b) => { a < to && b > from && (touched = !0) }), touched ? folded.update({ filterFrom: from, filterTo: to, filter: (a, b) => a >= to || b <= from }) : folded } function findFold(state, from, to) { let found = null; return state.field(foldState, !1)?.between(from, to, (from2, to2) => { (!found || found.from > from2) && (found = { from: from2, to: to2 }) }), found } function foldExists(folded, from, to) { let found = !1; return folded.between(from, from, (a, b) => { a == from && b == to && (found = !0) }), found } function maybeEnable(state, other) { return state.field(foldState, !1) ? other : other.concat(StateEffect.appendConfig.of(codeFolding())) } var foldCode = view => { for (let line of selectedLines(view)) { let range = foldable(view.state, line.from, line.to); if (range) return view.dispatch({ effects: maybeEnable(view.state, [foldEffect.of(range), announceFold(view, range)]) }), !0 } return !1 }, unfoldCode = view => { if (!view.state.field(foldState, !1)) return !1; let effects = []; for (let line of selectedLines(view)) { let folded = findFold(view.state, line.from, line.to); folded && effects.push(unfoldEffect.of(folded), announceFold(view, folded, !1)) } return effects.length && view.dispatch({ effects }), effects.length > 0 }; function announceFold(view, range, fold = !0) { let lineFrom = view.state.doc.lineAt(range.from).number, lineTo = view.state.doc.lineAt(range.to).number; return EditorView.announce.of(`${view.state.phrase(fold ? "Folded lines" : "Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`) } var foldAll = view => { let { state } = view, effects = []; for (let pos = 0; pos < state.doc.length;) { let line = view.lineBlockAt(pos), range = foldable(state, line.from, line.to); range && effects.push(foldEffect.of(range)), pos = (range ? view.lineBlockAt(range.to) : line).to + 1 } return effects.length && view.dispatch({ effects: maybeEnable(view.state, effects) }), !!effects.length }, unfoldAll = view => { let field = view.state.field(foldState, !1); if (!field || !field.size) return !1; let effects = []; return field.between(0, view.state.doc.length, (from, to) => { effects.push(unfoldEffect.of({ from, to })) }), view.dispatch({ effects }), !0 }; var foldKeymap = [{ key: "Ctrl-Shift-[", mac: "Cmd-Alt-[", run: foldCode }, { key: "Ctrl-Shift-]", mac: "Cmd-Alt-]", run: unfoldCode }, { key: "Ctrl-Alt-[", run: foldAll }, { key: "Ctrl-Alt-]", run: unfoldAll }], defaultConfig = { placeholderDOM: null, preparePlaceholder: null, placeholderText: "\u2026" }, foldConfig = Facet.define({ combine(values) { return combineConfig(values, defaultConfig) } }); function codeFolding(config) { let result = [foldState, baseTheme3]; return config && result.push(foldConfig.of(config)), result } function widgetToDOM(view, prepared) { let { state } = view, conf = state.facet(foldConfig), onclick = event => { let line = view.lineBlockAt(view.posAtDOM(event.target)), folded = findFold(view.state, line.from, line.to); folded && view.dispatch({ effects: unfoldEffect.of(folded) }), event.preventDefault() }; if (conf.placeholderDOM) return conf.placeholderDOM(view, onclick, prepared); let element = document.createElement("span"); return element.textContent = conf.placeholderText, element.setAttribute("aria-label", state.phrase("folded code")), element.title = state.phrase("unfold"), element.className = "cm-foldPlaceholder", element.onclick = onclick, element } var foldWidget = Decoration.replace({ widget: new class extends WidgetType { toDOM(view) { return widgetToDOM(view, null) } } }), PreparedFoldWidget = class extends WidgetType { constructor(value) { super(); this.value = value } value; eq(other) { return this.value == other.value } toDOM(view) { return widgetToDOM(view, this.value) } }, foldGutterDefaults = { openText: "\u2304", closedText: "\u203A", markerDOM: null, domEventHandlers: {}, foldingChanged: () => !1 }, FoldMarker = class extends GutterMarker { constructor(config, open) { super(); this.config = config; this.open = open } config; open; eq(other) { return this.config == other.config && this.open == other.open } toDOM(view) { if (this.config.markerDOM) return this.config.markerDOM(this.open); let span = document.createElement("span"); return span.textContent = this.open ? this.config.openText : this.config.closedText, span.title = view.state.phrase(this.open ? "Fold line" : "Unfold line"), span } }; function foldGutter(config = {}) { let fullConfig = { ...foldGutterDefaults, ...config }, canFold = new FoldMarker(fullConfig, !0), canUnfold = new FoldMarker(fullConfig, !1), markers = ViewPlugin.fromClass(class { markers; from; constructor(view) { this.from = view.viewport.from, this.markers = this.buildMarkers(view) } update(update) { (update.docChanged || update.viewportChanged || update.startState.facet(language) != update.state.facet(language) || update.startState.field(foldState, !1) != update.state.field(foldState, !1) || syntaxTree(update.startState) != syntaxTree(update.state) || fullConfig.foldingChanged(update)) && (this.markers = this.buildMarkers(update.view)) } buildMarkers(view) { let builder = new RangeSetBuilder; for (let line of view.viewportLineBlocks) { let mark = findFold(view.state, line.from, line.to) ? canUnfold : foldable(view.state, line.from, line.to) ? canFold : null; mark && builder.add(line.from, line.from, mark) } return builder.finish() } }), { domEventHandlers } = fullConfig; return [markers, gutter({ class: "cm-foldGutter", markers(view) { return view.plugin(markers)?.markers || RangeSet.empty }, initialSpacer() { return new FoldMarker(fullConfig, !1) }, domEventHandlers: { ...domEventHandlers, click: (view, line, event) => { if (domEventHandlers.click && domEventHandlers.click(view, line, event)) return !0; let folded = findFold(view.state, line.from, line.to); if (folded) return view.dispatch({ effects: unfoldEffect.of(folded) }), !0; let range = foldable(view.state, line.from, line.to); return range ? (view.dispatch({ effects: foldEffect.of(range) }), !0) : !1 } } }), codeFolding()] } var baseTheme3 = EditorView.baseTheme({ ".cm-foldPlaceholder": { backgroundColor: "#eee", border: "1px solid #ddd", color: "#888", borderRadius: ".2em", margin: "0 1px", padding: "0 1px", cursor: "pointer" }, ".cm-foldGutter span": { padding: "0 1px", cursor: "pointer" } }); var nextTagID = 0, Tag = class _Tag { constructor(name2, set, base2, modified) { this.name = name2; this.set = set; this.base = base2; this.modified = modified } name; set; base; modified; id = nextTagID++; toString() { let { name: name2 } = this; for (let mod of this.modified) mod.name && (name2 = `${mod.name}(${name2})`); return name2 } static define(nameOrParent, parent) { let name2 = typeof nameOrParent == "string" ? nameOrParent : "?"; if (nameOrParent instanceof _Tag && (parent = nameOrParent), parent?.base) throw new Error("Can not derive from a modified tag"); let tag = new _Tag(name2, [], null, []); if (tag.set.push(tag), parent) for (let t2 of parent.set) tag.set.push(t2); return tag } static defineModifier(name2) { let mod = new Modifier(name2); return tag => tag.modified.indexOf(mod) > -1 ? tag : Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a, b) => a.id - b.id)) } }, nextModifierID = 0, Modifier = class _Modifier { constructor(name2) { this.name = name2 } name; instances = []; id = nextModifierID++; static get(base2, mods) { if (!mods.length) return base2; let exists = mods[0].instances.find(t2 => t2.base == base2 && sameArray2(mods, t2.modified)); if (exists) return exists; let set = [], tag = new Tag(base2.name, set, base2, mods); for (let m of mods) m.instances.push(tag); let configs = powerSet(mods); for (let parent of base2.set) if (!parent.modified.length) for (let config of configs) set.push(_Modifier.get(parent, config)); return tag } }; function sameArray2(a, b) { return a.length == b.length && a.every((x, i2) => x == b[i2]) } function powerSet(array) { let sets = [[]]; for (let i2 = 0; i2 < array.length; i2++)for (let j = 0, e = sets.length; j < e; j++)sets.push(sets[j].concat(array[i2])); return sets.sort((a, b) => b.length - a.length) } function styleTags(spec) { let byName = Object.create(null); for (let prop in spec) { let tags2 = spec[prop]; Array.isArray(tags2) || (tags2 = [tags2]); for (let part of prop.split(" ")) if (part) { let pieces = [], mode = 2, rest = part; for (let pos = 0; ;) { if (rest == "..." && pos > 0 && pos + 3 == part.length) { mode = 1; break } let m = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest); if (!m) throw new RangeError("Invalid path: " + part); if (pieces.push(m[0] == "*" ? "" : m[0][0] == '"' ? JSON.parse(m[0]) : m[0]), pos += m[0].length, pos == part.length) break; let next = part[pos++]; if (pos == part.length && next == "!") { mode = 0; break } if (next != "/") throw new RangeError("Invalid path: " + part); rest = part.slice(pos) } let last = pieces.length - 1, inner = pieces[last]; if (!inner) throw new RangeError("Invalid path: " + part); let rule = new Rule(tags2, mode, last > 0 ? pieces.slice(0, last) : null); byName[inner] = rule.sort(byName[inner]) } } return ruleNodeProp.add(byName) } var ruleNodeProp = new NodeProp({ combine(a, b) { let cur, root, take; for (; a || b;) { if (!a || b && a.depth >= b.depth ? (take = b, b = b.next) : (take = a, a = a.next), cur && cur.mode == take.mode && !take.context && !cur.context) continue; let copy = new Rule(take.tags, take.mode, take.context); cur ? cur.next = copy : root = copy, cur = copy } return root } }); var Rule = class _Rule { constructor(tags2, mode, context, next) { this.tags = tags2; this.mode = mode; this.context = context; this.next = next } tags; mode; context; next; get opaque() { return this.mode == 0 } get inherit() { return this.mode == 1 } sort(other) { return !other || other.depth < this.depth ? (this.next = other, this) : (other.next = this.sort(other.next), other) } get depth() { return this.context ? this.context.length : 0 } static empty = new _Rule([], 2, null) }; function tagHighlighter(tags2, options) { let map = Object.create(null); for (let style of tags2) if (!Array.isArray(style.tag)) map[style.tag.id] = style.class; else for (let tag of style.tag) map[tag.id] = style.class; let { scope, all = null } = options || {}; return { style: tags3 => { let cls = all; for (let tag of tags3) for (let sub of tag.set) { let tagClass = map[sub.id]; if (tagClass) { cls = cls ? cls + " " + tagClass : tagClass; break } } return cls }, scope } } function highlightTags(highlighters, tags2) { let result = null; for (let highlighter of highlighters) { let value = highlighter.style(tags2); value && (result = result ? result + " " + value : value) } return result } function highlightTree(tree, highlighter, putStyle, from = 0, to = tree.length) { let builder = new HighlightBuilder(from, Array.isArray(highlighter) ? highlighter : [highlighter], putStyle); builder.highlightRange(tree.cursor(), from, to, "", builder.highlighters), builder.flush(to) } var HighlightBuilder = class { constructor(at, highlighters, span) { this.at = at; this.highlighters = highlighters; this.span = span } at; highlighters; span; class = ""; startSpan(at, cls) { cls != this.class && (this.flush(at), at > this.at && (this.at = at), this.class = cls) } flush(to) { to > this.at && this.class && this.span(this.at, to, this.class) } highlightRange(cursor, from, to, inheritedClass, highlighters) { let { type, from: start, to: end } = cursor; if (start >= to || end <= from) return; type.isTop && (highlighters = this.highlighters.filter(h => !h.scope || h.scope(type))); let cls = inheritedClass, rule = getStyleTags(cursor) || Rule.empty, tagCls = highlightTags(highlighters, rule.tags); if (tagCls && (cls && (cls += " "), cls += tagCls, rule.mode == 1 && (inheritedClass += (inheritedClass ? " " : "") + tagCls)), this.startSpan(Math.max(from, start), cls), rule.opaque) return; let mounted = cursor.tree && cursor.tree.prop(NodeProp.mounted); if (mounted && mounted.overlay) { let inner = cursor.node.enter(mounted.overlay[0].from + start, 1), innerHighlighters = this.highlighters.filter(h => !h.scope || h.scope(mounted.tree.type)), hasChild2 = cursor.firstChild(); for (let i2 = 0, pos = start; ; i2++) { let next = i2 < mounted.overlay.length ? mounted.overlay[i2] : null, nextPos = next ? next.from + start : end, rangeFrom2 = Math.max(from, pos), rangeTo2 = Math.min(to, nextPos); if (rangeFrom2 < rangeTo2 && hasChild2) for (; cursor.from < rangeTo2 && (this.highlightRange(cursor, rangeFrom2, rangeTo2, inheritedClass, highlighters), this.startSpan(Math.min(rangeTo2, cursor.to), cls), !(cursor.to >= nextPos || !cursor.nextSibling()));); if (!next || nextPos > to) break; pos = next.to + start, pos > from && (this.highlightRange(inner.cursor(), Math.max(from, next.from + start), Math.min(to, pos), "", innerHighlighters), this.startSpan(Math.min(to, pos), cls)) } hasChild2 && cursor.parent() } else if (cursor.firstChild()) { mounted && (inheritedClass = ""); do if (!(cursor.to <= from)) { if (cursor.from >= to) break; this.highlightRange(cursor, from, to, inheritedClass, highlighters), this.startSpan(Math.min(to, cursor.to), cls) } while (cursor.nextSibling()); cursor.parent() } } }; function getStyleTags(node) { let rule = node.type.prop(ruleNodeProp); for (; rule && rule.context && !node.matchContext(rule.context);)rule = rule.next; return rule || null } var t = Tag.define, comment = t(), name = t(), typeName = t(name), propertyName = t(name), literal = t(), string = t(literal), number = t(literal), content = t(), heading = t(content), keyword = t(), operator = t(), punctuation = t(), bracket = t(punctuation), meta = t(), tags = { comment, lineComment: t(comment), blockComment: t(comment), docComment: t(comment), name, variableName: t(name), typeName, tagName: t(typeName), propertyName, attributeName: t(propertyName), className: t(name), labelName: t(name), namespace: t(name), macroName: t(name), literal, string, docString: t(string), character: t(string), attributeValue: t(string), number, integer: t(number), float: t(number), bool: t(literal), regexp: t(literal), escape: t(literal), color: t(literal), url: t(literal), keyword, self: t(keyword), null: t(keyword), atom: t(keyword), unit: t(keyword), modifier: t(keyword), operatorKeyword: t(keyword), controlKeyword: t(keyword), definitionKeyword: t(keyword), moduleKeyword: t(keyword), operator, derefOperator: t(operator), arithmeticOperator: t(operator), logicOperator: t(operator), bitwiseOperator: t(operator), compareOperator: t(operator), updateOperator: t(operator), definitionOperator: t(operator), typeOperator: t(operator), controlOperator: t(operator), punctuation, separator: t(punctuation), bracket, angleBracket: t(bracket), squareBracket: t(bracket), paren: t(bracket), brace: t(bracket), content, heading, heading1: t(heading), heading2: t(heading), heading3: t(heading), heading4: t(heading), heading5: t(heading), heading6: t(heading), contentSeparator: t(content), list: t(content), quote: t(content), emphasis: t(content), strong: t(content), link: t(content), monospace: t(content), strikethrough: t(content), inserted: t(), deleted: t(), changed: t(), invalid: t(), meta, documentMeta: t(meta), annotation: t(meta), processingInstruction: t(meta), definition: Tag.defineModifier("definition"), constant: Tag.defineModifier("constant"), function: Tag.defineModifier("function"), standard: Tag.defineModifier("standard"), local: Tag.defineModifier("local"), special: Tag.defineModifier("special") }; for (let name2 in tags) { let val = tags[name2]; val instanceof Tag && (val.name = name2) } var classHighlighter = tagHighlighter([{ tag: tags.link, class: "tok-link" }, { tag: tags.heading, class: "tok-heading" }, { tag: tags.emphasis, class: "tok-emphasis" }, { tag: tags.strong, class: "tok-strong" }, { tag: tags.keyword, class: "tok-keyword" }, { tag: tags.atom, class: "tok-atom" }, { tag: tags.bool, class: "tok-bool" }, { tag: tags.url, class: "tok-url" }, { tag: tags.labelName, class: "tok-labelName" }, { tag: tags.inserted, class: "tok-inserted" }, { tag: tags.deleted, class: "tok-deleted" }, { tag: tags.literal, class: "tok-literal" }, { tag: tags.string, class: "tok-string" }, { tag: tags.number, class: "tok-number" }, { tag: [tags.regexp, tags.escape, tags.special(tags.string)], class: "tok-string2" }, { tag: tags.variableName, class: "tok-variableName" }, { tag: tags.local(tags.variableName), class: "tok-variableName tok-local" }, { tag: tags.definition(tags.variableName), class: "tok-variableName tok-definition" }, { tag: tags.special(tags.variableName), class: "tok-variableName2" }, { tag: tags.definition(tags.propertyName), class: "tok-propertyName tok-definition" }, { tag: tags.typeName, class: "tok-typeName" }, { tag: tags.namespace, class: "tok-namespace" }, { tag: tags.className, class: "tok-className" }, { tag: tags.macroName, class: "tok-macroName" }, { tag: tags.propertyName, class: "tok-propertyName" }, { tag: tags.operator, class: "tok-operator" }, { tag: tags.comment, class: "tok-comment" }, { tag: tags.meta, class: "tok-meta" }, { tag: tags.invalid, class: "tok-invalid" }, { tag: tags.punctuation, class: "tok-punctuation" }]); var HighlightStyle = class _HighlightStyle { constructor(specs, options) { this.specs = specs; let modSpec; function def(spec) { let cls = StyleModule.newName(); return (modSpec || (modSpec = Object.create(null)))["." + cls] = spec, cls } let all = typeof options.all == "string" ? options.all : options.all ? def(options.all) : void 0, scopeOpt = options.scope; this.scope = scopeOpt instanceof Language ? type => type.prop(languageDataProp) == scopeOpt.data : scopeOpt ? type => type == scopeOpt : void 0, this.style = tagHighlighter(specs.map(style => ({ tag: style.tag, class: style.class || def(Object.assign({}, style, { tag: null })) })), { all }).style, this.module = modSpec ? new StyleModule(modSpec) : null, this.themeType = options.themeType } specs; module; themeType; style; scope; static define(specs, options) { return new _HighlightStyle(specs, options || {}) } }, highlighterFacet = Facet.define(), fallbackHighlighter = Facet.define({ combine(values) { return values.length ? [values[0]] : null } }); function getHighlighters(state) { let main = state.facet(highlighterFacet); return main.length ? main : state.facet(fallbackHighlighter) } function syntaxHighlighting(highlighter, options) { let ext = [treeHighlighter], themeType; return highlighter instanceof HighlightStyle && (highlighter.module && ext.push(EditorView.styleModule.of(highlighter.module)), themeType = highlighter.themeType), options?.fallback ? ext.push(fallbackHighlighter.of(highlighter)) : themeType ? ext.push(highlighterFacet.computeN([EditorView.darkTheme], state => state.facet(EditorView.darkTheme) == (themeType == "dark") ? [highlighter] : [])) : ext.push(highlighterFacet.of(highlighter)), ext } var TreeHighlighter = class { decorations; decoratedTo; tree; markCache = Object.create(null); constructor(view) { this.tree = syntaxTree(view.state), this.decorations = this.buildDeco(view, getHighlighters(view.state)), this.decoratedTo = view.viewport.to } update(update) { let tree = syntaxTree(update.state), highlighters = getHighlighters(update.state), styleChange = highlighters != getHighlighters(update.startState), { viewport } = update.view, decoratedToMapped = update.changes.mapPos(this.decoratedTo, 1); tree.length < viewport.to && !styleChange && tree.type == this.tree.type && decoratedToMapped >= viewport.to ? (this.decorations = this.decorations.map(update.changes), this.decoratedTo = decoratedToMapped) : (tree != this.tree || update.viewportChanged || styleChange) && (this.tree = tree, this.decorations = this.buildDeco(update.view, highlighters), this.decoratedTo = viewport.to) } buildDeco(view, highlighters) { if (!highlighters || !this.tree.length) return Decoration.none; let builder = new RangeSetBuilder; for (let { from, to } of view.visibleRanges) highlightTree(this.tree, highlighters, (from2, to2, style) => { builder.add(from2, to2, this.markCache[style] || (this.markCache[style] = Decoration.mark({ class: style }))) }, from, to); return builder.finish() } }, treeHighlighter = Prec.high(ViewPlugin.fromClass(TreeHighlighter, { decorations: v => v.decorations })), defaultHighlightStyle = HighlightStyle.define([{ tag: tags.meta, color: "#404740" }, { tag: tags.link, textDecoration: "underline" }, { tag: tags.heading, textDecoration: "underline", fontWeight: "bold" }, { tag: tags.emphasis, fontStyle: "italic" }, { tag: tags.strong, fontWeight: "bold" }, { tag: tags.strikethrough, textDecoration: "line-through" }, { tag: tags.keyword, color: "#708" }, { tag: [tags.atom, tags.bool, tags.url, tags.contentSeparator, tags.labelName], color: "#219" }, { tag: [tags.literal, tags.inserted], color: "#164" }, { tag: [tags.string, tags.deleted], color: "#a11" }, { tag: [tags.regexp, tags.escape, tags.special(tags.string)], color: "#e40" }, { tag: tags.definition(tags.variableName), color: "#00f" }, { tag: tags.local(tags.variableName), color: "#30a" }, { tag: [tags.typeName, tags.namespace], color: "#085" }, { tag: tags.className, color: "#167" }, { tag: [tags.special(tags.variableName), tags.macroName], color: "#256" }, { tag: tags.definition(tags.propertyName), color: "#00c" }, { tag: tags.comment, color: "#940" }, { tag: tags.invalid, color: "#f00" }]); var baseTheme4 = EditorView.baseTheme({ "&.cm-focused .cm-matchingBracket": { backgroundColor: "#328c8252" }, "&.cm-focused .cm-nonmatchingBracket": { backgroundColor: "#bb555544" } }), DefaultScanDist = 1e4, DefaultBrackets = "()[]{}", bracketMatchingConfig = Facet.define({ combine(configs) { return combineConfig(configs, { afterCursor: !0, brackets: DefaultBrackets, maxScanDistance: DefaultScanDist, renderMatch: defaultRenderMatch }) } }), matchingMark = Decoration.mark({ class: "cm-matchingBracket" }), nonmatchingMark = Decoration.mark({ class: "cm-nonmatchingBracket" }); function defaultRenderMatch(match) { let decorations2 = [], mark = match.matched ? matchingMark : nonmatchingMark; return decorations2.push(mark.range(match.start.from, match.start.to)), match.end && decorations2.push(mark.range(match.end.from, match.end.to)), decorations2 } function bracketDeco(state) { let decorations2 = [], config = state.facet(bracketMatchingConfig); for (let range of state.selection.ranges) { if (!range.empty) continue; let match = matchBrackets(state, range.head, -1, config) || range.head > 0 && matchBrackets(state, range.head - 1, 1, config) || config.afterCursor && (matchBrackets(state, range.head, 1, config) || range.head < state.doc.length && matchBrackets(state, range.head + 1, -1, config)); match && (decorations2 = decorations2.concat(config.renderMatch(match, state))) } return Decoration.set(decorations2, !0) } var bracketMatcher = ViewPlugin.fromClass(class { decorations; paused = !1; constructor(view) { this.decorations = bracketDeco(view.state) } update(update) { (update.docChanged || update.selectionSet || this.paused) && (update.view.composing ? (this.decorations = this.decorations.map(update.changes), this.paused = !0) : (this.decorations = bracketDeco(update.state), this.paused = !1)) } }, { decorations: v => v.decorations }), bracketMatchingUnique = [bracketMatcher, baseTheme4]; function bracketMatching(config = {}) { return [bracketMatchingConfig.of(config), bracketMatchingUnique] } var bracketMatchingHandle = new NodeProp; function matchingNodes(node, dir, brackets) { let byProp = node.prop(dir < 0 ? NodeProp.openedBy : NodeProp.closedBy); if (byProp) return byProp; if (node.name.length == 1) { let index = brackets.indexOf(node.name); if (index > -1 && index % 2 == (dir < 0 ? 1 : 0)) return [brackets[index + dir]] } return null } function findHandle(node) { let hasHandle = node.type.prop(bracketMatchingHandle); return hasHandle ? hasHandle(node.node) : node } function matchBrackets(state, pos, dir, config = {}) { let maxScanDistance = config.maxScanDistance || DefaultScanDist, brackets = config.brackets || DefaultBrackets, tree = syntaxTree(state), node = tree.resolveInner(pos, dir); for (let cur = node; cur; cur = cur.parent) { let matches = matchingNodes(cur.type, dir, brackets); if (matches && cur.from < cur.to) { let handle = findHandle(cur); if (handle && (dir > 0 ? pos >= handle.from && pos < handle.to : pos > handle.from && pos <= handle.to)) return matchMarkedBrackets(state, pos, dir, cur, handle, matches, brackets) } } return matchPlainBrackets(state, pos, dir, tree, node.type, maxScanDistance, brackets) } function matchMarkedBrackets(_state, _pos, dir, token, handle, matching, brackets) { let parent = token.parent, firstToken = { from: handle.from, to: handle.to }, depth2 = 0, cursor = parent?.cursor(); if (cursor && (dir < 0 ? cursor.childBefore(token.from) : cursor.childAfter(token.to))) do if (dir < 0 ? cursor.to <= token.from : cursor.from >= token.to) { if (depth2 == 0 && matching.indexOf(cursor.type.name) > -1 && cursor.from < cursor.to) { let endHandle = findHandle(cursor); return { start: firstToken, end: endHandle ? { from: endHandle.from, to: endHandle.to } : void 0, matched: !0 } } else if (matchingNodes(cursor.type, dir, brackets)) depth2++; else if (matchingNodes(cursor.type, -dir, brackets)) { if (depth2 == 0) { let endHandle = findHandle(cursor); return { start: firstToken, end: endHandle && endHandle.from < endHandle.to ? { from: endHandle.from, to: endHandle.to } : void 0, matched: !1 } } depth2-- } } while (dir < 0 ? cursor.prevSibling() : cursor.nextSibling()); return { start: firstToken, matched: !1 } } function matchPlainBrackets(state, pos, dir, tree, tokenType, maxScanDistance, brackets) { if (dir < 0 ? !pos : pos == state.doc.length) return null; let startCh = dir < 0 ? state.sliceDoc(pos - 1, pos) : state.sliceDoc(pos, pos + 1), bracket2 = brackets.indexOf(startCh); if (bracket2 < 0 || bracket2 % 2 == 0 != dir > 0) return null; let startToken = { from: dir < 0 ? pos - 1 : pos, to: dir > 0 ? pos + 1 : pos }, iter = state.doc.iterRange(pos, dir > 0 ? state.doc.length : 0), depth2 = 0; for (let distance = 0; !iter.next().done && distance <= maxScanDistance;) { let text = iter.value; dir < 0 && (distance += text.length); let basePos = pos + distance * dir; for (let pos2 = dir > 0 ? 0 : text.length - 1, end = dir > 0 ? text.length : -1; pos2 != end; pos2 += dir) { let found = brackets.indexOf(text[pos2]); if (!(found < 0 || tree.resolveInner(basePos + pos2, 1).type != tokenType)) if (found % 2 == 0 == dir > 0) depth2++; else { if (depth2 == 1) return { start: startToken, end: { from: basePos + pos2, to: basePos + pos2 + 1 }, matched: found >> 1 == bracket2 >> 1 }; depth2-- } } dir > 0 && (distance += text.length) } return iter.done ? { start: startToken, matched: !1 } : null } function countCol(string2, end, tabSize, startIndex = 0, startValue = 0) { end == null && (end = string2.search(/[^\s\u00a0]/), end == -1 && (end = string2.length)); let n = startValue; for (let i2 = startIndex; i2 < end; i2++)string2.charCodeAt(i2) == 9 ? n += tabSize - n % tabSize : n++; return n } var StringStream = class { constructor(string2, tabSize, indentUnit2, overrideIndent) { this.string = string2; this.tabSize = tabSize; this.indentUnit = indentUnit2; this.overrideIndent = overrideIndent } string; tabSize; indentUnit; overrideIndent; pos = 0; start = 0; lastColumnPos = 0; lastColumnValue = 0; eol() { return this.pos >= this.string.length } sol() { return this.pos == 0 } peek() { return this.string.charAt(this.pos) || void 0 } next() { if (this.pos < this.string.length) return this.string.charAt(this.pos++) } eat(match) { let ch = this.string.charAt(this.pos), ok; if (typeof match == "string" ? ok = ch == match : ok = ch && (match instanceof RegExp ? match.test(ch) : match(ch)), ok) return ++this.pos, ch } eatWhile(match) { let start = this.pos; for (; this.eat(match);); return this.pos > start } eatSpace() { let start = this.pos; for (; /[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos; return this.pos > start } skipToEnd() { this.pos = this.string.length } skipTo(ch) { let found = this.string.indexOf(ch, this.pos); if (found > -1) return this.pos = found, !0 } backUp(n) { this.pos -= n } column() { return this.lastColumnPos < this.start && (this.lastColumnValue = countCol(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue), this.lastColumnPos = this.start), this.lastColumnValue } indentation() { return this.overrideIndent ?? countCol(this.string, null, this.tabSize) } match(pattern, consume, caseInsensitive) { if (typeof pattern == "string") { let cased = str => caseInsensitive ? str.toLowerCase() : str, substr = this.string.substr(this.pos, pattern.length); return cased(substr) == cased(pattern) ? (consume !== !1 && (this.pos += pattern.length), !0) : null } else { let match = this.string.slice(this.pos).match(pattern); return match && match.index > 0 ? null : (match && consume !== !1 && (this.pos += match[0].length), match) } } current() { return this.string.slice(this.start, this.pos) } }; function fullParser(spec) { return { name: spec.name || "", token: spec.token, blankLine: spec.blankLine || (() => { }), startState: spec.startState || (() => !0), copyState: spec.copyState || defaultCopyState, indent: spec.indent || (() => null), languageData: spec.languageData || {}, tokenTable: spec.tokenTable || noTokens, mergeTokens: spec.mergeTokens !== !1 } } function defaultCopyState(state) { if (typeof state != "object") return state; let newState = {}; for (let prop in state) { let val = state[prop]; newState[prop] = val instanceof Array ? val.slice() : val } return newState } var IndentedFrom = new WeakMap, StreamLanguage = class _StreamLanguage extends Language { streamParser; stateAfter; tokenTable; topNode; constructor(parser) { let data = defineLanguageFacet(parser.languageData), p = fullParser(parser), self, impl = new class extends Parser { createParse(input, fragments, ranges) { return new Parse(self, input, fragments, ranges) } }; super(data, impl, [], parser.name), this.topNode = docID(data, this), self = this, this.streamParser = p, this.stateAfter = new NodeProp({ perNode: !0 }), this.tokenTable = parser.tokenTable ? new TokenTable(p.tokenTable) : defaultTokenTable } static define(spec) { return new _StreamLanguage(spec) } getIndent(cx) { let from, { overrideIndentation } = cx.options; overrideIndentation && (from = IndentedFrom.get(cx.state), from != null && from < cx.pos - 1e4 && (from = void 0)); let start = findState(this, cx.node.tree, cx.node.from, cx.node.from, from ?? cx.pos), statePos, state; if (start ? (state = start.state, statePos = start.pos + 1) : (state = this.streamParser.startState(cx.unit), statePos = cx.node.from), cx.pos - statePos > 1e4) return null; for (; statePos < cx.pos;) { let line2 = cx.state.doc.lineAt(statePos), end = Math.min(cx.pos, line2.to); if (line2.length) { let indentation = overrideIndentation ? overrideIndentation(line2.from) : -1, stream = new StringStream(line2.text, cx.state.tabSize, cx.unit, indentation < 0 ? void 0 : indentation); for (; stream.pos < end - line2.from;)readToken(this.streamParser.token, stream, state) } else this.streamParser.blankLine(state, cx.unit); if (end == cx.pos) break; statePos = line2.to + 1 } let line = cx.lineAt(cx.pos); return overrideIndentation && from == null && IndentedFrom.set(cx.state, line.from), this.streamParser.indent(state, /^\s*(.*)/.exec(line.text)[1], cx) } get allowsNesting() { return !1 } }; function findState(lang, tree, off, startPos, before) { let state = off >= startPos && off + tree.length <= before && tree.prop(lang.stateAfter); if (state) return { state: lang.streamParser.copyState(state), pos: off + tree.length }; for (let i2 = tree.children.length - 1; i2 >= 0; i2--) { let child = tree.children[i2], pos = off + tree.positions[i2], found = child instanceof Tree && pos < before && findState(lang, child, pos, startPos, before); if (found) return found } return null } function cutTree(lang, tree, from, to, inside) { if (inside && from <= 0 && to >= tree.length) return tree; !inside && from == 0 && tree.type == lang.topNode && (inside = !0); for (let i2 = tree.children.length - 1; i2 >= 0; i2--) { let pos = tree.positions[i2], child = tree.children[i2], inner; if (pos < to && child instanceof Tree) { if (!(inner = cutTree(lang, child, from - pos, to - pos, inside))) break; return inside ? new Tree(tree.type, tree.children.slice(0, i2).concat(inner), tree.positions.slice(0, i2 + 1), pos + inner.length) : inner } } return null } function findStartInFragments(lang, fragments, startPos, endPos, editorState) { for (let f of fragments) { let from = f.from + (f.openStart ? 25 : 0), to = f.to - (f.openEnd ? 25 : 0), found = from <= startPos && to > startPos && findState(lang, f.tree, 0 - f.offset, startPos, to), tree; if (found && found.pos <= endPos && (tree = cutTree(lang, f.tree, startPos + f.offset, found.pos + f.offset, !1))) return { state: found.state, tree } } return { state: lang.streamParser.startState(editorState ? getIndentUnit(editorState) : 4), tree: Tree.empty } } var Parse = class { + constructor(lang, input, fragments, ranges) { this.lang = lang; this.input = input; this.fragments = fragments; this.ranges = ranges; this.to = ranges[ranges.length - 1].to; let context = ParseContext.get(), from = ranges[0].from, { state, tree } = findStartInFragments(lang, fragments, from, this.to, context?.state); this.state = state, this.parsedPos = this.chunkStart = from + tree.length; for (let i2 = 0; i2 < tree.children.length; i2++)this.chunks.push(tree.children[i2]), this.chunkPos.push(tree.positions[i2]); context && this.parsedPos < context.viewport.from - 1e5 && ranges.some(r => r.from <= context.viewport.from && r.to >= context.viewport.from) && (this.state = this.lang.streamParser.startState(getIndentUnit(context.state)), context.skipUntilInView(this.parsedPos, context.viewport.from), this.parsedPos = context.viewport.from), this.moveRangeIndex() } lang; input; fragments; ranges; state; parsedPos; stoppedAt = null; chunks = []; chunkPos = []; chunkStart; chunk = []; chunkReused = void 0; rangeIndex = 0; to; advance() { let context = ParseContext.get(), parseEnd = this.stoppedAt == null ? this.to : Math.min(this.to, this.stoppedAt), end = Math.min(parseEnd, this.chunkStart + 512); for (context && (end = Math.min(end, context.viewport.to)); this.parsedPos < end;)this.parseLine(context); return this.chunkStart < this.parsedPos && this.finishChunk(), this.parsedPos >= parseEnd ? this.finish() : context && this.parsedPos >= context.viewport.to ? (context.skipUntilInView(this.parsedPos, parseEnd), this.finish()) : null } stopAt(pos) { this.stoppedAt = pos } lineAfter(pos) { + let chunk = this.input.chunk(pos); if (this.input.lineChunks) chunk == ` +`&& (chunk = ""); else { + let eol = chunk.indexOf(` +`); eol > -1 && (chunk = chunk.slice(0, eol)) + } return pos + chunk.length <= this.to ? chunk : chunk.slice(0, this.to - pos) + } nextLine() { let from = this.parsedPos, line = this.lineAfter(from), end = from + line.length; for (let index = this.rangeIndex; ;) { let rangeEnd2 = this.ranges[index].to; if (rangeEnd2 >= end || (line = line.slice(0, rangeEnd2 - (end - line.length)), index++, index == this.ranges.length)) break; let rangeStart = this.ranges[index].from, after = this.lineAfter(rangeStart); line += after, end = rangeStart + after.length } return { line, end } } skipGapsTo(pos, offset, side) { for (; ;) { let end = this.ranges[this.rangeIndex].to, offPos = pos + offset; if (side > 0 ? end > offPos : end >= offPos) break; let start = this.ranges[++this.rangeIndex].from; offset += start - end } return offset } moveRangeIndex() { for (; this.ranges[this.rangeIndex].to < this.parsedPos;)this.rangeIndex++ } emitToken(id, from, to, offset) { let size = 4; if (this.ranges.length > 1) { offset = this.skipGapsTo(from, offset, 1), from += offset; let len0 = this.chunk.length; offset = this.skipGapsTo(to, offset, -1), to += offset, size += this.chunk.length - len0 } let last = this.chunk.length - 4; return this.lang.streamParser.mergeTokens && size == 4 && last >= 0 && this.chunk[last] == id && this.chunk[last + 2] == from ? this.chunk[last + 2] = to : this.chunk.push(id, from, to, size), offset } parseLine(context) { let { line, end } = this.nextLine(), offset = 0, { streamParser } = this.lang, stream = new StringStream(line, context ? context.state.tabSize : 4, context ? getIndentUnit(context.state) : 2); if (stream.eol()) streamParser.blankLine(this.state, stream.indentUnit); else for (; !stream.eol();) { let token = readToken(streamParser.token, stream, this.state); if (token && (offset = this.emitToken(this.lang.tokenTable.resolve(token), this.parsedPos + stream.start, this.parsedPos + stream.pos, offset)), stream.start > 1e4) break } this.parsedPos = end, this.moveRangeIndex(), this.parsedPos < this.to && this.parsedPos++ } finishChunk() { let tree = Tree.build({ buffer: this.chunk, start: this.chunkStart, length: this.parsedPos - this.chunkStart, nodeSet, topID: 0, maxBufferLength: 512, reused: this.chunkReused }); tree = new Tree(tree.type, tree.children, tree.positions, tree.length, [[this.lang.stateAfter, this.lang.streamParser.copyState(this.state)]]), this.chunks.push(tree), this.chunkPos.push(this.chunkStart - this.ranges[0].from), this.chunk = [], this.chunkReused = void 0, this.chunkStart = this.parsedPos } finish() { return new Tree(this.lang.topNode, this.chunks, this.chunkPos, this.parsedPos - this.ranges[0].from).balance() } +}; function readToken(token, stream, state) { stream.start = stream.pos; for (let i2 = 0; i2 < 10; i2++) { let result = token(stream, state); if (stream.pos > stream.start) return result } throw new Error("Stream parser failed to advance stream.") } var noTokens = Object.create(null), typeArray = [NodeType.none], nodeSet = new NodeSet(typeArray), warned = [], byTag = Object.create(null), defaultTable = Object.create(null); for (let [legacyName, name2] of [["variable", "variableName"], ["variable-2", "variableName.special"], ["string-2", "string.special"], ["def", "variableName.definition"], ["tag", "tagName"], ["attribute", "attributeName"], ["type", "typeName"], ["builtin", "variableName.standard"], ["qualifier", "modifier"], ["error", "invalid"], ["header", "heading"], ["property", "propertyName"]]) defaultTable[legacyName] = createTokenType(noTokens, name2); var TokenTable = class { constructor(extra) { this.extra = extra } extra; table = Object.assign(Object.create(null), defaultTable); resolve(tag) { return tag ? this.table[tag] || (this.table[tag] = createTokenType(this.extra, tag)) : 0 } }, defaultTokenTable = new TokenTable(noTokens); function warnForPart(part, msg) { warned.indexOf(part) > -1 || (warned.push(part), console.warn(msg)) } function createTokenType(extra, tagStr) { let tags2 = []; for (let name3 of tagStr.split(" ")) { let found = []; for (let part of name3.split(".")) { let value = extra[part] || tags[part]; value ? typeof value == "function" ? found.length ? found = found.map(value) : warnForPart(part, `Modifier ${part} used at start of tag`) : found.length ? warnForPart(part, `Tag ${part} used as modifier`) : found = Array.isArray(value) ? value : [value] : warnForPart(part, `Unknown highlighting tag ${part}`) } for (let tag of found) tags2.push(tag) } if (!tags2.length) return 0; let name2 = tagStr.replace(/ /g, "_"), key = name2 + " " + tags2.map(t2 => t2.id), known = byTag[key]; if (known) return known.id; let type = byTag[key] = NodeType.define({ id: typeArray.length, name: name2, props: [styleTags({ [name2]: tags2 })] }); return typeArray.push(type), type.id } function docID(data, lang) { let type = NodeType.define({ id: typeArray.length, name: "Document", props: [languageDataProp.add(() => data), indentNodeProp.add(() => cx => lang.getIndent(cx))], top: !0 }); return typeArray.push(type), type } var toggleComment = target => { let { state } = target, line = state.doc.lineAt(state.selection.main.from), config = getConfig(target.state, line.from); return config.line ? toggleLineComment(target) : config.block ? toggleBlockCommentByLine(target) : !1 }; function command(f, option) { return ({ state, dispatch }) => { if (state.readOnly) return !1; let tr = f(option, state); return tr ? (dispatch(state.update(tr)), !0) : !1 } } var toggleLineComment = command(changeLineComment, 0), lineComment = command(changeLineComment, 1), lineUncomment = command(changeLineComment, 2), toggleBlockComment = command(changeBlockComment, 0), blockComment = command(changeBlockComment, 1), blockUncomment = command(changeBlockComment, 2), toggleBlockCommentByLine = command((o, s) => changeBlockComment(o, s, selectedLineRanges(s)), 0); function getConfig(state, pos) { let data = state.languageDataAt("commentTokens", pos, 1); return data.length ? data[0] : {} } var SearchMargin = 50; function findBlockComment(state, { open, close }, from, to) { let textBefore = state.sliceDoc(from - SearchMargin, from), textAfter = state.sliceDoc(to, to + SearchMargin), spaceBefore = /\s*$/.exec(textBefore)[0].length, spaceAfter = /^\s*/.exec(textAfter)[0].length, beforeOff = textBefore.length - spaceBefore; if (textBefore.slice(beforeOff - open.length, beforeOff) == open && textAfter.slice(spaceAfter, spaceAfter + close.length) == close) return { open: { pos: from - spaceBefore, margin: spaceBefore && 1 }, close: { pos: to + spaceAfter, margin: spaceAfter && 1 } }; let startText, endText; to - from <= 2 * SearchMargin ? startText = endText = state.sliceDoc(from, to) : (startText = state.sliceDoc(from, from + SearchMargin), endText = state.sliceDoc(to - SearchMargin, to)); let startSpace = /^\s*/.exec(startText)[0].length, endSpace = /\s*$/.exec(endText)[0].length, endOff = endText.length - endSpace - close.length; return startText.slice(startSpace, startSpace + open.length) == open && endText.slice(endOff, endOff + close.length) == close ? { open: { pos: from + startSpace + open.length, margin: /\s/.test(startText.charAt(startSpace + open.length)) ? 1 : 0 }, close: { pos: to - endSpace - close.length, margin: /\s/.test(endText.charAt(endOff - 1)) ? 1 : 0 } } : null } function selectedLineRanges(state) { let ranges = []; for (let r of state.selection.ranges) { let fromLine = state.doc.lineAt(r.from), toLine = r.to <= fromLine.to ? fromLine : state.doc.lineAt(r.to); toLine.from > fromLine.from && toLine.from == r.to && (toLine = r.to == fromLine.to + 1 ? fromLine : state.doc.lineAt(r.to - 1)); let last = ranges.length - 1; last >= 0 && ranges[last].to > fromLine.from ? ranges[last].to = toLine.to : ranges.push({ from: fromLine.from + /^\s*/.exec(fromLine.text)[0].length, to: toLine.to }) } return ranges } function changeBlockComment(option, state, ranges = state.selection.ranges) { let tokens = ranges.map(r => getConfig(state, r.from).block); if (!tokens.every(c => c)) return null; let comments = ranges.map((r, i2) => findBlockComment(state, tokens[i2], r.from, r.to)); if (option != 2 && !comments.every(c => c)) return { changes: state.changes(ranges.map((range, i2) => comments[i2] ? [] : [{ from: range.from, insert: tokens[i2].open + " " }, { from: range.to, insert: " " + tokens[i2].close }])) }; if (option != 1 && comments.some(c => c)) { let changes = []; for (let i2 = 0, comment2; i2 < comments.length; i2++)if (comment2 = comments[i2]) { let token = tokens[i2], { open, close } = comment2; changes.push({ from: open.pos - token.open.length, to: open.pos + open.margin }, { from: close.pos - close.margin, to: close.pos + token.close.length }) } return { changes } } return null } function changeLineComment(option, state, ranges = state.selection.ranges) { let lines = [], prevLine = -1; ranges: for (let { from, to } of ranges) { let startI = lines.length, minIndent = 1e9, token; for (let pos = from; pos <= to;) { let line = state.doc.lineAt(pos); if (token == null && (token = getConfig(state, line.from).line, !token)) continue ranges; if (line.from > prevLine && (from == to || to > line.from)) { prevLine = line.from; let indent = /^\s*/.exec(line.text)[0].length, empty2 = indent == line.length, comment2 = line.text.slice(indent, indent + token.length) == token ? indent : -1; indent < line.text.length && indent < minIndent && (minIndent = indent), lines.push({ line, comment: comment2, token, indent, empty: empty2, single: !1 }) } pos = line.to + 1 } if (minIndent < 1e9) for (let i2 = startI; i2 < lines.length; i2++)lines[i2].indent < lines[i2].line.text.length && (lines[i2].indent = minIndent); lines.length == startI + 1 && (lines[startI].single = !0) } if (option != 2 && lines.some(l => l.comment < 0 && (!l.empty || l.single))) { let changes = []; for (let { line, token, indent, empty: empty2, single } of lines) (single || !empty2) && changes.push({ from: line.from + indent, insert: token + " " }); let changeSet = state.changes(changes); return { changes: changeSet, selection: state.selection.map(changeSet, 1) } } else if (option != 1 && lines.some(l => l.comment >= 0)) { let changes = []; for (let { line, comment: comment2, token } of lines) if (comment2 >= 0) { let from = line.from + comment2, to = from + token.length; line.text[to - line.from] == " " && to++, changes.push({ from, to }) } return { changes } } return null } var fromHistory = Annotation.define(), isolateHistory = Annotation.define(), invertedEffects = Facet.define(), historyConfig = Facet.define({ combine(configs) { return combineConfig(configs, { minDepth: 100, newGroupDelay: 500, joinToEvent: (_t, isAdjacent2) => isAdjacent2 }, { minDepth: Math.max, newGroupDelay: Math.min, joinToEvent: (a, b) => (tr, adj) => a(tr, adj) || b(tr, adj) }) } }), historyField_ = StateField.define({ create() { return HistoryState.empty }, update(state, tr) { let config = tr.state.facet(historyConfig), fromHist = tr.annotation(fromHistory); if (fromHist) { let item = HistEvent.fromTransaction(tr, fromHist.selection), from = fromHist.side, other = from == 0 ? state.undone : state.done; return item ? other = updateBranch(other, other.length, config.minDepth, item) : other = addSelection(other, tr.startState.selection), new HistoryState(from == 0 ? fromHist.rest : other, from == 0 ? other : fromHist.rest) } let isolate = tr.annotation(isolateHistory); if ((isolate == "full" || isolate == "before") && (state = state.isolate()), tr.annotation(Transaction.addToHistory) === !1) return tr.changes.empty ? state : state.addMapping(tr.changes.desc); let event = HistEvent.fromTransaction(tr), time = tr.annotation(Transaction.time), userEvent = tr.annotation(Transaction.userEvent); return event ? state = state.addChanges(event, time, userEvent, config, tr) : tr.selection && (state = state.addSelection(tr.startState.selection, time, userEvent, config.newGroupDelay)), (isolate == "full" || isolate == "after") && (state = state.isolate()), state }, toJSON(value) { return { done: value.done.map(e => e.toJSON()), undone: value.undone.map(e => e.toJSON()) } }, fromJSON(json) { return new HistoryState(json.done.map(HistEvent.fromJSON), json.undone.map(HistEvent.fromJSON)) } }); function history(config = {}) { return [historyField_, historyConfig.of(config), EditorView.domEventHandlers({ beforeinput(e, view) { let command2 = e.inputType == "historyUndo" ? undo : e.inputType == "historyRedo" ? redo : null; return command2 ? (e.preventDefault(), command2(view)) : !1 } })] } function cmd(side, selection) { return function ({ state, dispatch }) { if (!selection && state.readOnly) return !1; let historyState = state.field(historyField_, !1); if (!historyState) return !1; let tr = historyState.pop(side, state, selection); return tr ? (dispatch(tr), !0) : !1 } } var undo = cmd(0, !1), redo = cmd(1, !1), undoSelection = cmd(0, !0), redoSelection = cmd(1, !0); function depth(side) { return function (state) { let histState = state.field(historyField_, !1); if (!histState) return 0; let branch = side == 0 ? histState.done : histState.undone; return branch.length - (branch.length && !branch[0].changes ? 1 : 0) } } var undoDepth = depth(0), redoDepth = depth(1), HistEvent = class _HistEvent { constructor(changes, effects, mapped, startSelection, selectionsAfter) { this.changes = changes; this.effects = effects; this.mapped = mapped; this.startSelection = startSelection; this.selectionsAfter = selectionsAfter } changes; effects; mapped; startSelection; selectionsAfter; setSelAfter(after) { return new _HistEvent(this.changes, this.effects, this.mapped, this.startSelection, after) } toJSON() { return { changes: this.changes?.toJSON(), mapped: this.mapped?.toJSON(), startSelection: this.startSelection?.toJSON(), selectionsAfter: this.selectionsAfter.map(s => s.toJSON()) } } static fromJSON(json) { return new _HistEvent(json.changes && ChangeSet.fromJSON(json.changes), [], json.mapped && ChangeDesc.fromJSON(json.mapped), json.startSelection && EditorSelection.fromJSON(json.startSelection), json.selectionsAfter.map(EditorSelection.fromJSON)) } static fromTransaction(tr, selection) { let effects = none2; for (let invert of tr.startState.facet(invertedEffects)) { let result = invert(tr); result.length && (effects = effects.concat(result)) } return !effects.length && tr.changes.empty ? null : new _HistEvent(tr.changes.invert(tr.startState.doc), effects, void 0, selection || tr.startState.selection, none2) } static selection(selections) { return new _HistEvent(void 0, none2, void 0, void 0, selections) } }; function updateBranch(branch, to, maxLen, newEvent) { let start = to + 1 > maxLen + 20 ? to - maxLen - 1 : 0, newBranch = branch.slice(start, to); return newBranch.push(newEvent), newBranch } function isAdjacent(a, b) { let ranges = [], isAdjacent2 = !1; return a.iterChangedRanges((f, t2) => ranges.push(f, t2)), b.iterChangedRanges((_f, _t, f, t2) => { for (let i2 = 0; i2 < ranges.length;) { let from = ranges[i2++], to = ranges[i2++]; t2 >= from && f <= to && (isAdjacent2 = !0) } }), isAdjacent2 } function eqSelectionShape(a, b) { return a.ranges.length == b.ranges.length && a.ranges.filter((r, i2) => r.empty != b.ranges[i2].empty).length === 0 } function conc(a, b) { return a.length ? b.length ? a.concat(b) : a : b } var none2 = [], MaxSelectionsPerEvent = 200; function addSelection(branch, selection) { if (branch.length) { let lastEvent = branch[branch.length - 1], sels = lastEvent.selectionsAfter.slice(Math.max(0, lastEvent.selectionsAfter.length - MaxSelectionsPerEvent)); return sels.length && sels[sels.length - 1].eq(selection) ? branch : (sels.push(selection), updateBranch(branch, branch.length - 1, 1e9, lastEvent.setSelAfter(sels))) } else return [HistEvent.selection([selection])] } function popSelection(branch) { let last = branch[branch.length - 1], newBranch = branch.slice(); return newBranch[branch.length - 1] = last.setSelAfter(last.selectionsAfter.slice(0, last.selectionsAfter.length - 1)), newBranch } function addMappingToBranch(branch, mapping) { if (!branch.length) return branch; let length = branch.length, selections = none2; for (; length;) { let event = mapEvent(branch[length - 1], mapping, selections); if (event.changes && !event.changes.empty || event.effects.length) { let result = branch.slice(0, length); return result[length - 1] = event, result } else mapping = event.mapped, length--, selections = event.selectionsAfter } return selections.length ? [HistEvent.selection(selections)] : none2 } function mapEvent(event, mapping, extraSelections) { let selections = conc(event.selectionsAfter.length ? event.selectionsAfter.map(s => s.map(mapping)) : none2, extraSelections); if (!event.changes) return HistEvent.selection(selections); let mappedChanges = event.changes.map(mapping), before = mapping.mapDesc(event.changes, !0), fullMapping = event.mapped ? event.mapped.composeDesc(before) : before; return new HistEvent(mappedChanges, StateEffect.mapEffects(event.effects, mapping), fullMapping, event.startSelection.map(before), selections) } var joinableUserEvent = /^(input\.type|delete)($|\.)/, HistoryState = class _HistoryState { constructor(done, undone, prevTime = 0, prevUserEvent = void 0) { this.done = done; this.undone = undone; this.prevTime = prevTime; this.prevUserEvent = prevUserEvent } done; undone; prevTime; prevUserEvent; isolate() { return this.prevTime ? new _HistoryState(this.done, this.undone) : this } addChanges(event, time, userEvent, config, tr) { let done = this.done, lastEvent = done[done.length - 1]; return lastEvent && lastEvent.changes && !lastEvent.changes.empty && event.changes && (!userEvent || joinableUserEvent.test(userEvent)) && (!lastEvent.selectionsAfter.length && time - this.prevTime < config.newGroupDelay && config.joinToEvent(tr, isAdjacent(lastEvent.changes, event.changes)) || userEvent == "input.type.compose") ? done = updateBranch(done, done.length - 1, config.minDepth, new HistEvent(event.changes.compose(lastEvent.changes), conc(StateEffect.mapEffects(event.effects, lastEvent.changes), lastEvent.effects), lastEvent.mapped, lastEvent.startSelection, none2)) : done = updateBranch(done, done.length, config.minDepth, event), new _HistoryState(done, none2, time, userEvent) } addSelection(selection, time, userEvent, newGroupDelay) { let last = this.done.length ? this.done[this.done.length - 1].selectionsAfter : none2; return last.length > 0 && time - this.prevTime < newGroupDelay && userEvent == this.prevUserEvent && userEvent && /^select($|\.)/.test(userEvent) && eqSelectionShape(last[last.length - 1], selection) ? this : new _HistoryState(addSelection(this.done, selection), this.undone, time, userEvent) } addMapping(mapping) { return new _HistoryState(addMappingToBranch(this.done, mapping), addMappingToBranch(this.undone, mapping), this.prevTime, this.prevUserEvent) } pop(side, state, onlySelection) { let branch = side == 0 ? this.done : this.undone; if (branch.length == 0) return null; let event = branch[branch.length - 1], selection = event.selectionsAfter[0] || (event.startSelection ? event.startSelection.map(event.changes.invertedDesc, 1) : state.selection); if (onlySelection && event.selectionsAfter.length) return state.update({ selection: event.selectionsAfter[event.selectionsAfter.length - 1], annotations: fromHistory.of({ side, rest: popSelection(branch), selection }), userEvent: side == 0 ? "select.undo" : "select.redo", scrollIntoView: !0 }); if (event.changes) { let rest = branch.length == 1 ? none2 : branch.slice(0, branch.length - 1); return event.mapped && (rest = addMappingToBranch(rest, event.mapped)), state.update({ changes: event.changes, selection: event.startSelection, effects: event.effects, annotations: fromHistory.of({ side, rest, selection }), filter: !1, userEvent: side == 0 ? "undo" : "redo", scrollIntoView: !0 }) } else return null } static empty = new _HistoryState(none2, none2) }, historyKeymap = [{ key: "Mod-z", run: undo, preventDefault: !0 }, { key: "Mod-y", mac: "Mod-Shift-z", run: redo, preventDefault: !0 }, { linux: "Ctrl-Shift-z", run: redo, preventDefault: !0 }, { key: "Mod-u", run: undoSelection, preventDefault: !0 }, { key: "Alt-u", mac: "Mod-Shift-u", run: redoSelection, preventDefault: !0 }]; function updateSel(sel, by) { return EditorSelection.create(sel.ranges.map(by), sel.mainIndex) } function setSel(state, selection) { return state.update({ selection, scrollIntoView: !0, userEvent: "select" }) } function moveSel({ state, dispatch }, how) { let selection = updateSel(state.selection, how); return selection.eq(state.selection, !0) ? !1 : (dispatch(setSel(state, selection)), !0) } function rangeEnd(range, forward) { return EditorSelection.cursor(forward ? range.to : range.from) } function cursorByChar(view, forward) { return moveSel(view, range => range.empty ? view.moveByChar(range, forward) : rangeEnd(range, forward)) } function ltrAtCursor(view) { return view.textDirectionAt(view.state.selection.main.head) == 0 } var cursorCharLeft = view => cursorByChar(view, !ltrAtCursor(view)), cursorCharRight = view => cursorByChar(view, ltrAtCursor(view)); function cursorByGroup(view, forward) { return moveSel(view, range => range.empty ? view.moveByGroup(range, forward) : rangeEnd(range, forward)) } var cursorGroupLeft = view => cursorByGroup(view, !ltrAtCursor(view)), cursorGroupRight = view => cursorByGroup(view, ltrAtCursor(view)); var segmenter = typeof Intl < "u" && Intl.Segmenter ? new Intl.Segmenter(void 0, { granularity: "word" }) : null; function interestingNode(state, node, bracketProp) { if (node.type.prop(bracketProp)) return !0; let len = node.to - node.from; return len && (len > 2 || /[^\s,.;:]/.test(state.sliceDoc(node.from, node.to))) || node.firstChild } function moveBySyntax(state, start, forward) { let pos = syntaxTree(state).resolveInner(start.head), bracketProp = forward ? NodeProp.closedBy : NodeProp.openedBy; for (let at = start.head; ;) { let next = forward ? pos.childAfter(at) : pos.childBefore(at); if (!next) break; interestingNode(state, next, bracketProp) ? pos = next : at = forward ? next.to : next.from } let bracket2 = pos.type.prop(bracketProp), match, newPos; return bracket2 && (match = forward ? matchBrackets(state, pos.from, 1) : matchBrackets(state, pos.to, -1)) && match.matched ? newPos = forward ? match.end.to : match.end.from : newPos = forward ? pos.to : pos.from, EditorSelection.cursor(newPos, forward ? -1 : 1) } var cursorSyntaxLeft = view => moveSel(view, range => moveBySyntax(view.state, range, !ltrAtCursor(view))), cursorSyntaxRight = view => moveSel(view, range => moveBySyntax(view.state, range, ltrAtCursor(view))); function cursorByLine(view, forward) { return moveSel(view, range => { if (!range.empty) return rangeEnd(range, forward); let moved = view.moveVertically(range, forward); return moved.head != range.head ? moved : view.moveToLineBoundary(range, forward) }) } var cursorLineUp = view => cursorByLine(view, !1), cursorLineDown = view => cursorByLine(view, !0); function pageInfo(view) { let selfScroll = view.scrollDOM.clientHeight < view.scrollDOM.scrollHeight - 2, marginTop = 0, marginBottom = 0, height; if (selfScroll) { for (let source of view.state.facet(EditorView.scrollMargins)) { let margins = source(view); margins?.top && (marginTop = Math.max(margins?.top, marginTop)), margins?.bottom && (marginBottom = Math.max(margins?.bottom, marginBottom)) } height = view.scrollDOM.clientHeight - marginTop - marginBottom } else height = (view.dom.ownerDocument.defaultView || window).innerHeight; return { marginTop, marginBottom, selfScroll, height: Math.max(view.defaultLineHeight, height - 5) } } function cursorByPage(view, forward) { let page = pageInfo(view), { state } = view, selection = updateSel(state.selection, range => range.empty ? view.moveVertically(range, forward, page.height) : rangeEnd(range, forward)); if (selection.eq(state.selection)) return !1; let effect; if (page.selfScroll) { let startPos = view.coordsAtPos(state.selection.main.head), scrollRect = view.scrollDOM.getBoundingClientRect(), scrollTop = scrollRect.top + page.marginTop, scrollBottom = scrollRect.bottom - page.marginBottom; startPos && startPos.top > scrollTop && startPos.bottom < scrollBottom && (effect = EditorView.scrollIntoView(selection.main.head, { y: "start", yMargin: startPos.top - scrollTop })) } return view.dispatch(setSel(state, selection), { effects: effect }), !0 } var cursorPageUp = view => cursorByPage(view, !1), cursorPageDown = view => cursorByPage(view, !0); function moveByLineBoundary(view, start, forward) { let line = view.lineBlockAt(start.head), moved = view.moveToLineBoundary(start, forward); if (moved.head == start.head && moved.head != (forward ? line.to : line.from) && (moved = view.moveToLineBoundary(start, forward, !1)), !forward && moved.head == line.from && line.length) { let space = /^\s*/.exec(view.state.sliceDoc(line.from, Math.min(line.from + 100, line.to)))[0].length; space && start.head != line.from + space && (moved = EditorSelection.cursor(line.from + space)) } return moved } var cursorLineBoundaryForward = view => moveSel(view, range => moveByLineBoundary(view, range, !0)), cursorLineBoundaryBackward = view => moveSel(view, range => moveByLineBoundary(view, range, !1)), cursorLineBoundaryLeft = view => moveSel(view, range => moveByLineBoundary(view, range, !ltrAtCursor(view))), cursorLineBoundaryRight = view => moveSel(view, range => moveByLineBoundary(view, range, ltrAtCursor(view))), cursorLineStart = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from, 1)), cursorLineEnd = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to, -1)); function toMatchingBracket(state, dispatch, extend) { let found = !1, selection = updateSel(state.selection, range => { let matching = matchBrackets(state, range.head, -1) || matchBrackets(state, range.head, 1) || range.head > 0 && matchBrackets(state, range.head - 1, 1) || range.head < state.doc.length && matchBrackets(state, range.head + 1, -1); if (!matching || !matching.end) return range; found = !0; let head = matching.start.from == range.head ? matching.end.to : matching.end.from; return extend ? EditorSelection.range(range.anchor, head) : EditorSelection.cursor(head) }); return found ? (dispatch(setSel(state, selection)), !0) : !1 } var cursorMatchingBracket = ({ state, dispatch }) => toMatchingBracket(state, dispatch, !1); function extendSel(target, how) { let selection = updateSel(target.state.selection, range => { let head = how(range); return EditorSelection.range(range.anchor, head.head, head.goalColumn, head.bidiLevel || void 0, head.assoc) }); return selection.eq(target.state.selection) ? !1 : (target.dispatch(setSel(target.state, selection)), !0) } function selectByChar(view, forward) { return extendSel(view, range => view.moveByChar(range, forward)) } var selectCharLeft = view => selectByChar(view, !ltrAtCursor(view)), selectCharRight = view => selectByChar(view, ltrAtCursor(view)); function selectByGroup(view, forward) { return extendSel(view, range => view.moveByGroup(range, forward)) } var selectGroupLeft = view => selectByGroup(view, !ltrAtCursor(view)), selectGroupRight = view => selectByGroup(view, ltrAtCursor(view)); var selectSyntaxLeft = view => extendSel(view, range => moveBySyntax(view.state, range, !ltrAtCursor(view))), selectSyntaxRight = view => extendSel(view, range => moveBySyntax(view.state, range, ltrAtCursor(view))); function selectByLine(view, forward) { return extendSel(view, range => view.moveVertically(range, forward)) } var selectLineUp = view => selectByLine(view, !1), selectLineDown = view => selectByLine(view, !0); function selectByPage(view, forward) { return extendSel(view, range => view.moveVertically(range, forward, pageInfo(view).height)) } var selectPageUp = view => selectByPage(view, !1), selectPageDown = view => selectByPage(view, !0), selectLineBoundaryForward = view => extendSel(view, range => moveByLineBoundary(view, range, !0)), selectLineBoundaryBackward = view => extendSel(view, range => moveByLineBoundary(view, range, !1)), selectLineBoundaryLeft = view => extendSel(view, range => moveByLineBoundary(view, range, !ltrAtCursor(view))), selectLineBoundaryRight = view => extendSel(view, range => moveByLineBoundary(view, range, ltrAtCursor(view))), selectLineStart = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from)), selectLineEnd = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to)), cursorDocStart = ({ state, dispatch }) => (dispatch(setSel(state, { anchor: 0 })), !0), cursorDocEnd = ({ state, dispatch }) => (dispatch(setSel(state, { anchor: state.doc.length })), !0), selectDocStart = ({ state, dispatch }) => (dispatch(setSel(state, { anchor: state.selection.main.anchor, head: 0 })), !0), selectDocEnd = ({ state, dispatch }) => (dispatch(setSel(state, { anchor: state.selection.main.anchor, head: state.doc.length })), !0), selectAll = ({ state, dispatch }) => (dispatch(state.update({ selection: { anchor: 0, head: state.doc.length }, userEvent: "select" })), !0), selectLine = ({ state, dispatch }) => { let ranges = selectedLineBlocks(state).map(({ from, to }) => EditorSelection.range(from, Math.min(to + 1, state.doc.length))); return dispatch(state.update({ selection: EditorSelection.create(ranges), userEvent: "select" })), !0 }, selectParentSyntax = ({ state, dispatch }) => { let selection = updateSel(state.selection, range => { let tree = syntaxTree(state), stack = tree.resolveStack(range.from, 1); if (range.empty) { let stackBefore = tree.resolveStack(range.from, -1); stackBefore.node.from >= stack.node.from && stackBefore.node.to <= stack.node.to && (stack = stackBefore) } for (let cur = stack; cur; cur = cur.next) { let { node } = cur; if ((node.from < range.from && node.to >= range.to || node.to > range.to && node.from <= range.from) && cur.next) return EditorSelection.range(node.to, node.from) } return range }); return selection.eq(state.selection) ? !1 : (dispatch(setSel(state, selection)), !0) }; function addCursorVertically(view, forward) { let { state } = view, sel = state.selection, ranges = state.selection.ranges.slice(); for (let range of state.selection.ranges) { let line = state.doc.lineAt(range.head); if (forward ? line.to < view.state.doc.length : line.from > 0) for (let cur = range; ;) { let next = view.moveVertically(cur, forward); if (next.head < line.from || next.head > line.to) { ranges.some(r => r.head == next.head) || ranges.push(next); break } else { if (next.head == cur.head) break; cur = next } } } return ranges.length == sel.ranges.length ? !1 : (view.dispatch(setSel(state, EditorSelection.create(ranges, ranges.length - 1))), !0) } var addCursorAbove = view => addCursorVertically(view, !1), addCursorBelow = view => addCursorVertically(view, !0), simplifySelection = ({ state, dispatch }) => { let cur = state.selection, selection = null; return cur.ranges.length > 1 ? selection = EditorSelection.create([cur.main]) : cur.main.empty || (selection = EditorSelection.create([EditorSelection.cursor(cur.main.head)])), selection ? (dispatch(setSel(state, selection)), !0) : !1 }; function deleteBy(target, by) { if (target.state.readOnly) return !1; let event = "delete.selection", { state } = target, changes = state.changeByRange(range => { let { from, to } = range; if (from == to) { let towards = by(range); towards < from ? (event = "delete.backward", towards = skipAtomic(target, towards, !1)) : towards > from && (event = "delete.forward", towards = skipAtomic(target, towards, !0)), from = Math.min(from, towards), to = Math.max(to, towards) } else from = skipAtomic(target, from, !1), to = skipAtomic(target, to, !0); return from == to ? { range } : { changes: { from, to }, range: EditorSelection.cursor(from, from < range.head ? -1 : 1) } }); return changes.changes.empty ? !1 : (target.dispatch(state.update(changes, { scrollIntoView: !0, userEvent: event, effects: event == "delete.selection" ? EditorView.announce.of(state.phrase("Selection deleted")) : void 0 })), !0) } function skipAtomic(target, pos, forward) { if (target instanceof EditorView) for (let ranges of target.state.facet(EditorView.atomicRanges).map(f => f(target))) ranges.between(pos, pos, (from, to) => { from < pos && to > pos && (pos = forward ? to : from) }); return pos } var deleteByChar = (target, forward, byIndentUnit) => deleteBy(target, range => { let pos = range.from, { state } = target, line = state.doc.lineAt(pos), before, targetPos; if (byIndentUnit && !forward && pos > line.from && pos < line.from + 200 && !/[^ \t]/.test(before = line.text.slice(0, pos - line.from))) { if (before[before.length - 1] == " ") return pos - 1; let col = countColumn(before, state.tabSize), drop = col % getIndentUnit(state) || getIndentUnit(state); for (let i2 = 0; i2 < drop && before[before.length - 1 - i2] == " "; i2++)pos--; targetPos = pos } else targetPos = findClusterBreak2(line.text, pos - line.from, forward, forward) + line.from, targetPos == pos && line.number != (forward ? state.doc.lines : 1) ? targetPos += forward ? 1 : -1 : !forward && /[\ufe00-\ufe0f]/.test(line.text.slice(targetPos - line.from, pos - line.from)) && (targetPos = findClusterBreak2(line.text, targetPos - line.from, !1, !1) + line.from); return targetPos }), deleteCharBackward = view => deleteByChar(view, !1, !0); var deleteCharForward = view => deleteByChar(view, !0, !1), deleteByGroup = (target, forward) => deleteBy(target, range => { let pos = range.head, { state } = target, line = state.doc.lineAt(pos), categorize = state.charCategorizer(pos); for (let cat = null; ;) { if (pos == (forward ? line.to : line.from)) { pos == range.head && line.number != (forward ? state.doc.lines : 1) && (pos += forward ? 1 : -1); break } let next = findClusterBreak2(line.text, pos - line.from, forward) + line.from, nextChar = line.text.slice(Math.min(pos, next) - line.from, Math.max(pos, next) - line.from), nextCat = categorize(nextChar); if (cat != null && nextCat != cat) break; (nextChar != " " || pos != range.head) && (cat = nextCat), pos = next } return pos }), deleteGroupBackward = target => deleteByGroup(target, !1), deleteGroupForward = target => deleteByGroup(target, !0); var deleteToLineEnd = view => deleteBy(view, range => { let lineEnd = view.lineBlockAt(range.head).to; return range.head < lineEnd ? lineEnd : Math.min(view.state.doc.length, range.head + 1) }); var deleteLineBoundaryBackward = view => deleteBy(view, range => { let lineStart = view.moveToLineBoundary(range, !1).head; return range.head > lineStart ? lineStart : Math.max(0, range.head - 1) }), deleteLineBoundaryForward = view => deleteBy(view, range => { let lineStart = view.moveToLineBoundary(range, !0).head; return range.head < lineStart ? lineStart : Math.min(view.state.doc.length, range.head + 1) }); var splitLine = ({ state, dispatch }) => { if (state.readOnly) return !1; let changes = state.changeByRange(range => ({ changes: { from: range.from, to: range.to, insert: Text.of(["", ""]) }, range: EditorSelection.cursor(range.from) })); return dispatch(state.update(changes, { scrollIntoView: !0, userEvent: "input" })), !0 }, transposeChars = ({ state, dispatch }) => { if (state.readOnly) return !1; let changes = state.changeByRange(range => { if (!range.empty || range.from == 0 || range.from == state.doc.length) return { range }; let pos = range.from, line = state.doc.lineAt(pos), from = pos == line.from ? pos - 1 : findClusterBreak2(line.text, pos - line.from, !1) + line.from, to = pos == line.to ? pos + 1 : findClusterBreak2(line.text, pos - line.from, !0) + line.from; return { changes: { from, to, insert: state.doc.slice(pos, to).append(state.doc.slice(from, pos)) }, range: EditorSelection.cursor(to) } }); return changes.changes.empty ? !1 : (dispatch(state.update(changes, { scrollIntoView: !0, userEvent: "move.character" })), !0) }; function selectedLineBlocks(state) { let blocks = [], upto = -1; for (let range of state.selection.ranges) { let startLine = state.doc.lineAt(range.from), endLine = state.doc.lineAt(range.to); if (!range.empty && range.to == endLine.from && (endLine = state.doc.lineAt(range.to - 1)), upto >= startLine.number) { let prev = blocks[blocks.length - 1]; prev.to = endLine.to, prev.ranges.push(range) } else blocks.push({ from: startLine.from, to: endLine.to, ranges: [range] }); upto = endLine.number + 1 } return blocks } function moveLine(state, dispatch, forward) { if (state.readOnly) return !1; let changes = [], ranges = []; for (let block of selectedLineBlocks(state)) { if (forward ? block.to == state.doc.length : block.from == 0) continue; let nextLine = state.doc.lineAt(forward ? block.to + 1 : block.from - 1), size = nextLine.length + 1; if (forward) { changes.push({ from: block.to, to: nextLine.to }, { from: block.from, insert: nextLine.text + state.lineBreak }); for (let r of block.ranges) ranges.push(EditorSelection.range(Math.min(state.doc.length, r.anchor + size), Math.min(state.doc.length, r.head + size))) } else { changes.push({ from: nextLine.from, to: block.from }, { from: block.to, insert: state.lineBreak + nextLine.text }); for (let r of block.ranges) ranges.push(EditorSelection.range(r.anchor - size, r.head - size)) } } return changes.length ? (dispatch(state.update({ changes, scrollIntoView: !0, selection: EditorSelection.create(ranges, state.selection.mainIndex), userEvent: "move.line" })), !0) : !1 } var moveLineUp = ({ state, dispatch }) => moveLine(state, dispatch, !1), moveLineDown = ({ state, dispatch }) => moveLine(state, dispatch, !0); function copyLine(state, dispatch, forward) { if (state.readOnly) return !1; let changes = []; for (let block of selectedLineBlocks(state)) forward ? changes.push({ from: block.from, insert: state.doc.slice(block.from, block.to) + state.lineBreak }) : changes.push({ from: block.to, insert: state.lineBreak + state.doc.slice(block.from, block.to) }); let changeSet = state.changes(changes); return dispatch(state.update({ changes: changeSet, selection: state.selection.map(changeSet, forward ? 1 : -1), scrollIntoView: !0, userEvent: "input.copyline" })), !0 } var copyLineUp = ({ state, dispatch }) => copyLine(state, dispatch, !1), copyLineDown = ({ state, dispatch }) => copyLine(state, dispatch, !0), deleteLine = view => { if (view.state.readOnly) return !1; let { state } = view, changes = state.changes(selectedLineBlocks(state).map(({ from, to }) => (from > 0 ? from-- : to < state.doc.length && to++, { from, to }))), selection = updateSel(state.selection, range => { let dist2; if (view.lineWrapping) { let block = view.lineBlockAt(range.head), pos = view.coordsAtPos(range.head, range.assoc || 1); pos && (dist2 = block.bottom + view.documentTop - pos.bottom + view.defaultLineHeight / 2) } return view.moveVertically(range, !0, dist2) }).map(changes); return view.dispatch({ changes, selection, scrollIntoView: !0, userEvent: "delete.line" }), !0 }; function isBetweenBrackets(state, pos) { if (/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos - 1, pos + 1))) return { from: pos, to: pos }; let context = syntaxTree(state).resolveInner(pos), before = context.childBefore(pos), after = context.childAfter(pos), closedBy; return before && after && before.to <= pos && after.from >= pos && (closedBy = before.type.prop(NodeProp.closedBy)) && closedBy.indexOf(after.name) > -1 && state.doc.lineAt(before.to).from == state.doc.lineAt(after.from).from && !/\S/.test(state.sliceDoc(before.to, after.from)) ? { from: before.to, to: after.from } : null } var insertNewlineAndIndent = newlineAndIndent(!1), insertBlankLine = newlineAndIndent(!0); function newlineAndIndent(atEof) { return ({ state, dispatch }) => { if (state.readOnly) return !1; let changes = state.changeByRange(range => { let { from, to } = range, line = state.doc.lineAt(from), explode = !atEof && from == to && isBetweenBrackets(state, from); atEof && (from = to = (to <= line.to ? line : state.doc.lineAt(to)).to); let cx = new IndentContext(state, { simulateBreak: from, simulateDoubleBreak: !!explode }), indent = getIndentation(cx, from); for (indent == null && (indent = countColumn(/^\s*/.exec(state.doc.lineAt(from).text)[0], state.tabSize)); to < line.to && /\s/.test(line.text[to - line.from]);)to++; explode ? { from, to } = explode : from > line.from && from < line.from + 100 && !/\S/.test(line.text.slice(0, from)) && (from = line.from); let insert2 = ["", indentString(state, indent)]; return explode && insert2.push(indentString(state, cx.lineIndent(line.from, -1))), { changes: { from, to, insert: Text.of(insert2) }, range: EditorSelection.cursor(from + 1 + insert2[1].length) } }); return dispatch(state.update(changes, { scrollIntoView: !0, userEvent: "input" })), !0 } } function changeBySelectedLine(state, f) { let atLine = -1; return state.changeByRange(range => { let changes = []; for (let pos = range.from; pos <= range.to;) { let line = state.doc.lineAt(pos); line.number > atLine && (range.empty || range.to > line.from) && (f(line, changes, range), atLine = line.number), pos = line.to + 1 } let changeSet = state.changes(changes); return { changes, range: EditorSelection.range(changeSet.mapPos(range.anchor, 1), changeSet.mapPos(range.head, 1)) } }) } var indentSelection = ({ state, dispatch }) => { if (state.readOnly) return !1; let updated = Object.create(null), context = new IndentContext(state, { overrideIndentation: start => { let found = updated[start]; return found ?? -1 } }), changes = changeBySelectedLine(state, (line, changes2, range) => { let indent = getIndentation(context, line.from); if (indent == null) return; /\S/.test(line.text) || (indent = 0); let cur = /^\s*/.exec(line.text)[0], norm = indentString(state, indent); (cur != norm || range.from < line.from + cur.length) && (updated[line.from] = indent, changes2.push({ from: line.from, to: line.from + cur.length, insert: norm })) }); return changes.changes.empty || dispatch(state.update(changes, { userEvent: "indent" })), !0 }, indentMore = ({ state, dispatch }) => state.readOnly ? !1 : (dispatch(state.update(changeBySelectedLine(state, (line, changes) => { changes.push({ from: line.from, insert: state.facet(indentUnit) }) }), { userEvent: "input.indent" })), !0), indentLess = ({ state, dispatch }) => state.readOnly ? !1 : (dispatch(state.update(changeBySelectedLine(state, (line, changes) => { let space = /^\s*/.exec(line.text)[0]; if (!space) return; let col = countColumn(space, state.tabSize), keep = 0, insert2 = indentString(state, Math.max(0, col - getIndentUnit(state))); for (; keep < space.length && keep < insert2.length && space.charCodeAt(keep) == insert2.charCodeAt(keep);)keep++; changes.push({ from: line.from + keep, to: line.from + space.length, insert: insert2.slice(keep) }) }), { userEvent: "delete.dedent" })), !0), toggleTabFocusMode = view => (view.setTabFocusMode(), !0); var emacsStyleKeymap = [{ key: "Ctrl-b", run: cursorCharLeft, shift: selectCharLeft, preventDefault: !0 }, { key: "Ctrl-f", run: cursorCharRight, shift: selectCharRight }, { key: "Ctrl-p", run: cursorLineUp, shift: selectLineUp }, { key: "Ctrl-n", run: cursorLineDown, shift: selectLineDown }, { key: "Ctrl-a", run: cursorLineStart, shift: selectLineStart }, { key: "Ctrl-e", run: cursorLineEnd, shift: selectLineEnd }, { key: "Ctrl-d", run: deleteCharForward }, { key: "Ctrl-h", run: deleteCharBackward }, { key: "Ctrl-k", run: deleteToLineEnd }, { key: "Ctrl-Alt-h", run: deleteGroupBackward }, { key: "Ctrl-o", run: splitLine }, { key: "Ctrl-t", run: transposeChars }, { key: "Ctrl-v", run: cursorPageDown }], standardKeymap = [{ key: "ArrowLeft", run: cursorCharLeft, shift: selectCharLeft, preventDefault: !0 }, { key: "Mod-ArrowLeft", mac: "Alt-ArrowLeft", run: cursorGroupLeft, shift: selectGroupLeft, preventDefault: !0 }, { mac: "Cmd-ArrowLeft", run: cursorLineBoundaryLeft, shift: selectLineBoundaryLeft, preventDefault: !0 }, { key: "ArrowRight", run: cursorCharRight, shift: selectCharRight, preventDefault: !0 }, { key: "Mod-ArrowRight", mac: "Alt-ArrowRight", run: cursorGroupRight, shift: selectGroupRight, preventDefault: !0 }, { mac: "Cmd-ArrowRight", run: cursorLineBoundaryRight, shift: selectLineBoundaryRight, preventDefault: !0 }, { key: "ArrowUp", run: cursorLineUp, shift: selectLineUp, preventDefault: !0 }, { mac: "Cmd-ArrowUp", run: cursorDocStart, shift: selectDocStart }, { mac: "Ctrl-ArrowUp", run: cursorPageUp, shift: selectPageUp }, { key: "ArrowDown", run: cursorLineDown, shift: selectLineDown, preventDefault: !0 }, { mac: "Cmd-ArrowDown", run: cursorDocEnd, shift: selectDocEnd }, { mac: "Ctrl-ArrowDown", run: cursorPageDown, shift: selectPageDown }, { key: "PageUp", run: cursorPageUp, shift: selectPageUp }, { key: "PageDown", run: cursorPageDown, shift: selectPageDown }, { key: "Home", run: cursorLineBoundaryBackward, shift: selectLineBoundaryBackward, preventDefault: !0 }, { key: "Mod-Home", run: cursorDocStart, shift: selectDocStart }, { key: "End", run: cursorLineBoundaryForward, shift: selectLineBoundaryForward, preventDefault: !0 }, { key: "Mod-End", run: cursorDocEnd, shift: selectDocEnd }, { key: "Enter", run: insertNewlineAndIndent, shift: insertNewlineAndIndent }, { key: "Mod-a", run: selectAll }, { key: "Backspace", run: deleteCharBackward, shift: deleteCharBackward, preventDefault: !0 }, { key: "Delete", run: deleteCharForward, preventDefault: !0 }, { key: "Mod-Backspace", mac: "Alt-Backspace", run: deleteGroupBackward, preventDefault: !0 }, { key: "Mod-Delete", mac: "Alt-Delete", run: deleteGroupForward, preventDefault: !0 }, { mac: "Mod-Backspace", run: deleteLineBoundaryBackward, preventDefault: !0 }, { mac: "Mod-Delete", run: deleteLineBoundaryForward, preventDefault: !0 }].concat(emacsStyleKeymap.map(b => ({ mac: b.key, run: b.run, shift: b.shift }))), defaultKeymap = [{ key: "Alt-ArrowLeft", mac: "Ctrl-ArrowLeft", run: cursorSyntaxLeft, shift: selectSyntaxLeft }, { key: "Alt-ArrowRight", mac: "Ctrl-ArrowRight", run: cursorSyntaxRight, shift: selectSyntaxRight }, { key: "Alt-ArrowUp", run: moveLineUp }, { key: "Shift-Alt-ArrowUp", run: copyLineUp }, { key: "Alt-ArrowDown", run: moveLineDown }, { key: "Shift-Alt-ArrowDown", run: copyLineDown }, { key: "Mod-Alt-ArrowUp", run: addCursorAbove }, { key: "Mod-Alt-ArrowDown", run: addCursorBelow }, { key: "Escape", run: simplifySelection }, { key: "Mod-Enter", run: insertBlankLine }, { key: "Alt-l", mac: "Ctrl-l", run: selectLine }, { key: "Mod-i", run: selectParentSyntax, preventDefault: !0 }, { key: "Mod-[", run: indentLess }, { key: "Mod-]", run: indentMore }, { key: "Mod-Alt-\\", run: indentSelection }, { key: "Shift-Mod-k", run: deleteLine }, { key: "Shift-Mod-\\", run: cursorMatchingBracket }, { key: "Mod-/", run: toggleComment }, { key: "Alt-A", run: toggleBlockComment }, { key: "Ctrl-m", mac: "Shift-Alt-m", run: toggleTabFocusMode }].concat(standardKeymap), indentWithTab = { key: "Tab", run: indentMore, shift: indentLess }; var basicNormalize = typeof String.prototype.normalize == "function" ? x => x.normalize("NFKD") : x => x, SearchCursor = class { constructor(text, query, from = 0, to = text.length, normalize, test) { this.test = test; this.iter = text.iterRange(from, to), this.bufferStart = from, this.normalize = normalize ? x => normalize(basicNormalize(x)) : basicNormalize, this.query = this.normalize(query) } test; iter; value = { from: 0, to: 0 }; done = !1; matches = []; buffer = ""; bufferPos = 0; bufferStart; normalize; query; peek() { if (this.bufferPos == this.buffer.length) { if (this.bufferStart += this.buffer.length, this.iter.next(), this.iter.done) return -1; this.bufferPos = 0, this.buffer = this.iter.value } return codePointAt2(this.buffer, this.bufferPos) } next() { for (; this.matches.length;)this.matches.pop(); return this.nextOverlapping() } nextOverlapping() { for (; ;) { let next = this.peek(); if (next < 0) return this.done = !0, this; let str = fromCodePoint(next), start = this.bufferStart + this.bufferPos; this.bufferPos += codePointSize2(next); let norm = this.normalize(str); if (norm.length) for (let i2 = 0, pos = start; ; i2++) { let code2 = norm.charCodeAt(i2), match = this.match(code2, pos, this.bufferPos + this.bufferStart); if (i2 == norm.length - 1) { if (match) return this.value = match, this; break } pos == start && i2 < str.length && str.charCodeAt(i2) == code2 && pos++ } } } match(code2, pos, end) { let match = null; for (let i2 = 0; i2 < this.matches.length; i2 += 2) { let index = this.matches[i2], keep = !1; this.query.charCodeAt(index) == code2 && (index == this.query.length - 1 ? match = { from: this.matches[i2 + 1], to: end } : (this.matches[i2]++, keep = !0)), keep || (this.matches.splice(i2, 2), i2 -= 2) } return this.query.charCodeAt(0) == code2 && (this.query.length == 1 ? match = { from: pos, to: end } : this.matches.push(1, pos)), match && this.test && !this.test(match.from, match.to, this.buffer, this.bufferStart) && (match = null), match } }; typeof Symbol < "u" && (SearchCursor.prototype[Symbol.iterator] = function () { return this }); var empty = { from: -1, to: -1, match: /.*/.exec("") }, baseFlags = "gm" + (/x/.unicode == null ? "" : "u"), RegExpCursor = class { constructor(text, query, options, from = 0, to = text.length) { this.text = text; this.to = to; if (/\\[sWDnr]|\n|\r|\[\^/.test(query)) return new MultilineRegExpCursor(text, query, options, from, to); this.re = new RegExp(query, baseFlags + (options?.ignoreCase ? "i" : "")), this.test = options?.test, this.iter = text.iter(); let startLine = text.lineAt(from); this.curLineStart = startLine.from, this.matchPos = toCharEnd(text, from), this.getLine(this.curLineStart) } text; to; test; curLine = ""; done = !1; value = empty; getLine(skip) { this.iter.next(skip), this.iter.lineBreak ? this.curLine = "" : (this.curLine = this.iter.value, this.curLineStart + this.curLine.length > this.to && (this.curLine = this.curLine.slice(0, this.to - this.curLineStart)), this.iter.next()) } nextLine() { this.curLineStart = this.curLineStart + this.curLine.length + 1, this.curLineStart > this.to ? this.curLine = "" : this.getLine(0) } next() { for (let off = this.matchPos - this.curLineStart; ;) { this.re.lastIndex = off; let match = this.matchPos <= this.to && this.re.exec(this.curLine); if (match) { let from = this.curLineStart + match.index, to = from + match[0].length; if (this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0)), from == this.curLineStart + this.curLine.length && this.nextLine(), (from < to || from > this.value.to) && (!this.test || this.test(from, to, match))) return this.value = { from, to, match }, this; off = this.matchPos - this.curLineStart } else if (this.curLineStart + this.curLine.length < this.to) this.nextLine(), off = 0; else return this.done = !0, this } } }, flattened = new WeakMap, FlattenedDoc = class _FlattenedDoc { constructor(from, text) { this.from = from; this.text = text } from; text; get to() { return this.from + this.text.length } static get(doc2, from, to) { let cached = flattened.get(doc2); if (!cached || cached.from >= to || cached.to <= from) { let flat = new _FlattenedDoc(from, doc2.sliceString(from, to)); return flattened.set(doc2, flat), flat } if (cached.from == from && cached.to == to) return cached; let { text, from: cachedFrom } = cached; return cachedFrom > from && (text = doc2.sliceString(from, cachedFrom) + text, cachedFrom = from), cached.to < to && (text += doc2.sliceString(cached.to, to)), flattened.set(doc2, new _FlattenedDoc(cachedFrom, text)), new _FlattenedDoc(from, text.slice(from - cachedFrom, to - cachedFrom)) } }; var MultilineRegExpCursor = class { constructor(text, query, options, from, to) { this.text = text; this.to = to; this.matchPos = toCharEnd(text, from), this.re = new RegExp(query, baseFlags + (options?.ignoreCase ? "i" : "")), this.test = options?.test, this.flat = FlattenedDoc.get(text, from, this.chunkEnd(from + 5e3)) } text; to; flat; matchPos; re; test; done = !1; value = empty; chunkEnd(pos) { return pos >= this.to ? this.to : this.text.lineAt(pos).to } next() { for (; ;) { let off = this.re.lastIndex = this.matchPos - this.flat.from, match = this.re.exec(this.flat.text); if (match && !match[0] && match.index == off && (this.re.lastIndex = off + 1, match = this.re.exec(this.flat.text)), match) { let from = this.flat.from + match.index, to = from + match[0].length; if ((this.flat.to >= this.to || match.index + match[0].length <= this.flat.text.length - 10) && (!this.test || this.test(from, to, match))) return this.value = { from, to, match }, this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0)), this } if (this.flat.to == this.to) return this.done = !0, this; this.flat = FlattenedDoc.get(this.text, this.flat.from, this.chunkEnd(this.flat.from + this.flat.text.length * 2)) } } }; typeof Symbol < "u" && (RegExpCursor.prototype[Symbol.iterator] = MultilineRegExpCursor.prototype[Symbol.iterator] = function () { return this }); function validRegExp(source) { try { return new RegExp(source, baseFlags), !0 } catch { return !1 } } function toCharEnd(text, pos) { if (pos >= text.length) return pos; let line = text.lineAt(pos), next; for (; pos < line.to && (next = line.text.charCodeAt(pos - line.from)) >= 56320 && next < 57344;)pos++; return pos } var gotoLine = view => { let { state } = view, line = String(state.doc.lineAt(view.state.selection.main.head).number), { close, result } = showDialog(view, { label: state.phrase("Go to line"), input: { type: "text", name: "line", value: line }, focus: !0, submitLabel: state.phrase("go") }); return result.then(form => { let match = form && /^([+-])?(\d+)?(:\d+)?(%)?$/.exec(form.elements.line.value); if (!match) { view.dispatch({ effects: close }); return } let startLine = state.doc.lineAt(state.selection.main.head), [, sign, ln, cl, percent] = match, col = cl ? +cl.slice(1) : 0, line2 = ln ? +ln : startLine.number; if (ln && percent) { let pc = line2 / 100; sign && (pc = pc * (sign == "-" ? -1 : 1) + startLine.number / state.doc.lines), line2 = Math.round(state.doc.lines * pc) } else ln && sign && (line2 = line2 * (sign == "-" ? -1 : 1) + startLine.number); let docLine = state.doc.line(Math.max(1, Math.min(state.doc.lines, line2))), selection = EditorSelection.cursor(docLine.from + Math.max(0, Math.min(col, docLine.length))); view.dispatch({ effects: [close, EditorView.scrollIntoView(selection.from, { y: "center" })], selection }) }), !0 }; var defaultHighlightOptions = { highlightWordAroundCursor: !1, minSelectionLength: 1, maxMatches: 100, wholeWords: !1 }, highlightConfig = Facet.define({ combine(options) { return combineConfig(options, defaultHighlightOptions, { highlightWordAroundCursor: (a, b) => a || b, minSelectionLength: Math.min, maxMatches: Math.min }) } }); function highlightSelectionMatches(options) { let ext = [defaultTheme, matchHighlighter]; return options && ext.push(highlightConfig.of(options)), ext } var matchDeco = Decoration.mark({ class: "cm-selectionMatch" }), mainMatchDeco = Decoration.mark({ class: "cm-selectionMatch cm-selectionMatch-main" }); function insideWordBoundaries(check, state, from, to) { return (from == 0 || check(state.sliceDoc(from - 1, from)) != 0) && (to == state.doc.length || check(state.sliceDoc(to, to + 1)) != 0) } function insideWord(check, state, from, to) { return check(state.sliceDoc(from, from + 1)) == 0 && check(state.sliceDoc(to - 1, to)) == 0 } var matchHighlighter = ViewPlugin.fromClass(class { decorations; constructor(view) { this.decorations = this.getDeco(view) } update(update) { (update.selectionSet || update.docChanged || update.viewportChanged) && (this.decorations = this.getDeco(update.view)) } getDeco(view) { let conf = view.state.facet(highlightConfig), { state } = view, sel = state.selection; if (sel.ranges.length > 1) return Decoration.none; let range = sel.main, query, check = null; if (range.empty) { if (!conf.highlightWordAroundCursor) return Decoration.none; let word = state.wordAt(range.head); if (!word) return Decoration.none; check = state.charCategorizer(range.head), query = state.sliceDoc(word.from, word.to) } else { let len = range.to - range.from; if (len < conf.minSelectionLength || len > 200) return Decoration.none; if (conf.wholeWords) { if (query = state.sliceDoc(range.from, range.to), check = state.charCategorizer(range.head), !(insideWordBoundaries(check, state, range.from, range.to) && insideWord(check, state, range.from, range.to))) return Decoration.none } else if (query = state.sliceDoc(range.from, range.to), !query) return Decoration.none } let deco = []; for (let part of view.visibleRanges) { let cursor = new SearchCursor(state.doc, query, part.from, part.to); for (; !cursor.next().done;) { let { from, to } = cursor.value; if ((!check || insideWordBoundaries(check, state, from, to)) && (range.empty && from <= range.from && to >= range.to ? deco.push(mainMatchDeco.range(from, to)) : (from >= range.to || to <= range.from) && deco.push(matchDeco.range(from, to)), deco.length > conf.maxMatches)) return Decoration.none } } return Decoration.set(deco) } }, { decorations: v => v.decorations }), defaultTheme = EditorView.baseTheme({ ".cm-selectionMatch": { backgroundColor: "#99ff7780" }, ".cm-searchMatch .cm-selectionMatch": { backgroundColor: "transparent" } }), selectWord = ({ state, dispatch }) => { let { selection } = state, newSel = EditorSelection.create(selection.ranges.map(range => state.wordAt(range.head) || EditorSelection.cursor(range.head)), selection.mainIndex); return newSel.eq(selection) ? !1 : (dispatch(state.update({ selection: newSel })), !0) }; function findNextOccurrence(state, query) { let { main, ranges } = state.selection, word = state.wordAt(main.head), fullWord = word && word.from == main.from && word.to == main.to; for (let cycled = !1, cursor = new SearchCursor(state.doc, query, ranges[ranges.length - 1].to); ;)if (cursor.next(), cursor.done) { if (cycled) return null; cursor = new SearchCursor(state.doc, query, 0, Math.max(0, ranges[ranges.length - 1].from - 1)), cycled = !0 } else { if (cycled && ranges.some(r => r.from == cursor.value.from)) continue; if (fullWord) { let word2 = state.wordAt(cursor.value.from); if (!word2 || word2.from != cursor.value.from || word2.to != cursor.value.to) continue } return cursor.value } } var selectNextOccurrence = ({ state, dispatch }) => { let { ranges } = state.selection; if (ranges.some(sel => sel.from === sel.to)) return selectWord({ state, dispatch }); let searchedText = state.sliceDoc(ranges[0].from, ranges[0].to); if (state.selection.ranges.some(r => state.sliceDoc(r.from, r.to) != searchedText)) return !1; let range = findNextOccurrence(state, searchedText); return range ? (dispatch(state.update({ selection: state.selection.addRange(EditorSelection.range(range.from, range.to), !1), effects: EditorView.scrollIntoView(range.to) })), !0) : !1 }; var searchConfigFacet = Facet.define({ combine(configs) { return combineConfig(configs, { top: !1, caseSensitive: !1, literal: !1, regexp: !1, wholeWord: !1, createPanel: view => new SearchPanel(view), scrollToMatch: range => EditorView.scrollIntoView(range) }) } }); function search(config) { return config ? [searchConfigFacet.of(config), searchExtensions] : searchExtensions } var SearchQuery = class { + search; caseSensitive; literal; regexp; replace; valid; wholeWord; unquoted; test; constructor(config) { this.search = config.search, this.caseSensitive = !!config.caseSensitive, this.literal = !!config.literal, this.regexp = !!config.regexp, this.replace = config.replace || "", this.valid = !!this.search && (!this.regexp || validRegExp(this.search)), this.unquoted = this.unquote(this.search), this.wholeWord = !!config.wholeWord, this.test = config.test } unquote(text) { + return this.literal ? text : text.replace(/\\([nrt\\])/g, (_, ch) => ch == "n" ? ` +`: ch == "r" ? "\r" : ch == "t" ? " " : "\\") + } eq(other) { return this.search == other.search && this.replace == other.replace && this.caseSensitive == other.caseSensitive && this.regexp == other.regexp && this.wholeWord == other.wholeWord && this.test == other.test } create() { return this.regexp ? new RegExpQuery(this) : new StringQuery(this) } getCursor(state, from = 0, to) { let st = state.doc ? state : EditorState.create({ doc: state }); return to == null && (to = st.doc.length), this.regexp ? regexpCursor(this, st, from, to) : stringCursor(this, st, from, to) } +}, QueryType2 = class { constructor(spec) { this.spec = spec } spec }; function wrapStringTest(test, state, inner) { return (from, to, buffer, bufferPos) => { if (inner && !inner(from, to, buffer, bufferPos)) return !1; let match = from >= bufferPos && to <= bufferPos + buffer.length ? buffer.slice(from - bufferPos, to - bufferPos) : state.doc.sliceString(from, to); return test(match, state, from, to) } } function stringCursor(spec, state, from, to) { let test; return spec.wholeWord && (test = stringWordTest(state.doc, state.charCategorizer(state.selection.main.head))), spec.test && (test = wrapStringTest(spec.test, state, test)), new SearchCursor(state.doc, spec.unquoted, from, to, spec.caseSensitive ? void 0 : x => x.toLowerCase(), test) } function stringWordTest(doc2, categorizer) { return (from, to, buf, bufPos) => ((bufPos > from || bufPos + buf.length < to) && (bufPos = Math.max(0, from - 2), buf = doc2.sliceString(bufPos, Math.min(doc2.length, to + 2))), (categorizer(charBefore(buf, from - bufPos)) != 0 || categorizer(charAfter(buf, from - bufPos)) != 0) && (categorizer(charAfter(buf, to - bufPos)) != 0 || categorizer(charBefore(buf, to - bufPos)) != 0)) } var StringQuery = class extends QueryType2 { constructor(spec) { super(spec) } nextMatch(state, curFrom, curTo) { let cursor = stringCursor(this.spec, state, curTo, state.doc.length).nextOverlapping(); if (cursor.done) { let end = Math.min(state.doc.length, curFrom + this.spec.unquoted.length); cursor = stringCursor(this.spec, state, 0, end).nextOverlapping() } return cursor.done || cursor.value.from == curFrom && cursor.value.to == curTo ? null : cursor.value } prevMatchInRange(state, from, to) { for (let pos = to; ;) { let start = Math.max(from, pos - 1e4 - this.spec.unquoted.length), cursor = stringCursor(this.spec, state, start, pos), range = null; for (; !cursor.nextOverlapping().done;)range = cursor.value; if (range) return range; if (start == from) return null; pos -= 1e4 } } prevMatch(state, curFrom, curTo) { let found = this.prevMatchInRange(state, 0, curFrom); return found || (found = this.prevMatchInRange(state, Math.max(0, curTo - this.spec.unquoted.length), state.doc.length)), found && (found.from != curFrom || found.to != curTo) ? found : null } getReplacement(_result) { return this.spec.unquote(this.spec.replace) } matchAll(state, limit) { let cursor = stringCursor(this.spec, state, 0, state.doc.length), ranges = []; for (; !cursor.next().done;) { if (ranges.length >= limit) return null; ranges.push(cursor.value) } return ranges } highlight(state, from, to, add2) { let cursor = stringCursor(this.spec, state, Math.max(0, from - this.spec.unquoted.length), Math.min(to + this.spec.unquoted.length, state.doc.length)); for (; !cursor.next().done;)add2(cursor.value.from, cursor.value.to) } }; function wrapRegexpTest(test, state, inner) { return (from, to, match) => (!inner || inner(from, to, match)) && test(match[0], state, from, to) } function regexpCursor(spec, state, from, to) { let test; return spec.wholeWord && (test = regexpWordTest(state.charCategorizer(state.selection.main.head))), spec.test && (test = wrapRegexpTest(spec.test, state, test)), new RegExpCursor(state.doc, spec.search, { ignoreCase: !spec.caseSensitive, test }, from, to) } function charBefore(str, index) { return str.slice(findClusterBreak2(str, index, !1), index) } function charAfter(str, index) { return str.slice(index, findClusterBreak2(str, index)) } function regexpWordTest(categorizer) { return (_from, _to, match) => !match[0].length || (categorizer(charBefore(match.input, match.index)) != 0 || categorizer(charAfter(match.input, match.index)) != 0) && (categorizer(charAfter(match.input, match.index + match[0].length)) != 0 || categorizer(charBefore(match.input, match.index + match[0].length)) != 0) } var RegExpQuery = class extends QueryType2 { nextMatch(state, curFrom, curTo) { let cursor = regexpCursor(this.spec, state, curTo, state.doc.length).next(); return cursor.done && (cursor = regexpCursor(this.spec, state, 0, curFrom).next()), cursor.done ? null : cursor.value } prevMatchInRange(state, from, to) { for (let size = 1; ; size++) { let start = Math.max(from, to - size * 1e4), cursor = regexpCursor(this.spec, state, start, to), range = null; for (; !cursor.next().done;)range = cursor.value; if (range && (start == from || range.from > start + 10)) return range; if (start == from) return null } } prevMatch(state, curFrom, curTo) { return this.prevMatchInRange(state, 0, curFrom) || this.prevMatchInRange(state, curTo, state.doc.length) } getReplacement(result) { return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g, (m, i2) => { if (i2 == "&") return result.match[0]; if (i2 == "$") return "$"; for (let l = i2.length; l > 0; l--) { let n = +i2.slice(0, l); if (n > 0 && n < result.match.length) return result.match[n] + i2.slice(l) } return m }) } matchAll(state, limit) { let cursor = regexpCursor(this.spec, state, 0, state.doc.length), ranges = []; for (; !cursor.next().done;) { if (ranges.length >= limit) return null; ranges.push(cursor.value) } return ranges } highlight(state, from, to, add2) { let cursor = regexpCursor(this.spec, state, Math.max(0, from - 250), Math.min(to + 250, state.doc.length)); for (; !cursor.next().done;)add2(cursor.value.from, cursor.value.to) } }, setSearchQuery = StateEffect.define(), togglePanel = StateEffect.define(), searchState = StateField.define({ create(state) { return new SearchState(defaultQuery(state).create(), null) }, update(value, tr) { for (let effect of tr.effects) effect.is(setSearchQuery) ? value = new SearchState(effect.value.create(), value.panel) : effect.is(togglePanel) && (value = new SearchState(value.query, effect.value ? createSearchPanel : null)); return value }, provide: f => showPanel.from(f, val => val.panel) }); var SearchState = class { constructor(query, panel) { this.query = query; this.panel = panel } query; panel }, matchMark = Decoration.mark({ class: "cm-searchMatch" }), selectedMatchMark = Decoration.mark({ class: "cm-searchMatch cm-searchMatch-selected" }), searchHighlighter = ViewPlugin.fromClass(class { constructor(view) { this.view = view; this.decorations = this.highlight(view.state.field(searchState)) } view; decorations; update(update) { let state = update.state.field(searchState); (state != update.startState.field(searchState) || update.docChanged || update.selectionSet || update.viewportChanged) && (this.decorations = this.highlight(state)) } highlight({ query, panel }) { if (!panel || !query.spec.valid) return Decoration.none; let { view } = this, builder = new RangeSetBuilder; for (let i2 = 0, ranges = view.visibleRanges, l = ranges.length; i2 < l; i2++) { let { from, to } = ranges[i2]; for (; i2 < l - 1 && to > ranges[i2 + 1].from - 500;)to = ranges[++i2].to; query.highlight(view.state, from, to, (from2, to2) => { let selected = view.state.selection.ranges.some(r => r.from == from2 && r.to == to2); builder.add(from2, to2, selected ? selectedMatchMark : matchMark) }) } return builder.finish() } }, { decorations: v => v.decorations }); function searchCommand(f) { return view => { let state = view.state.field(searchState, !1); return state && state.query.spec.valid ? f(view, state) : openSearchPanel(view) } } var findNext = searchCommand((view, { query }) => { let { to } = view.state.selection.main, next = query.nextMatch(view.state, to, to); if (!next) return !1; let selection = EditorSelection.single(next.from, next.to), config = view.state.facet(searchConfigFacet); return view.dispatch({ selection, effects: [announceMatch(view, next), config.scrollToMatch(selection.main, view)], userEvent: "select.search" }), selectSearchInput(view), !0 }), findPrevious = searchCommand((view, { query }) => { let { state } = view, { from } = state.selection.main, prev = query.prevMatch(state, from, from); if (!prev) return !1; let selection = EditorSelection.single(prev.from, prev.to), config = view.state.facet(searchConfigFacet); return view.dispatch({ selection, effects: [announceMatch(view, prev), config.scrollToMatch(selection.main, view)], userEvent: "select.search" }), selectSearchInput(view), !0 }), selectMatches = searchCommand((view, { query }) => { let ranges = query.matchAll(view.state, 1e3); return !ranges || !ranges.length ? !1 : (view.dispatch({ selection: EditorSelection.create(ranges.map(r => EditorSelection.range(r.from, r.to))), userEvent: "select.search.matches" }), !0) }), selectSelectionMatches = ({ state, dispatch }) => { let sel = state.selection; if (sel.ranges.length > 1 || sel.main.empty) return !1; let { from, to } = sel.main, ranges = [], main = 0; for (let cur = new SearchCursor(state.doc, state.sliceDoc(from, to)); !cur.next().done;) { if (ranges.length > 1e3) return !1; cur.value.from == from && (main = ranges.length), ranges.push(EditorSelection.range(cur.value.from, cur.value.to)) } return dispatch(state.update({ selection: EditorSelection.create(ranges, main), userEvent: "select.search.matches" })), !0 }, replaceNext = searchCommand((view, { query }) => { let { state } = view, { from, to } = state.selection.main; if (state.readOnly) return !1; let match = query.nextMatch(state, from, from); if (!match) return !1; let next = match, changes = [], selection, replacement, effects = []; next.from == from && next.to == to && (replacement = state.toText(query.getReplacement(next)), changes.push({ from: next.from, to: next.to, insert: replacement }), next = query.nextMatch(state, next.from, next.to), effects.push(EditorView.announce.of(state.phrase("replaced match on line $", state.doc.lineAt(from).number) + "."))); let changeSet = view.state.changes(changes); return next && (selection = EditorSelection.single(next.from, next.to).map(changeSet), effects.push(announceMatch(view, next)), effects.push(state.facet(searchConfigFacet).scrollToMatch(selection.main, view))), view.dispatch({ changes: changeSet, selection, effects, userEvent: "input.replace" }), !0 }), replaceAll = searchCommand((view, { query }) => { if (view.state.readOnly) return !1; let changes = query.matchAll(view.state, 1e9).map(match => { let { from, to } = match; return { from, to, insert: query.getReplacement(match) } }); if (!changes.length) return !1; let announceText = view.state.phrase("replaced $ matches", changes.length) + "."; return view.dispatch({ changes, effects: EditorView.announce.of(announceText), userEvent: "input.replace.all" }), !0 }); function createSearchPanel(view) { return view.state.facet(searchConfigFacet).createPanel(view) } function defaultQuery(state, fallback) { let sel = state.selection.main, selText = sel.empty || sel.to > sel.from + 100 ? "" : state.sliceDoc(sel.from, sel.to); if (fallback && !selText) return fallback; let config = state.facet(searchConfigFacet); return new SearchQuery({ search: fallback?.literal ?? config.literal ? selText : selText.replace(/\n/g, "\\n"), caseSensitive: fallback?.caseSensitive ?? config.caseSensitive, literal: fallback?.literal ?? config.literal, regexp: fallback?.regexp ?? config.regexp, wholeWord: fallback?.wholeWord ?? config.wholeWord }) } function getSearchInput(view) { let panel = getPanel(view, createSearchPanel); return panel && panel.dom.querySelector("[main-field]") } function selectSearchInput(view) { let input = getSearchInput(view); input && input == view.root.activeElement && input.select() } var openSearchPanel = view => { let state = view.state.field(searchState, !1); if (state && state.panel) { let searchInput = getSearchInput(view); if (searchInput && searchInput != view.root.activeElement) { let query = defaultQuery(view.state, state.query.spec); query.valid && view.dispatch({ effects: setSearchQuery.of(query) }), searchInput.focus(), searchInput.select() } } else view.dispatch({ effects: [togglePanel.of(!0), state ? setSearchQuery.of(defaultQuery(view.state, state.query.spec)) : StateEffect.appendConfig.of(searchExtensions)] }); return !0 }, closeSearchPanel = view => { let state = view.state.field(searchState, !1); if (!state || !state.panel) return !1; let panel = getPanel(view, createSearchPanel); return panel && panel.dom.contains(view.root.activeElement) && view.focus(), view.dispatch({ effects: togglePanel.of(!1) }), !0 }, searchKeymap = [{ key: "Mod-f", run: openSearchPanel, scope: "editor search-panel" }, { key: "F3", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: !0 }, { key: "Mod-g", run: findNext, shift: findPrevious, scope: "editor search-panel", preventDefault: !0 }, { key: "Escape", run: closeSearchPanel, scope: "editor search-panel" }, { key: "Mod-Shift-l", run: selectSelectionMatches }, { key: "Mod-Alt-g", run: gotoLine }, { key: "Mod-d", run: selectNextOccurrence, preventDefault: !0 }], SearchPanel = class { constructor(view) { this.view = view; let query = this.query = view.state.field(searchState).query.spec; this.commit = this.commit.bind(this), this.searchField = crelt("input", { value: query.search, placeholder: phrase(view, "Find"), "aria-label": phrase(view, "Find"), class: "cm-textfield", name: "search", form: "", "main-field": "true", onchange: this.commit, onkeyup: this.commit }), this.replaceField = crelt("input", { value: query.replace, placeholder: phrase(view, "Replace"), "aria-label": phrase(view, "Replace"), class: "cm-textfield", name: "replace", form: "", onchange: this.commit, onkeyup: this.commit }), this.caseField = crelt("input", { type: "checkbox", name: "case", form: "", checked: query.caseSensitive, onchange: this.commit }), this.reField = crelt("input", { type: "checkbox", name: "re", form: "", checked: query.regexp, onchange: this.commit }), this.wordField = crelt("input", { type: "checkbox", name: "word", form: "", checked: query.wholeWord, onchange: this.commit }); function button(name2, onclick, content2) { return crelt("button", { class: "cm-button", name: name2, onclick, type: "button" }, content2) } this.dom = crelt("div", { onkeydown: e => this.keydown(e), class: "cm-search" }, [this.searchField, button("next", () => findNext(view), [phrase(view, "next")]), button("prev", () => findPrevious(view), [phrase(view, "previous")]), button("select", () => selectMatches(view), [phrase(view, "all")]), crelt("label", null, [this.caseField, phrase(view, "match case")]), crelt("label", null, [this.reField, phrase(view, "regexp")]), crelt("label", null, [this.wordField, phrase(view, "by word")]), ...view.state.readOnly ? [] : [crelt("br"), this.replaceField, button("replace", () => replaceNext(view), [phrase(view, "replace")]), button("replaceAll", () => replaceAll(view), [phrase(view, "replace all")])], crelt("button", { name: "close", onclick: () => closeSearchPanel(view), "aria-label": phrase(view, "close"), type: "button" }, ["\xD7"])]) } view; searchField; replaceField; caseField; reField; wordField; dom; query; commit() { let query = new SearchQuery({ search: this.searchField.value, caseSensitive: this.caseField.checked, regexp: this.reField.checked, wholeWord: this.wordField.checked, replace: this.replaceField.value }); query.eq(this.query) || (this.query = query, this.view.dispatch({ effects: setSearchQuery.of(query) })) } keydown(e) { runScopeHandlers(this.view, e, "search-panel") ? e.preventDefault() : e.keyCode == 13 && e.target == this.searchField ? (e.preventDefault(), (e.shiftKey ? findPrevious : findNext)(this.view)) : e.keyCode == 13 && e.target == this.replaceField && (e.preventDefault(), replaceNext(this.view)) } update(update) { for (let tr of update.transactions) for (let effect of tr.effects) effect.is(setSearchQuery) && !effect.value.eq(this.query) && this.setQuery(effect.value) } setQuery(query) { this.query = query, this.searchField.value = query.search, this.replaceField.value = query.replace, this.caseField.checked = query.caseSensitive, this.reField.checked = query.regexp, this.wordField.checked = query.wholeWord } mount() { this.searchField.select() } get pos() { return 80 } get top() { return this.view.state.facet(searchConfigFacet).top } }; function phrase(view, phrase2) { return view.state.phrase(phrase2) } var AnnounceMargin = 30, Break = /[\s\.,:;?!]/; function announceMatch(view, { from, to }) { let line = view.state.doc.lineAt(from), lineEnd = view.state.doc.lineAt(to).to, start = Math.max(line.from, from - AnnounceMargin), end = Math.min(lineEnd, to + AnnounceMargin), text = view.state.sliceDoc(start, end); if (start != line.from) { for (let i2 = 0; i2 < AnnounceMargin; i2++)if (!Break.test(text[i2 + 1]) && Break.test(text[i2])) { text = text.slice(i2); break } } if (end != lineEnd) { for (let i2 = text.length - 1; i2 > text.length - AnnounceMargin; i2--)if (!Break.test(text[i2 - 1]) && Break.test(text[i2])) { text = text.slice(0, i2); break } } return EditorView.announce.of(`${view.state.phrase("current match")}. ${text} ${view.state.phrase("on line")} ${line.number}.`) } var baseTheme5 = EditorView.baseTheme({ ".cm-panel.cm-search": { padding: "2px 6px 4px", position: "relative", "& [name=close]": { position: "absolute", top: "0", right: "4px", backgroundColor: "inherit", border: "none", font: "inherit", padding: 0, margin: 0 }, "& input, & button, & label": { margin: ".2em .6em .2em 0" }, "& input[type=checkbox]": { marginRight: ".2em" }, "& label": { fontSize: "80%", whiteSpace: "pre" } }, "&light .cm-searchMatch": { backgroundColor: "#ffff0054" }, "&dark .cm-searchMatch": { backgroundColor: "#00ffff8a" }, "&light .cm-searchMatch-selected": { backgroundColor: "#ff6a0054" }, "&dark .cm-searchMatch-selected": { backgroundColor: "#ff00ff8a" } }), searchExtensions = [searchState, Prec.low(searchHighlighter), baseTheme5]; export { Annotation, AnnotationType, BidiSpan, BlockInfo, BlockType, BlockWrapper, ChangeDesc, ChangeSet, CharCategory, Compartment, Decoration, Direction, EditorSelection, EditorState, EditorView, Facet, GutterMarker, HighlightStyle, LanguageSupport, Line, MapMode, MatchDecorator, Prec, Range, RangeSet, RangeSetBuilder, RangeValue, RectangleMarker, SelectionRange, StateEffect, StateEffectType, StateField, StreamLanguage, Text, Transaction, ViewPlugin, ViewUpdate, WidgetType, __test, bracketMatching, closeHoverTooltips, closeSearchPanel, codeFolding, codePointAt2 as codePointAt, codePointSize2 as codePointSize, combineConfig, countColumn, crosshairCursor, defaultHighlightStyle, defaultKeymap, drawSelection, dropCursor, findClusterBreak2 as findClusterBreak, findColumn, foldGutter, foldKeymap, foldService, fromCodePoint, getDialog, getDrawSelectionConfig, getPanel, getTooltip, gotoLine, gutter, gutterLineClass, gutterWidgetClass, gutters, hasHoverTooltips, highlightActiveLine, highlightActiveLineGutter, highlightSelectionMatches, highlightSpecialChars, highlightTrailingWhitespace, highlightWhitespace, history, historyKeymap, hoverTooltip, indentLess, indentMore, indentService, indentUnit, indentWithTab, insertNewlineAndIndent, keymap, layer, lineNumberMarkers, lineNumberWidgetMarker, lineNumbers, logException, openSearchPanel, panels, placeholder2 as placeholder, rectangularSelection, redo, repositionTooltips, runScopeHandlers, scrollPastEnd, search, searchKeymap, selectAll, showDialog, showPanel, showTooltip, syntaxHighlighting, toggleComment, tooltips, undo }; diff --git a/styles.css b/styles.css new file mode 100644 index 0000000..0d58a43 --- /dev/null +++ b/styles.css @@ -0,0 +1,4348 @@ +/* Programming+: a lab notebook for algorithms. Tokens first; light and dark; IBM Plex in two voices. */ +:root { + --paper: #f7f8fa; + --paper-2: #ffffff; + --paper-3: #eef0f4; + --ink: #16191f; + --ink-2: #5c6370; + --ink-3: #646b77; + --line: #dde1e8; + --line-2: #c9cfd8; + --accent: #2f5bea; + --accent-ink: #ffffff; + --accent-bg: #e7edfd; + --marker: #f6c453; + --marker-bg: #fff3cf; + --last-bg: #e3ecfb; + --ok: #157a4c; + --ok-bg: #e2f5ea; + --warn: #8f5807; + --warn-bg: #fdf0d6; + --err: #b83232; + --err-bg: #fbe3e3; + --mono: "IBM Plex Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace; + --sans: "IBM Plex Sans", system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + --r: 6px; + --r-lg: 10px; + --shadow: 0 10px 30px rgba(22, 25, 31, .10); + --tok-keyword: #1d46c7; + --tok-builtin: #7a3fc4; + --tok-string: #a8580d; + --tok-number: #0f7b6c; + --tok-comment: #646b77; + --tok-label: #b4247a; + /* the P+ mark: a light tile on the light theme, a dark one on the dark theme */ + --brand-bg: #f6c453; + --brand-fg: #16191f; + --brand-edge: #e0ab35; + color-scheme: light; +} + +:root[data-theme="dark"] { + --paper: #141821; + --paper-2: #1b2029; + --paper-3: #232935; + --ink: #e9ecf1; + --ink-2: #a7afbc; + --ink-3: #8b93a1; + --line: #2c333f; + --line-2: #3b4452; + --accent: #8db0ff; + --accent-ink: #0f1626; + --accent-bg: #1f2b4a; + --marker: #f0c05a; + --marker-bg: #4a3c12; + --last-bg: #1f3350; + --ok: #5fd39a; + --ok-bg: #16331f; + --warn: #f0b860; + --warn-bg: #3a2c12; + --err: #ff8585; + --err-bg: #3f1b1b; + --shadow: 0 10px 30px rgba(0, 0, 0, .45); + --tok-keyword: #8db0ff; + --tok-builtin: #c9a7ff; + --tok-string: #f2b56b; + --tok-number: #5fd3c6; + --tok-comment: #8b93a1; + --tok-label: #f49ac2; + --brand-bg: #0e1117; + --brand-fg: #f0c05a; + --brand-edge: #2c333f; + color-scheme: dark; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]):not([data-theme="dark"]) { + --paper: #141821; + --paper-2: #1b2029; + --paper-3: #232935; + --ink: #e9ecf1; + --ink-2: #a7afbc; + --ink-3: #8b93a1; + --line: #2c333f; + --line-2: #3b4452; + --accent: #8db0ff; + --accent-ink: #0f1626; + --accent-bg: #1f2b4a; + --marker: #f0c05a; + --marker-bg: #4a3c12; + --last-bg: #1f3350; + --ok: #5fd39a; + --ok-bg: #16331f; + --warn: #f0b860; + --warn-bg: #3a2c12; + --err: #ff8585; + --err-bg: #3f1b1b; + --shadow: 0 10px 30px rgba(0, 0, 0, .45); + --tok-keyword: #8db0ff; + --tok-builtin: #c9a7ff; + --tok-string: #f2b56b; + --tok-number: #5fd3c6; + --tok-comment: #8b93a1; + --tok-label: #f49ac2; + --brand-bg: #0e1117; + --brand-fg: #f0c05a; + --brand-edge: #2c333f; + color-scheme: dark; + } +} + +/* legacy aliases used by older rules */ +:root { + --bg: var(--paper); + --bg-2: var(--paper-2); + --bg-3: var(--paper-3); + --fg: var(--ink); + --fg-2: var(--ink-2); + --note: var(--ink-3); + --current: var(--marker-bg); + --last: var(--last-bg); + --radius: var(--r-lg); +} + +* { + box-sizing: border-box; +} + +html, +body { + height: 100%; +} + +body { + margin: 0; + background: var(--paper); + color: var(--ink); + font: 14px/1.5 var(--sans); + -webkit-font-smoothing: antialiased; +} + +body.is-embed { + background: var(--paper-2); +} + +#app { + height: 100%; +} + +a { + color: var(--accent); + text-decoration: none; +} + +a:hover { + text-decoration: underline; +} + +h1, +h2, +h3, +h4 { + margin: 0 0 .4em; + font-weight: 600; + line-height: 1.2; + letter-spacing: -.01em; +} + +h4 { + font-size: 13px; + color: var(--ink-2); + font-weight: 600; + margin: 14px 0 6px; + letter-spacing: 0; +} + +code, +.mono { + font-family: var(--mono); + font-size: 12.5px; +} + +.muted { + color: var(--ink-2); +} + +.small { + font-size: 12px; +} + +.hint { + font-size: 12.5px; + color: var(--ink-2); + background: var(--paper-3); + border-left: 3px solid var(--accent); + padding: 6px 10px; + border-radius: 4px; + margin: 0 0 10px; +} + +.math { + font-family: "STIX Two Math", "Cambria Math", var(--mono); + font-size: 13px; +} + +:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 1px; +} + +@media (prefers-reduced-motion: reduce) { + + *, + *::before, + *::after { + transition: none !important; + animation: none !important; + } +} + +/* ---------- controls ---------- */ +.btn { + font: inherit; + font-size: 13px; + padding: 5px 11px; + border: 1px solid var(--line-2); + border-radius: var(--r); + background: var(--paper-2); + color: var(--ink); + cursor: pointer; + transition: border-color .12s, background .12s; +} + +.btn:hover { + border-color: var(--ink-3); +} + +.btn-primary { + background: var(--accent); + border-color: var(--accent); + color: var(--accent-ink); + font-weight: 600; +} + +.btn-primary:hover { + filter: brightness(1.06); +} + +.btn-quiet { + background: transparent; + border-color: transparent; + color: var(--ink-2); +} + +.btn-quiet:hover { + background: var(--paper-3); + border-color: transparent; +} + +.btn-small { + padding: 2px 8px; + font-size: 12px; +} + +.btn-option { + margin: 4px 6px 0 0; + background: var(--accent-bg); + border-color: transparent; +} + +.btn.on { + background: var(--accent-bg); + border-color: var(--accent); + color: var(--accent); +} + +.linkish { + background: none; + border: 0; + padding: 0; + color: var(--accent); + cursor: pointer; + font: inherit; + text-decoration: underline dotted; +} + +.select, +.input { + font: inherit; + font-size: 13px; + padding: 5px 8px; + border: 1px solid var(--line-2); + border-radius: var(--r); + background: var(--paper-2); + color: var(--ink); +} + +.input { + min-width: 240px; +} + +.tool-label { + display: inline-flex; + align-items: center; + gap: 6px; + color: var(--ink-2); + font-size: 12.5px; +} + +.badge { + display: inline-block; + font-size: 11.5px; + padding: 1px 8px; + border-radius: 10px; + font-weight: 600; + margin-right: 6px; + line-height: 1.6; +} + +.badge-proved { + background: var(--ok-bg); + color: var(--ok); +} + +.badge-broken { + background: var(--err-bg); + color: var(--err); +} + +.badge-open { + background: var(--warn-bg); + color: var(--warn); +} + +.chip { + display: inline-block; + font-size: 11.5px; + padding: 1px 8px; + border-radius: 10px; + background: var(--paper-3); + color: var(--ink-2); + margin-right: 4px; + line-height: 1.6; +} + +.chip-saved { + background: var(--ok-bg); + color: var(--ok); +} + +.chip-level-intro { + background: var(--ok-bg); + color: var(--ok); +} + +.chip-level-advanced { + background: var(--warn-bg); + color: var(--warn); +} + +.chip-tag { + background: transparent; + border: 1px solid var(--line); +} + +kbd { + font-family: var(--mono); + font-size: 11px; + padding: 1px 6px; + border: 1px solid var(--line-2); + border-bottom-width: 2px; + border-radius: 4px; + background: var(--paper-2); + color: var(--ink); +} + +/* a segmented switch: Mojo | pseudo */ +.seg { + display: inline-flex; + border: 1px solid var(--line-2); + border-radius: 999px; + padding: 2px; + background: var(--paper-2); + gap: 2px; +} + +.seg-opt { + font: inherit; + font-size: 12.5px; + font-weight: 600; + padding: 3px 12px; + border: 0; + border-radius: 999px; + background: transparent; + color: var(--ink-2); + cursor: pointer; +} + +.seg-opt:hover { + color: var(--ink); +} + +.seg-opt.on { + background: var(--ink); + color: var(--paper); +} + +/* ---------- top bar ---------- */ +.toolbar { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 14px; + border-bottom: 1px solid var(--line); + background: var(--paper-2); + flex-wrap: wrap; +} + +.brand { + display: inline-flex; + align-items: center; + gap: 8px; + font-weight: 700; + font-size: 15px; + color: var(--ink); + margin-right: 6px; + white-space: nowrap; + letter-spacing: -.01em; +} + +.brand:hover { + text-decoration: none; +} + +.brand-mark { + min-width: 22px; + height: 22px; + padding: 0 4px; + border-radius: 6px; + background: var(--brand-bg); + color: var(--brand-fg); + box-shadow: inset 0 0 0 1px var(--brand-edge); + display: inline-grid; + place-items: center; + font-family: var(--mono); + font-size: 11px; + font-weight: 700; +} + +.spacer { + flex: 1; +} + +.icon-btn { + width: 32px; + height: 32px; + padding: 0; + display: inline-grid; + place-items: center; + font-size: 15px; +} + +/* ---------- home ---------- */ +.home { + max-width: 1120px; + margin: 0 auto; + padding: 0 24px 64px; +} + +.home-nav { + display: flex; + align-items: center; + gap: 16px; + padding: 18px 0 8px; +} + +.home-nav a { + color: var(--ink-2); + font-size: 13.5px; +} + +.hero { + display: grid; + grid-template-columns: minmax(0, 1.05fr) minmax(0, 1fr); + gap: 40px; + align-items: center; + padding: 36px 0 44px; + border-bottom: 1px solid var(--line); +} + +.hero h1 { + font-size: 44px; + line-height: 1.08; + letter-spacing: -.025em; + margin: 0 0 16px; + max-width: 14ch; +} + +.hero .lede { + font-size: 17px; + color: var(--ink-2); + margin: 0 0 22px; + max-width: 48ch; + line-height: 1.5; +} + +.hero-actions { + display: flex; + gap: 10px; + flex-wrap: wrap; +} + +.hero-actions .btn { + padding: 9px 16px; + font-size: 14px; +} + +.demo { + border: 1px solid var(--line); + border-radius: var(--r-lg); + background: var(--paper-2); + overflow: hidden; + box-shadow: var(--shadow); +} + +.demo-head { + display: flex; + align-items: center; + gap: 8px; + padding: 8px 12px; + border-bottom: 1px solid var(--line); + font-size: 12.5px; + color: var(--ink-2); +} + +.demo-head b { + color: var(--ink); + font-weight: 600; +} + +.demo-code { + margin: 0; + padding: 12px 14px; + font-family: var(--mono); + font-size: 12.5px; + line-height: 1.7; + white-space: pre; + overflow-x: auto; +} + +.demo-line { + display: block; + padding: 0 6px; + margin: 0 -6px; + border-radius: 3px; +} + +.demo-line.cur { + background: var(--marker-bg); + box-shadow: inset 3px 0 var(--marker); +} + +.demo-foot { + display: grid; + grid-template-columns: 1fr auto; + gap: 10px; + align-items: center; + padding: 10px 12px; + border-top: 1px solid var(--line); + background: var(--paper); +} + +.demo-vars { + display: flex; + gap: 14px; + font-family: var(--mono); + font-size: 12.5px; + flex-wrap: wrap; +} + +.demo-vars b { + font-weight: 600; +} + +.demo-vars .v-new { + background: var(--last-bg); + border-radius: 3px; + padding: 0 4px; +} + +.demo-ctl { + display: flex; + gap: 4px; +} + +.ruler { + display: inline-flex; + gap: 2px; + font-family: var(--mono); +} + +.ruler-cell { + display: inline-flex; + flex-direction: column; + align-items: center; + min-width: 20px; + line-height: 1.1; + border-radius: 3px; + padding: 2px 1px; +} + +.ruler-cell b { + font-weight: 600; + font-size: 13px; +} + +.ruler-cell i { + font-style: normal; + font-size: 9.5px; + color: var(--ink-3); +} + +.ruler-cell.read { + background: var(--marker-bg); + box-shadow: inset 0 -2px var(--marker); +} + +.ruler-cell.wrote { + background: var(--last-bg); +} + +.how { + padding: 36px 0 28px; + border-bottom: 1px solid var(--line); +} + +.how .hero-actions { + margin-top: 18px; +} + +.how h2, +.home-h2, +.reference h2 { + font-size: 24px; + letter-spacing: -.02em; + margin-bottom: 6px; +} + +.how>p, +.home-sub { + color: var(--ink-2); + max-width: 64ch; + margin: 0 0 18px; +} + +.ways { + display: grid; + grid-template-columns: repeat(5, minmax(0, 1fr)); + gap: 10px; +} + +.way { + border: 1px solid var(--line); + border-radius: var(--r-lg); + background: var(--paper-2); + padding: 12px 12px 10px; + min-width: 0; +} + +.way h3 { + font-size: 14px; + margin: 0 0 2px; +} + +.way p { + margin: 0 0 8px; + font-size: 12.5px; + color: var(--ink-2); + min-height: 3.6em; +} + +.way pre { + margin: 0; + font-family: var(--mono); + font-size: 11px; + line-height: 1.5; + white-space: pre; + overflow: hidden; + color: var(--ink); + border-top: 1px solid var(--line); + padding-top: 8px; +} + +.problems-head { + display: flex; + align-items: baseline; + gap: 16px; + flex-wrap: wrap; + margin: 40px 0 12px; +} + +.filters { + display: flex; + gap: 6px; + flex-wrap: wrap; + margin-bottom: 14px; +} + +.filter { + font: inherit; + font-size: 12.5px; + padding: 3px 10px; + border-radius: 12px; + border: 1px solid var(--line-2); + background: var(--paper-2); + color: var(--ink-2); + cursor: pointer; +} + +.filter.on { + background: var(--ink); + color: var(--paper); + border-color: var(--ink); +} + +.search { + min-width: 220px; +} + +.home-group { + font-size: 13px; + color: var(--ink-2); + margin: 20px 0 8px; + font-weight: 600; +} + +.cards { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); + gap: 12px; +} + +.card { + display: block; + color: inherit; + background: var(--paper-2); + border: 1px solid var(--line); + border-radius: var(--r-lg); + padding: 14px 16px 12px; + transition: border-color .12s; +} + +.card:hover { + border-color: var(--accent); + text-decoration: none; +} + +.card h3 { + font-size: 15px; + margin-bottom: 4px; +} + +.card p { + margin: 0 0 10px; + color: var(--ink-2); + font-size: 13px; +} + +.card-meta, +.card-foot { + display: flex; + flex-wrap: wrap; + gap: 2px; +} + +.card-meta { + margin-bottom: 6px; +} + +.home-foot { + margin-top: 40px; + color: var(--ink-2); + font-size: 12.5px; + border-top: 1px solid var(--line); + padding-top: 14px; +} + +/* ---------- shell: an IDE layout ---------- */ +.shell { + display: flex; + flex-direction: column; + height: 100%; +} + +.workspace { + --dock: 68%; + flex: 1; + min-height: 0; + display: grid; + grid-template-rows: minmax(0, var(--dock)) 6px minmax(0, 1fr); +} + +.workspace.dock-collapsed { + grid-template-rows: minmax(0, 1fr) 0 auto; +} + +.workspace.dock-collapsed .splitter-y { + display: none; +} + +.workspace.dock-collapsed .dock-body { + display: none; +} + +.main { + --split: 54%; + min-height: 0; + display: grid; + grid-template-columns: minmax(280px, var(--split)) 6px minmax(320px, 1fr); +} + +.panes, +.side { + min-height: 0; + min-width: 0; + display: flex; + flex-direction: column; +} + +.side { + background: var(--paper); + border-left: 0; +} + +/* tabs: file tabs over the editor, panel tabs elsewhere */ +.tabs { + display: flex; + gap: 2px; + padding: 6px 10px 0; + border-bottom: 1px solid var(--line); + background: var(--paper); + overflow-x: auto; + align-items: flex-end; + flex-shrink: 0; +} + +.tab { + font: inherit; + font-size: 13px; + padding: 6px 12px; + border: 1px solid transparent; + border-bottom: 0; + border-radius: var(--r) var(--r) 0 0; + background: transparent; + color: var(--ink-2); + cursor: pointer; + white-space: nowrap; + display: inline-flex; + align-items: center; + gap: 6px; +} + +.tab:hover { + color: var(--ink); +} + +.tab.active { + background: var(--paper-2); + border-color: var(--line); + color: var(--ink); + font-weight: 600; + margin-bottom: -1px; +} + +.tab.tab-dim { + color: var(--ink-3); +} + +.pane-tabs .tab-dim .tab-dot { + opacity: .3; +} + +/* the Bridge sets the generated Mojo tab slightly apart from the four languages kept in step */ +.pane-tabs .tab-apart { + margin-left: 14px; +} + +/* where a pane stands against the others: edited here, in step, or not in step */ +.tab-state { + font-size: 11px; + margin-left: 5px; + color: var(--ink-3); +} + +.tab-link-stale .tab-state { + color: var(--warn); +} + +.pane-stale { + color: var(--warn); +} + +.badge-generated { + background: var(--warn-bg); + color: var(--warn); + border: 1px dashed currentColor; +} + +.tab.tab-dim.active { + color: var(--ink-2); +} + +.tab-dot { + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--ink-3); + opacity: .7; +} + +.tab-lingo .tab-dot { + background: var(--lang-lingo); +} + +.tab-matho .tab-dot { + background: var(--lang-matho); +} + +.tab-pseudo .tab-dot { + background: var(--lang-pseudo); +} + +.tab-speco .tab-dot { + background: var(--lang-speco); +} + +.tab-mojo .tab-dot { + background: var(--lang-mojo); +} + +.tab-asm .tab-dot { + background: var(--lang-asm); +} + +.tab-badge { + display: inline-block; + min-width: 16px; + padding: 0 5px; + border-radius: 8px; + font-size: 11px; + font-weight: 600; + background: var(--paper-3); + color: var(--ink-2); +} + +.tab-badge.err { + background: var(--err-bg); + color: var(--err); +} + +.tab-badge.warn { + background: var(--warn-bg); + color: var(--warn); +} + +.tabs .spacer { + flex: 1; +} + +.tabs-tool { + font-size: 12px; + color: var(--ink-2); + padding: 0 4px 6px; + white-space: nowrap; +} + +.badge { + white-space: nowrap; +} + +.tab-toggle { + margin-left: auto; + font-size: 14px; + padding: 4px 10px; +} + +.inspect-tabs .tab, +.dock-tabs .tab { + font-size: 12.5px; + padding: 5px 10px; +} + +.inspect-tabs .tab-toggle { + margin-left: 4px; + padding: 3px 8px; +} + +/* the editor column */ +.pane-split { + flex: 1; + min-height: 0; + display: grid; + grid-template-columns: minmax(0, 1fr); + background: var(--paper-2); +} + +.pane-host { + min-height: 0; + display: flex; +} + +.pane-host .ed { + flex: 1; +} + +.pane-head { + display: flex; + align-items: center; + gap: 10px; + padding: 4px 12px; + border-bottom: 1px solid var(--line); + background: var(--paper); + font-size: 12px; + min-height: 30px; + flex-shrink: 0; +} + +.pane-note { + color: var(--ink-2); + min-width: 0; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.pane-note b { + font-weight: 600; + color: var(--ink); +} + +.tool-label.tool-check { + gap: 4px; + cursor: pointer; + white-space: nowrap; +} + +/* the side column: run setup, controls, next, variables, inspect */ +.setup { + border-bottom: 1px solid var(--line); + background: var(--paper); + flex-shrink: 0; +} + +.setup-head { + width: 100%; + display: flex; + align-items: center; + gap: 8px; + font: inherit; + font-size: 12px; + font-weight: 600; + color: var(--ink-2); + background: transparent; + border: 0; + padding: 6px 12px; + cursor: pointer; + text-align: left; +} + +.setup-head:hover { + color: var(--ink); +} + +.setup-caret { + width: 10px; + font-size: 10px; +} + +.setup-summary { + font-weight: 400; + font-family: var(--mono); + font-size: 11.5px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + min-width: 0; +} + +.setup-grid { + display: grid; + grid-template-columns: auto minmax(0, 1fr); + gap: 6px 10px; + align-items: start; + padding: 2px 12px 10px; +} + +.setup-label { + font-size: 12px; + color: var(--ink-2); + padding-top: 5px; + white-space: nowrap; +} + +.setup-grid .input, +.setup-grid .select { + width: 100%; + margin: 0; +} + +.setup-ta { + resize: vertical; + min-height: 44px; + line-height: 1.4; + font-size: 12.5px; + border: 1px solid var(--line-2); + border-radius: var(--r); + padding: 5px 8px; + background: var(--paper-2); + color: var(--ink); + font-family: var(--mono); + display: block; +} + +.run-bar { + padding: 6px 14px 4px; + border-bottom: 1px solid var(--line); + background: var(--paper); + flex-shrink: 0; + outline: none; + display: flex; + align-items: center; + gap: 16px; + flex-wrap: wrap; +} + +.run-bar .run-controls { + display: flex; + align-items: center; + gap: 14px; + flex: 1; + min-width: 0; + flex-wrap: wrap; +} + +.run-bar .run-controls .stepper { + flex: 1; + min-width: 320px; + margin: 0; +} + +.run-bar .run-controls .stepper-row2 { + margin: 0; +} + +.run-bar .run-status { + white-space: nowrap; +} + +.view-setup { + padding: 10px 14px 14px; +} + +.view-setup .setup-grid { + max-width: 760px; + padding: 0; +} + +.setup-note { + margin: 10px 0 0; + max-width: 76ch; +} + +.tab-note { + font-size: 11px; + color: var(--ink-3); + font-weight: 400; + max-width: 240px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.tab.active .tab-note { + color: var(--ink-2); +} + +.run-bar:focus-visible { + box-shadow: inset 0 0 0 2px var(--accent); +} + +.run-controls .stepper { + margin-bottom: 4px; +} + +.run-controls .stepper-row2 { + margin-bottom: 2px; +} + +.run-controls .stepper .btn, +.run-controls .stepper-row2 .btn { + padding: 3px 8px; + font-size: 12px; +} + +.run-status { + font-size: 11.5px; + color: var(--ink-2); + min-height: 0; + font-variant-numeric: tabular-nums; +} + +.run-status:empty { + display: none; +} + +.next-host { + padding: 8px 12px 0; + background: var(--paper); + flex-shrink: 0; + border-bottom: 1px solid var(--line); +} + +.next-host .trace-next { + margin-bottom: 8px; +} + +.next-host .predict { + margin-bottom: 8px; +} + +.side-split { + --right: 50%; + flex: 1; + min-height: 0; + min-width: 0; + display: grid; + grid-template-rows: minmax(60px, var(--right)) 6px minmax(60px, 1fr); + grid-template-columns: minmax(0, 1fr); +} + +.side-split.inspect-max { + grid-template-rows: minmax(60px, 1fr); +} + +.side-split.inspect-max .panel-vars, +.side-split.inspect-max>.splitter { + display: none; +} + +.panel { + min-height: 0; + min-width: 0; + display: flex; + flex-direction: column; + background: var(--paper-2); +} + +.panel-title { + font-size: 12px; + font-weight: 600; + color: var(--ink-2); + padding: 6px 12px; + border-bottom: 1px solid var(--line); + background: var(--paper); + flex-shrink: 0; +} + +.panel-body { + flex: 1; + min-height: 0; + overflow: auto; + padding: 8px 12px 16px; +} + +.vars-host .vars-tbl { + margin-bottom: 8px; +} + +.inspect-host { + padding: 0; + overflow: hidden; + display: flex; + flex-direction: column; +} + +.inspect-view { + padding: 8px 12px 16px; + flex: 1; + min-height: 0; + overflow: auto; +} + +.inspect-view.view { + padding: 10px 12px 20px; + display: flex; + flex-direction: column; +} + +.inspect-view.view>.viz-scroll { + flex: 1; + min-height: 0; + max-height: none; + min-width: 0; + width: 100%; + align-self: stretch; +} + +.inspect-view.view>.viz-head { + flex-shrink: 0; +} + +.legend { + font-size: 11.5px; + color: var(--ink-2); + position: relative; + align-self: center; + margin-bottom: 4px; +} + +.legend summary { + cursor: pointer; + list-style: none; + padding: 2px 8px; + border-radius: 10px; + border: 1px solid var(--line); +} + +.legend summary::-webkit-details-marker { + display: none; +} + +.legend[open] summary { + background: var(--paper-3); +} + +.legend-list { + position: absolute; + right: 0; + top: calc(100% + 4px); + z-index: 5; + background: var(--paper-2); + border: 1px solid var(--line); + border-radius: var(--r); + box-shadow: var(--shadow); + padding: 8px 10px; + display: grid; + gap: 4px; + min-width: 190px; +} + +.legend-item { + display: flex; + align-items: center; + gap: 8px; + white-space: nowrap; +} + +/* the dock */ +.dock { + min-height: 0; + display: flex; + flex-direction: column; + background: var(--paper-2); + border-top: 1px solid var(--line); +} + +.dock-body { + flex: 1; + min-height: 0; + overflow: auto; +} + +.view { + padding: 10px 14px 20px; +} + +.view-output { + padding: 8px 14px 14px; +} + +.view-output .trace-output { + margin: 0; + border: 0; + background: transparent; + padding: 0; + font-size: 13px; +} + +.output-empty { + margin: 0; +} + +.splitter { + background: var(--line); + cursor: col-resize; + position: relative; + touch-action: none; +} + +.splitter::after { + content: ''; + position: absolute; + inset: 0 -4px; +} + +.splitter:hover, +.splitter.dragging, +.splitter:focus-visible { + background: var(--accent); + outline: none; +} + +body.resizing { + cursor: col-resize; + user-select: none; +} + +body.resizing-y { + cursor: row-resize; +} + +.splitter-y { + cursor: row-resize; +} + +.splitter-y::after { + inset: -4px 0; +} + +body.resizing iframe, +body.resizing textarea { + pointer-events: none; +} + +/* narrow screens: everything stacks */ +@media (max-width: 900px) { + .shell { + height: auto; + min-height: 100%; + } + + .workspace { + display: flex; + flex-direction: column; + } + + .main { + display: flex; + flex-direction: column; + } + + .main>.splitter, + .workspace>.splitter, + .side-split>.splitter { + display: none; + } + + .panes { + min-height: 320px; + } + + .pane-host .ed { + min-height: 300px; + } + + .side-split { + display: flex; + flex-direction: column; + } + + .panel-body { + max-height: 360px; + } + + .dock-body { + max-height: 50vh; + } +} + +/* step colors: what a step does, the same everywhere */ +:root { + --k-write: #2f5bea; + --k-decision: #b5700d; + --k-loop: #7a3fc4; + --k-call: #0f7b6c; + --k-return: #1f9d63; + --k-io: #b4247a; + --k-life: #8a919c; + --k-error: #d64545; + --k-other: #c9cfd8; + --lang-lingo: #1f9d63; + --lang-matho: #b5700d; + --lang-pseudo: #2f5bea; + --lang-speco: #7a3fc4; + --lang-mojo: #e0592a; + --lang-asm: #5c6370; +} + +:root[data-theme="dark"] { + --k-write: #8db0ff; + --k-decision: #f0b860; + --k-loop: #c9a7ff; + --k-call: #5fd3c6; + --k-return: #5fd39a; + --k-io: #f49ac2; + --k-life: #7c8594; + --k-error: #ff8585; + --k-other: #3b4452; + --lang-mojo: #ff8a5c; + --lang-asm: #a7afbc; +} + +@media (prefers-color-scheme: dark) { + :root:not([data-theme="light"]):not([data-theme="dark"]) { + --k-write: #8db0ff; + --k-decision: #f0b860; + --k-loop: #c9a7ff; + --k-call: #5fd3c6; + --k-return: #5fd39a; + --k-io: #f49ac2; + --k-life: #7c8594; + --k-error: #ff8585; + --k-other: #3b4452; + --lang-mojo: #ff8a5c; + --lang-asm: #a7afbc; + } +} + +.k-dot { + display: inline-block; + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--k-other); + margin-right: 5px; + vertical-align: middle; + flex-shrink: 0; +} + +.k-dot.k-write { + background: var(--k-write); +} + +.k-dot.k-decision { + background: var(--k-decision); +} + +.k-dot.k-loop { + background: var(--k-loop); +} + +.k-dot.k-call { + background: var(--k-call); +} + +.k-dot.k-return { + background: var(--k-return); +} + +.k-dot.k-io { + background: var(--k-io); +} + +.k-dot.k-life { + background: var(--k-life); +} + +.k-dot.k-error { + background: var(--k-error); +} + +.trace-tbl tr.k-write td:first-child { + box-shadow: inset 3px 0 var(--k-write); +} + +.trace-tbl tr.k-decision td:first-child { + box-shadow: inset 3px 0 var(--k-decision); +} + +.trace-tbl tr.k-loop td:first-child { + box-shadow: inset 3px 0 var(--k-loop); +} + +.trace-tbl tr.k-call td:first-child { + box-shadow: inset 3px 0 var(--k-call); +} + +.trace-tbl tr.k-return td:first-child { + box-shadow: inset 3px 0 var(--k-return); +} + +.trace-tbl tr.k-io td:first-child { + box-shadow: inset 3px 0 var(--k-io); +} + +.trace-tbl tr.k-life td:first-child { + box-shadow: inset 3px 0 var(--k-life); +} + +.trace-tbl tr.k-error td:first-child { + box-shadow: inset 3px 0 var(--k-error); +} + +.trace-tbl .step-no { + white-space: nowrap; +} + +.trace-next.k-write { + border-left-color: var(--k-write); +} + +.trace-next.k-decision { + border-left-color: var(--k-decision); +} + +.trace-next.k-loop { + border-left-color: var(--k-loop); +} + +.trace-next.k-call { + border-left-color: var(--k-call); +} + +.trace-next.k-return { + border-left-color: var(--k-return); +} + +.trace-next.k-io { + border-left-color: var(--k-io); +} + +.trace-next.k-life { + border-left-color: var(--k-life); +} + +.trace-next.k-error { + border-left-color: var(--k-error); + background: var(--err-bg); +} + +.trace-next.k-done { + border-left-color: var(--ok); + background: var(--ok-bg); +} + +.trace-next.k-empty { + border-left-color: var(--line-2); + background: var(--paper-3); + color: var(--ink-2); +} + +/* ---------- editor (CodeMirror 6, vendored) ---------- */ +.ed { + position: relative; + display: flex; + min-height: 120px; + min-width: 0; + background: var(--paper-2); + font-family: var(--mono); + font-size: 13px; + line-height: 20px; + overflow: hidden; +} + +.ed .cm-editor { + flex: 1; + min-width: 0; + height: 100%; + outline: none !important; +} + +.ed .cm-scroller { + font: inherit; + line-height: inherit; + overflow: auto; +} + +.ed .cm-content { + padding: 8px 0; + caret-color: var(--ink); + tab-size: 4; +} + +.ed .cm-line { + padding: 0 12px; +} + +.ed .cm-gutters { + background: var(--paper); + border-right: 1px solid var(--line); + color: var(--ink-3); + font-size: 11.5px; + user-select: none; +} + +.ed .cm-gutterElement { + display: flex; + align-items: center; +} + +.ed .cm-lineNumbers .cm-gutterElement { + padding: 0 4px 0 6px; + justify-content: flex-end; + min-width: 28px; + cursor: pointer; +} + +.ed .cm-lineNumbers .cm-gutterElement:hover { + color: var(--ink); +} + +.ed .ed-g-marks .cm-gutterElement { + width: 16px; + justify-content: center; +} + +.ed .ed-g-hits .cm-gutterElement { + width: 34px; + justify-content: flex-end; + padding-right: 2px; +} + +.ed .ed-g-arrow .cm-gutterElement { + width: 16px; + justify-content: center; +} + +.ed .ed-mark { + cursor: pointer; + font-size: 9px; +} + +.ed .ed-mark-error { + color: var(--err); +} + +.ed .ed-mark-warning { + color: var(--warn); +} + +.ed .ed-mark-note { + color: var(--ink-3); +} + +.ed .ed-hits { + color: var(--ink-3); + font-size: 10.5px; +} + +.ed .ed-arrow { + color: var(--accent); + font-size: 10px; +} + +.ed .cm-gutterElement.ed-gcurrent { + background: var(--marker-bg); +} + +.ed .cm-lineNumbers .cm-gutterElement.ed-gbreak { + color: var(--err); + font-weight: 700; +} + +.ed .cm-lineNumbers .cm-gutterElement.ed-gbreak::before { + content: '●'; + font-size: 8px; + margin-right: 3px; +} + +.ed .cm-placeholder { + color: var(--ink-3); + opacity: .8; + font-style: normal; +} + +.ed .cm-content ::selection, +.ed .cm-selectionBackground { + background: rgba(47, 91, 234, .22) !important; +} + +.ed .cm-cursor { + border-left-color: var(--ink); +} + +.ed .cm-matchingBracket { + background: var(--accent-bg); + outline: 1px solid var(--line-2); +} + +.ed .cm-nonmatchingBracket { + color: var(--err); +} + +.ed .cm-selectionMatch { + background: rgba(246, 196, 83, .35); +} + +.ed .cm-searchMatch { + background: var(--marker-bg); + outline: 1px solid var(--marker); +} + +.ed .cm-searchMatch-selected { + background: var(--marker); +} + +.ed .cm-panels { + background: var(--paper); + border-bottom: 1px solid var(--line); + color: var(--ink); + font-family: var(--sans); + font-size: 12px; +} + +.ed .cm-panel.cm-search { + padding: 6px 10px; +} + +.ed .cm-panel.cm-search input, +.ed .cm-panel.cm-search button { + font: inherit; + font-size: 12px; + border: 1px solid var(--line-2); + border-radius: 4px; + background: var(--paper-2); + color: var(--ink); + padding: 2px 6px; + margin: 0 4px 2px 0; +} + +.ed .cm-panel.cm-search label { + margin-right: 8px; +} + +.ed-ro .cm-content { + cursor: default; +} + +.ed-ro .cm-cursor { + display: none; +} + + +.ed-compact { + font-size: 12px; + line-height: 18px; +} + +.ed .ed-line-error { + box-shadow: inset 0 -2px var(--err); +} + +.ed .ed-line-warning { + box-shadow: inset 0 -1px var(--warn); +} + +.ed .ed-current { + background: var(--marker-bg); + box-shadow: inset 3px 0 var(--marker); +} + +.ed .ed-last { + background: var(--last-bg); +} + +.ed .ed-linked { + outline: 2px solid var(--accent); + outline-offset: -2px; +} + +.ed-msg { + font-style: italic; + font-size: 11.5px; + opacity: .9; + pointer-events: none; +} + +.ed-msg-error { + color: var(--err); +} + +.ed-msg-warning { + color: var(--warn); +} + +.ed-msg-note { + color: var(--ink-3); +} + +.tok-keyword { + color: var(--tok-keyword); + font-weight: 600; +} + +.tok-builtin { + color: var(--tok-builtin); +} + +.tok-string { + color: var(--tok-string); +} + +.tok-number { + color: var(--tok-number); +} + +.tok-comment { + color: var(--tok-comment); + font-style: italic; +} + +.tok-label { + color: var(--tok-label); + font-weight: 600; +} + +.tok-op { + color: var(--ink-2); +} + +.tok-error { + color: var(--err); + text-decoration: underline wavy; + text-decoration-skip-ink: none; +} + +.tok-punct { + color: var(--ink-3); +} + +/* Mojo: the words of ownership stand out, since they are what Programming+ teaches about Mojo */ +.tok-convention { + color: var(--tok-keyword); + font-style: italic; + font-weight: 600; +} + +.tok-transfer { + color: var(--accent); + font-weight: 700; +} + +.tok-name { + color: var(--ink); +} + +/* ---------- step through ---------- */ +.stepper { + display: flex; + align-items: center; + gap: 6px; + flex-wrap: wrap; + margin-bottom: 6px; +} + +.stepper .btn { + min-width: 34px; +} + +.stepper-slider { + flex: 1; + min-width: 120px; + accent-color: var(--accent); +} + +.stepper-count { + font-size: 12.5px; + color: var(--ink-2); + white-space: nowrap; + font-variant-numeric: tabular-nums; +} + +.stepper-row2 { + display: flex; + align-items: center; + gap: 6px; + flex-wrap: wrap; + margin-bottom: 8px; + font-size: 12.5px; + color: var(--ink-2); +} + +.speed { + width: 90px; + accent-color: var(--accent); +} + +.trace-status { + font-size: 12.5px; + color: var(--ink-2); + /* one line, filled or empty: an empty status had a shorter box than a full one, so the stepper moved 4px */ + line-height: 19px; + height: 19px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + margin-bottom: 6px; +} + +.trace-next { + background: var(--marker-bg); + border-left: 3px solid var(--marker); + padding: 6px 10px; + border-radius: 4px; + margin-bottom: 10px; + font-size: 13px; +} + +.trace-next .mono { + font-size: 12.5px; +} + +/* What runs next holds one height on every step: two lines, each cut with an ellipsis instead of wrapping + (the tooltip has the whole text). A message on its own, such as the end of the run, may use both lines. */ +.trace-next { + /* two line boxes of 19px; the padding comes on top (content-box) */ + line-height: 19px; + height: 38px; + box-sizing: content-box; + overflow: hidden; +} + +.trace-next-line { + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 1; + overflow: hidden; + overflow-wrap: anywhere; +} + +.trace-next-line:only-child { + -webkit-line-clamp: 2; +} + +.trace-next-sub { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.predict { + background: var(--paper-3); + border: 1px solid var(--line); + border-radius: var(--r); + padding: 8px 10px; + margin-bottom: 10px; + font-size: 13px; +} + +.predict-row { + display: flex; + gap: 6px; + align-items: center; + flex-wrap: wrap; + margin-top: 6px; +} + +.predict-score { + font-size: 12px; + color: var(--ink-2); + margin-left: auto; +} + +.predict-right { + color: var(--ok); + font-weight: 600; +} + +.predict-wrong { + color: var(--err); + font-weight: 600; +} + +.trace-output { + background: var(--paper); + border: 1px solid var(--line); + border-radius: var(--r); + padding: 8px 10px; + margin: 10px 0 0; + font-size: 12.5px; + white-space: pre-wrap; + font-family: var(--mono); +} + +.trace-cols { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 16px; +} + +@media (max-width: 1100px) { + .trace-cols { + grid-template-columns: 1fr; + } +} + +.trace-col { + min-width: 0; +} + +.trace-empty { + padding: 12px 0; +} + +.tbl { + border-collapse: collapse; + width: 100%; + font-size: 12.5px; +} + +.tbl caption { + text-align: left; + font-weight: 600; + font-size: 12px; + color: var(--ink-2); + padding: 4px 0; +} + +.tbl th { + text-align: left; + font-weight: 600; + font-size: 11.5px; + color: var(--ink-2); + padding: 3px 6px; + border-bottom: 1px solid var(--line); +} + +.tbl td { + padding: 3px 6px; + border-bottom: 1px solid var(--line); + vertical-align: top; +} + +.trace-tbl tr { + cursor: pointer; +} + +.trace-tbl tr:hover td { + background: var(--paper-3); +} + +.row-last td { + background: var(--last-bg); +} + +.row-next td { + background: var(--marker-bg); +} + +.just-wrote td, +.just-wrote { + background: var(--last-bg); +} + +.about-to-read td { + box-shadow: inset 3px 0 var(--marker); +} + +.vars-tbl { + margin-bottom: 10px; +} + +.var-hist { + color: var(--ink-3); + font-size: 11.5px; +} + +.var-hist .linkish { + color: var(--ink-2); +} + +.var-ruler { + padding: 2px 6px 6px; +} + +.flags { + display: flex; + gap: 6px; +} + +.flag { + font-family: var(--mono); + font-size: 12px; + padding: 2px 8px; + border: 1px solid var(--line); + border-radius: 4px; + color: var(--ink-2); +} + +.flag.on { + background: var(--accent-bg); + color: var(--accent); + border-color: transparent; + font-weight: 600; +} + +.flag.just-wrote { + outline: 2px solid var(--accent); +} + +.mem-region { + margin-bottom: 8px; +} + +.mem-label { + font-size: 11.5px; + color: var(--ink-2); + margin-bottom: 2px; + font-family: var(--mono); +} + +.mem-cells { + display: flex; + flex-wrap: wrap; + gap: 2px; +} + +.mem-cell { + display: inline-flex; + flex-direction: column; + align-items: center; + width: 26px; + border: 1px solid var(--line); + border-radius: 3px; + font-family: var(--mono); + line-height: 1.1; + padding: 2px 0; +} + +.mem-cell b { + font-weight: 600; + font-size: 12px; +} + +.mem-cell i { + font-style: normal; + font-size: 9.5px; + color: var(--ink-2); +} + +.mem-cell.touched { + background: var(--marker-bg); + border-color: var(--marker); +} + +.explain ul { + margin: 4px 0 0; + padding-left: 18px; +} + +/* ---------- other views ---------- */ +.problems, +.obligations, +.failures, +.facts { + list-style: none; + margin: 0; + padding: 0; +} + +.problem { + display: grid; + grid-template-columns: 14px auto 1fr auto auto; + gap: 8px; + align-items: start; + padding: 7px 0; + border-bottom: 1px solid var(--line); + font-size: 13px; +} + +.problem-sev { + font-size: 10px; + padding-top: 3px; +} + +.problem-error .problem-sev { + color: var(--err); +} + +.problem-warning .problem-sev { + color: var(--warn); +} + +.problem-note .problem-sev { + color: var(--ink-3); +} + +.problem-guide { + font-size: 12px; + white-space: nowrap; +} + +.problem-question { + grid-column: 3 / -1; + background: var(--paper); + border: 1px solid var(--line); + border-radius: var(--r); + padding: 6px 10px; +} + +.problem-q { + font-size: 12.5px; + color: var(--ink-2); +} + +.proof-counts { + margin-bottom: 10px; +} + +.proof-unit { + margin-bottom: 10px; + border: 1px solid var(--line); + border-radius: var(--r); + padding: 6px 10px; +} + +.proof-unit summary { + cursor: pointer; + font-size: 13px; +} + +.obligation { + display: grid; + grid-template-columns: auto auto 1fr; + gap: 8px; + align-items: baseline; + padding: 6px 0; + border-top: 1px solid var(--line); + font-size: 13px; +} + +.ob-detail { + grid-column: 1 / -1; + font-size: 12.5px; +} + +.ob-detail summary { + color: var(--ink-2); + cursor: pointer; + font-size: 12px; +} + +.facts li { + padding: 1px 0 1px 12px; +} + +.goal { + padding: 2px 0 2px 12px; + font-weight: 600; +} + +.tests-unit { + margin-bottom: 14px; +} + +.failures li { + padding: 3px 0; + font-size: 13px; +} + +.perf-tbl { + max-width: 520px; +} + +.perf-tbl td:first-child { + color: var(--ink-2); +} + +.bounds { + padding-left: 18px; +} + +.compile-out { + border-bottom: 1px solid var(--line); + background: var(--paper); + padding: 8px 12px; + max-height: 45%; + overflow: auto; + font-size: 12.5px; +} + +.compile-head { + display: flex; + gap: 10px; + align-items: center; + margin-bottom: 6px; +} + +.compile-err { + color: var(--err); + white-space: pre-wrap; + margin: 0 0 6px; + font-size: 12px; +} + +.compile-std { + white-space: pre-wrap; + margin: 0 0 6px; + font-size: 12px; +} + +.compile-section { + margin: 10px 0 14px; +} + +.compile-section h4 { + margin: 0 0 6px; + font-size: 13px; +} + +.asm-fn, +.asm-library { + border: 1px solid var(--line); + border-radius: 6px; + padding: 4px 8px; + margin: 6px 0; +} + +.asm-fn summary, +.asm-library summary { + cursor: pointer; + font-size: 12px; +} + +.asm-fn-library, +.asm-fn-entry { + border-style: dashed; +} + +.asm-fn-actions { + display: flex; + gap: 6px; + margin: 4px 0; +} + +.asm-src { + color: var(--ink-3); + user-select: none; +} + +button.asm-src { + font: inherit; + padding: 0; + border: 0; + background: none; + cursor: pointer; +} + +button.asm-src:hover { + color: var(--accent); +} + +.compile-asm { + margin: 0; + font-family: var(--mono); + font-size: 12px; + line-height: 1.4; + white-space: pre; +} + +/* ---------- dialogs, tooltip ---------- */ +.share { + border: 1px solid var(--line); + border-radius: var(--r-lg); + padding: 18px 20px; + width: min(720px, 92vw); + background: var(--paper-2); + color: var(--ink); + box-shadow: var(--shadow); +} + +.share::backdrop { + background: rgba(10, 12, 18, .4); +} + +.share h3 { + font-size: 17px; +} + +.share-row { + display: grid; + grid-template-columns: 110px 1fr auto; + gap: 8px; + align-items: center; + margin: 8px 0; +} + +.share-row label { + font-size: 12.5px; + color: var(--ink-2); +} + +.share-actions { + text-align: right; + margin-top: 10px; + display: flex; + gap: 8px; + justify-content: flex-end; +} + +.keys { + display: grid; + grid-template-columns: auto 1fr; + gap: 6px 14px; + font-size: 13px; + align-items: center; +} + +.tip { + position: fixed; + z-index: 50; + background: var(--paper-2); + color: var(--ink); + border: 1px solid var(--line); + border-radius: var(--r); + padding: 8px 10px; + box-shadow: var(--shadow); + font-size: 12.5px; + line-height: 1.4; + pointer-events: none; +} + +.tip-title { + display: flex; + justify-content: space-between; + gap: 12px; + margin-bottom: 3px; +} + +.tip-title code { + font-weight: 600; + font-size: 12.5px; +} + +.tip-where { + color: var(--ink-2); + font-size: 11px; +} + +/* ---------- reference ---------- */ +.reference { + margin: 36px 0 24px; +} + +.ref-nav { + display: flex; + gap: 14px; + flex-wrap: wrap; + margin: 6px 0 14px; + font-size: 13.5px; +} + +.ref-lang { + border: 1px solid var(--line); + border-radius: var(--r-lg); + background: var(--paper-2); + margin-bottom: 10px; +} + +.ref-lang>summary { + list-style: none; + cursor: pointer; + padding: 12px 16px; + display: flex; + gap: 12px; + align-items: baseline; + flex-wrap: wrap; +} + +.ref-lang>summary::-webkit-details-marker { + display: none; +} + +.ref-lang>summary::before { + content: '▸'; + color: var(--ink-3); + font-size: 12px; +} + +.ref-lang[open]>summary::before { + content: '▾'; +} + +.ref-lang>summary h3 { + margin: 0; + font-size: 16px; +} + +.ref-body { + padding: 0 16px 16px; +} + +.ref-toc { + display: flex; + gap: 12px; + flex-wrap: wrap; + font-size: 12.5px; + margin-bottom: 8px; +} + +.ref-section { + margin-top: 18px; +} + +.ref-section h4 { + font-size: 14px; + color: var(--ink); +} + +.ref-table { + border-collapse: collapse; + width: 100%; + font-size: 13px; +} + +.ref-table th { + text-align: left; + font-size: 11.5px; + color: var(--ink-2); + font-weight: 600; + padding: 4px 8px; + border-bottom: 1px solid var(--line); +} + +.ref-table td { + padding: 6px 8px; + border-bottom: 1px solid var(--line); + vertical-align: top; +} + +.ref-term { + white-space: nowrap; + max-width: 320px; +} + +.ref-term code { + white-space: pre-wrap; + font-size: 12.5px; +} + +.ref-meaning { + min-width: 220px; +} + +.ref-extra { + min-width: 200px; +} + +.ref-code { + margin: 0; + font-family: var(--mono); + font-size: 12px; + line-height: 1.4; + white-space: pre; + background: var(--paper); + border: 1px solid var(--line); + border-radius: 5px; + padding: 6px 8px; + overflow-x: auto; + max-width: 520px; +} + +/* ---------- embed ---------- */ +.embed { + display: flex; + flex-direction: column; + height: 100%; + min-height: 100vh; + font-size: 13px; +} + +.embed-title { + display: flex; + justify-content: space-between; + align-items: center; + padding: 6px 12px; + border-bottom: 1px solid var(--line); + font-size: 12.5px; +} + +.embed-open { + font-size: 12px; +} + +.embed-reset { + margin-left: auto; + margin-right: 10px; +} + +.embed-pane-label { + font-size: 12px; + color: var(--ink-2); + padding: 6px 12px 0; +} + +.embed .ed { + min-height: 120px; + max-height: 45vh; + border-bottom: 1px solid var(--line); +} + +.embed-row { + display: flex; + gap: 6px; + align-items: center; + padding: 6px 12px; + border-bottom: 1px solid var(--line); +} + +.embed-call { + flex: 1; +} + +.embed-panel { + flex: 1; + overflow: auto; +} + +.embed .trace-cols { + grid-template-columns: 1fr; +} + +.embed-foot { + display: none; +} + +/* A fixed-height embed: the editors on top, the panel below, a draggable divider between them. + --embed-top (set by the divider) is the editors' share; they take most of the frame by default. */ +.embed:not(.embed-autosize) { + height: 100vh; + min-height: 0; +} + +.embed-split { + --embed-top: 70%; + flex: 1; + min-height: 0; + display: grid; + grid-template-rows: minmax(0, calc(var(--embed-top) - 3px)) 6px minmax(0, 1fr); +} + +.embed-top { + display: flex; + flex-direction: column; + min-height: 0; + overflow: hidden; +} + +.embed-top>.embed-pane-label, +.embed-top>.embed-row { + flex: none; +} + +.embed-split .embed-top .ed { + flex: 1 1 0; + min-height: 48px; + max-height: none; + border-bottom: 0; +} + +.embed-top>.embed-row { + border-top: 1px solid var(--line); + border-bottom: 0; +} + +.embed-split>.splitter-y::before { + content: ''; + position: absolute; + left: 50%; + top: 50%; + width: 36px; + height: 2px; + margin: -1px 0 0 -18px; + border-radius: 1px; + background: var(--ink-3); + opacity: .6; +} + +.embed-split>.embed-panel { + min-height: 0; + overflow: auto; +} + +/* height="auto" embeds: the content decides the height, and the host grows the frame to match */ +.embed-autosize { + min-height: 0; + height: auto; +} + +.embed-autosize .ed { + max-height: none; +} + +.embed-autosize .embed-panel { + flex: none; + overflow: visible; +} + +.embed-autosize .viz-scroll { + max-height: none; +} + +@media (max-width: 900px) { + .workspace { + grid-template-columns: 1fr !important; + grid-template-rows: minmax(0, 1fr) 6px minmax(0, 1fr); + } + + .workspace>.splitter { + cursor: row-resize; + } + + .workspace.views-collapsed { + grid-template-rows: minmax(0, 1fr) 6px 40px; + } + + .workspace.views-collapsed .view-tabs { + flex-direction: row; + height: auto; + } + + .workspace.views-collapsed .view-tabs .tab { + writing-mode: horizontal-tb; + transform: none; + } + + .input { + min-width: 140px; + } + + .hero { + grid-template-columns: 1fr; + gap: 24px; + } + + .hero h1 { + font-size: 34px; + } + + .ways { + grid-template-columns: 1fr 1fr; + } + + .ref-table, + .ref-table thead, + .ref-table tbody, + .ref-table tr, + .ref-table td { + display: block; + } + + .ref-table th { + display: none; + } + + .ref-term { + white-space: normal; + } +} + +@media (max-width: 560px) { + .ways { + grid-template-columns: 1fr; + } + + .home { + padding: 0 16px 48px; + } +} + +.way pre { + max-height: 150px; + -webkit-mask-image: linear-gradient(#000 70%, transparent); + mask-image: linear-gradient(#000 70%, transparent); +} + +/* ------------------------------------------------------------------ */ +/* Home: pitch sections */ +/* ------------------------------------------------------------------ */ +.home-nav a.on { + color: var(--ink); + font-weight: 600; +} + +.lede-2 { + color: var(--ink-2); + max-width: 72ch; + margin: 0 0 20px; + font-size: 15px; + line-height: 1.55; +} + +.hub { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 1.35fr) minmax(0, 1fr); + gap: 12px; + align-items: stretch; +} + +.hub-col { + display: grid; + gap: 12px; + align-content: stretch; +} + +.hub .way { + display: flex; + flex-direction: column; +} + +.hub .way p { + min-height: 0; + flex: 0 0 auto; +} + +.hub .way pre { + flex: 1; +} + +.hub-center { + border: 1px solid var(--ink); + border-radius: var(--r-lg); + background: var(--paper-2); + padding: 16px 16px 12px; + min-width: 0; + box-shadow: var(--shadow); + position: relative; +} + +.hub-center::before { + content: ""; + position: absolute; + inset: -1px; + border-radius: inherit; + pointer-events: none; + box-shadow: 0 0 0 3px var(--marker-bg); +} + +.hub-center h3 { + font-size: 20px; + margin: 0 0 4px; + letter-spacing: -.01em; +} + +.hub-center>p { + margin: 0 0 10px; + font-size: 13px; + color: var(--ink-2); +} + +.hub-center pre { + margin: 0; + font-family: var(--mono); + font-size: 12px; + line-height: 1.6; + white-space: pre; + overflow-x: auto; + border-top: 1px solid var(--line); + padding-top: 10px; +} + +.demo-out { + margin: 0; + padding: 6px 10px; + font-family: var(--mono); + font-size: 12.5px; + white-space: pre-wrap; + border: 1px solid var(--line); + border-radius: var(--r); + background: var(--paper-2); + max-height: 140px; + overflow: auto; + grid-column: 1 / -1; +} + +.demo-stop { + color: var(--err); +} + +.demo-frame { + color: var(--accent); + font-weight: 600; +} + +.ref-prints { + display: block; + margin-top: 4px; +} + +.input-lines { + resize: none; + min-height: 30px; + line-height: 1.4; + padding: 5px 8px; +} + +@media (max-width: 900px) { + .hub { + grid-template-columns: 1fr; + } + + .hub-center { + order: -1; + } +} + +.demo-vars>span { + display: inline-flex; + align-items: center; + gap: 6px; +} + +.demo-vars .ruler { + display: inline-flex; +} + +.demo-foot { + display: flex; + flex-direction: column; + gap: 8px; + align-items: stretch; +} + +.demo-ctl { + display: flex; + gap: 4px; + flex-wrap: wrap; + align-items: center; +} + +.demo-ctl .btn { + white-space: nowrap; +} + +.demo-ctl a.btn { + margin-left: auto; +} + +.toolbar .input-lines { + min-width: 120px; + width: 180px; +} + +.toolbar:has(.input-lines) .input { + min-width: 170px; +} + +@media (max-width: 560px) { + .home-nav { + flex-wrap: wrap; + gap: 10px 12px; + } + + .home-nav .brand { + flex-basis: 100%; + } + + .home-nav .spacer { + display: none; + } +} + +/* ---------- pictures of the procedure: flowchart, data flow, trace table ---------- */ +.viz-head { + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap; + margin-bottom: 8px; + font-size: 12.5px; +} + +.viz-title { + font-family: var(--mono); + font-weight: 600; +} + +.viz-scroll { + overflow: auto; + max-width: 100%; + border: 1px solid var(--line); + border-radius: var(--r-lg); + background: var(--paper-2); + padding: 8px; +} + +.flow-svg { + display: block; + font-family: var(--mono); + font-size: 12px; +} + +.flow-svg text { + fill: var(--ink); +} + +.flow-shape { + stroke: var(--ink-2); + stroke-width: 1.2; +} + +.flow-term { + stroke-width: 2; +} + +.flow-edge { + fill: none; + stroke: var(--ink-2); + stroke-width: 1.4; +} + +.flow-back { + stroke-dasharray: 4 3; +} + +.flow-arrowhead { + fill: var(--ink-2); +} + +.flow-badge { + fill: var(--paper-3); + stroke: var(--line); +} + +.flow-badge-never { + fill: var(--warn-bg); + stroke: var(--warn); +} + +.flow-badge-text { + font-size: 10.5px; + fill: var(--ink-2); +} + +.flow-never .flow-shape { + stroke-dasharray: 3 3; + stroke: var(--ink-3); +} + +.flow-never text { + fill: var(--ink-3); +} + +.flow-edge-label { + font-size: 10.5px; + fill: var(--ink-2); +} + +.flow-edge-label-bg { + fill: var(--paper-2); +} + +.flow-clickable { + cursor: pointer; +} + +.flow-clickable:hover .flow-shape, +.flow-clickable:hover .df-node { + stroke: var(--accent); + stroke-width: 2; +} + +.df-node { + stroke: var(--ink-2); + stroke-width: 1.2; + fill: var(--paper-2); +} + +.df-node-in { + fill: var(--accent-bg); +} + +.df-node-out { + fill: var(--ok-bg); +} + +.df-node-loop { + stroke-dasharray: 5 3; +} + +.df-edge { + fill: none; + stroke: var(--ink-2); + stroke-width: 1.4; +} + +.df-edge-ctrl { + stroke-dasharray: 4 3; + stroke: var(--ink-3); +} + +.df-type { + font-size: 10px; + fill: var(--ink-3); +} + +.df-label { + font-size: 10px; + fill: var(--ink-2); +} + +.df-label-bg { + fill: var(--paper-2); +} + +.vals-scroll { + padding: 0; +} + +.vals-tbl { + border-collapse: collapse; + font-family: var(--mono); + font-size: 12px; + min-width: 100%; +} + +.vals-tbl th, +.vals-tbl td { + border: 1px solid var(--line); + padding: 3px 8px; + text-align: left; + white-space: nowrap; +} + +.vals-tbl thead th { + background: var(--paper-3); + color: var(--ink-2); + font-weight: 500; + text-align: center; + position: sticky; + top: 0; +} + +.vals-tbl thead tr:nth-child(2) th { + top: 25px; + font-size: 11px; +} + +.vals-corner, +.vals-var { + position: sticky; + left: 0; + background: var(--paper-3); + z-index: 1; + text-align: left !important; + font-weight: 600; +} + +.vals-tbl thead .vals-corner { + z-index: 2; +} + +.vals-step.linkish { + cursor: pointer; + text-decoration: underline dotted; +} + +.vals-changed { + font-weight: 600; + background: var(--accent-bg); +} + +.vals-same { + color: var(--ink-3); +} + +.vals-absent { + background: repeating-linear-gradient(45deg, transparent 0 4px, var(--paper-3) 4px 5px); +} + +.vals-unset { + color: var(--ink-3); + font-weight: 400; +} + +.vals-out { + background: var(--ok-bg); +} + +.view-table .viz-scroll, +.view-flow .viz-scroll, +.view-data .viz-scroll { + max-height: calc(100vh - 220px); +} + +.embed .viz-scroll { + max-height: none; +} + +/* The Lifetimes view: one lane per value, from made to destroyed or moved out */ +.life { + display: grid; + gap: 6px; + margin: 8px 0; +} + +.life-row { + display: grid; + grid-template-columns: minmax(120px, 18%) 1fr minmax(140px, 20%); + gap: 10px; + align-items: center; +} + +.life-id { + color: var(--ink-3); + font-size: 11px; +} + +.life-lane { + position: relative; + height: 22px; + border-bottom: 1px dashed var(--line); +} + +.life-bar { + position: absolute; + top: 7px; + height: 8px; + border-radius: 4px; + background: var(--accent); + opacity: 0.35; +} + +.life-bar-copied { + background: var(--tok-string); +} + +.life-bar-moved { + background: var(--tok-number); +} + +.life-bar-open { + border-top-right-radius: 0; + border-bottom-right-radius: 0; +} + +.life-mark { + position: absolute; + top: 4px; + width: 14px; + height: 14px; + margin-left: -7px; + padding: 0; + border: 2px solid var(--paper); + border-radius: 50%; + cursor: pointer; + background: var(--accent); +} + +.life-mark.legend { + position: relative; + display: inline-block; + top: 3px; + margin: 0 2px 0 8px; + cursor: default; +} + +.life-mark-copied { + background: var(--tok-string); +} + +.life-mark-moved { + background: var(--tok-number); +} + +.life-mark-moved-out { + background: var(--ink-3); + border-radius: 2px; +} + +.life-mark-named { + background: var(--paper); + border-color: var(--accent); + width: 10px; + height: 10px; + top: 6px; + margin-left: -5px; +} + +.life-mark-destroyed { + background: var(--err); + border-radius: 2px; +} + +.life-cursor { + position: absolute; + top: 0; + bottom: 0; + width: 2px; + margin-left: -1px; + background: var(--ink-2); + opacity: 0.5; + pointer-events: none; +} + +.life-legend { + margin-top: 8px; +} + +/* The Compiler view, by Mojo line: each line of the program, then the instructions it became */ +.asm-group { + border-left: 3px solid transparent; + padding: 2px 0 4px 8px; + margin: 4px 0; +} + +.asm-group-head { + display: flex; + gap: 10px; + align-items: baseline; +} + +.asm-group-src { + color: var(--ink-2); +} + +.asm-group-active { + border-left-color: var(--accent); + background: var(--paper-2); +} + +/* Two builds of one function, side by side */ +.build-pair { + margin: 10px 0; +} + +.build-cols { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 12px; +} + +.build-col { + min-width: 0; + overflow-x: auto; +} + +.cost-by-line { + margin-bottom: 14px; +} + +/* ------------------------------------------------------------------ */ +/* Home: Mojo-first pitch (features, mental model, specification) */ +/* ------------------------------------------------------------------ */ +.sample { + margin: 0; + font-family: var(--mono); + font-size: 11.5px; + line-height: 1.55; + white-space: pre; + overflow: hidden; + text-overflow: ellipsis; + color: var(--ink); +} + +.features { + padding: 40px 0 8px; + border-bottom: 1px solid var(--line); +} + +.features h2, +.spec-section h2 { + font-size: 24px; + letter-spacing: -.02em; + margin-bottom: 6px; +} + +.feat-grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 14px; + margin-bottom: 36px; +} + +.feat { + border: 1px solid var(--line); + border-radius: var(--r-lg); + background: var(--paper-2); + padding: 16px 16px 14px; + min-width: 0; + display: flex; + flex-direction: column; + gap: 8px; +} + +.feat h3 { + font-size: 15px; + margin: 0; +} + +.feat>p { + margin: 0; + font-size: 13px; + color: var(--ink-2); + flex: 0 0 auto; +} + +.feat>p+* { + margin-top: auto; + border-top: 1px solid var(--line); + padding-top: 10px; +} + +.feat-diags { + list-style: none; + margin: 8px 0 0; + padding: 0; + font-size: 12px; +} + +.feat-diag { + display: flex; + gap: 6px; + align-items: baseline; + margin-bottom: 4px; +} + +.feat-diag-sev { + font-size: 9px; +} + +.feat-diag-error .feat-diag-sev { + color: var(--err); +} + +.feat-diag-note .feat-diag-sev, +.feat-diag-note { + color: var(--ink-3); +} + +.feat-steps { + list-style: none; + margin: 0; + padding: 0; + font-size: 12px; +} + +.feat-steps li { + display: flex; + align-items: baseline; + gap: 4px; + padding: 2px 0; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.feat-steps code { + font-size: 11.5px; +} + +.feat-legend { + display: flex; + flex-wrap: wrap; + gap: 4px 12px; + font-size: 11px; + color: var(--ink-2); + margin-top: 8px; +} + +.feat-verdict { + display: flex; + flex-wrap: wrap; + gap: 6px; + align-items: center; +} + +.feat-verdict p { + margin: 4px 0 0; + flex-basis: 100%; +} + +.feat-tests { + font-size: 12.5px; + display: grid; + gap: 8px; +} + +.ways-3 { + grid-template-columns: repeat(3, minmax(0, 1fr)); + margin-bottom: 20px; +} + +.ways-3 .way pre { + font-size: 11.5px; +} + + +.spec-section { + display: grid; + grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr); + gap: 32px; + align-items: center; + padding: 36px 0; + border-top: 1px solid var(--line); + border-bottom: 1px solid var(--line); +} + +.spec-section .way { + padding: 16px; +} + +.spec-section .proof-counts { + margin-top: 12px; +} + +.chip-verified { + background: var(--ok-bg); + color: var(--ok); +} + +@media (max-width: 900px) { + + .feat-grid, + .ways { + grid-template-columns: 1fr; + } + + .spec-section { + grid-template-columns: 1fr; + } +} + +/* the variable's timeline: every value it takes, past, now, and to come */ +.var-track { + display: flex; + flex-wrap: wrap; + gap: 3px; + margin-top: 4px; + align-items: center; +} + +.var-chip { + font: inherit; + font-family: var(--mono); + font-size: 11px; + line-height: 1.2; + padding: 1px 6px; + border-radius: 999px; + border: 1px solid var(--line); + background: var(--paper); + color: var(--ink-2); + cursor: pointer; + max-width: 160px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.var-chip-past { + background: var(--paper-3); + color: var(--ink); +} + +.var-chip-now { + background: var(--accent); + border-color: var(--accent); + color: var(--accent-ink); + font-weight: 600; +} + +.var-chip-next { + opacity: .45; + border-style: dashed; +} + +.var-chip:hover { + opacity: 1; + border-color: var(--accent); +} + +.var-chip-more { + border: 0; + background: transparent; + cursor: default; + color: var(--ink-3); +} + +/* the flowchart follows the stepper */ +.flow-node.flow-current .flow-shape { + stroke: var(--marker); + stroke-width: 3; +} + +.flow-node.flow-last .flow-shape { + stroke: var(--accent); + stroke-width: 2.4; +} + +.flow-node.flow-current.flow-last .flow-shape { + stroke: var(--marker); +} + +/* the data flow lights up what the step reads and writes */ +.df-nodeg.df-reads .df-node { + stroke: var(--marker); + stroke-width: 3; +} + +.df-nodeg.df-wrote .df-node { + stroke: var(--accent); + stroke-width: 3; +} + +.df-edge.df-edge-active { + stroke: var(--accent); + stroke-width: 2.6; +} + +/* the table of values marks the step that just ran */ +.vals-tbl .vals-now { + box-shadow: inset 0 -3px var(--marker); +} + +.vals-tbl td.vals-now { + background: var(--marker-bg); + box-shadow: none; +} +.embed-pane-label .badge, +.share-badges .badge { + margin-left: 6px; +} + +.share-badges { + display: inline-flex; + flex-wrap: wrap; + gap: 4px; +} + +.practices { + list-style: none; + margin: 0; + padding: 0; + display: grid; + gap: 8px; +} + +.practice { + border: 1px solid var(--line); + border-radius: 6px; + padding: 8px 10px; + cursor: pointer; +} + +.practice:hover { + border-color: var(--ink-2); +} + +.practice p { + margin: 4px 0; +} + +.practice-head { + display: flex; + justify-content: space-between; + gap: 8px; +} + +.practice-diff { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 8px; +} + +.practice-diff pre { + margin: 0; + padding: 6px 8px; + border-radius: 4px; + overflow: auto; + background: var(--panel, transparent); + border: 1px solid var(--line); +} + +.practice-after { + border-color: var(--ok, currentColor); +} + +.problem-origin { + font-size: 12px; + color: var(--ink-2); +} + +.idiomatic { + flex-basis: 100%; + margin: 4px 0 0; +} + +.idiomatic-head { + display: flex; + align-items: center; + gap: 8px; +} + +.idiomatic-code { + margin: 4px 0 0; + padding: 6px 8px; + max-height: 240px; + overflow: auto; + border: 1px solid var(--line); + border-radius: 4px; +} + +.btn-on { + color: var(--ok); +} + +.banner { + display: flex; + align-items: center; + gap: 10px; + padding: 6px 14px; + background: var(--warn-bg); + color: var(--warn); + border-bottom: 1px solid var(--line); + font-size: 13px; +} + +.versions { + position: relative; +} + +.versions-menu { + position: absolute; + z-index: 30; + top: calc(100% + 4px); + left: 0; + width: min(420px, 90vw); + max-height: 60vh; + overflow: auto; + padding: 6px; + background: var(--paper); + border: 1px solid var(--line-2); + border-radius: 8px; + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.18); +} + +.version-row { + display: flex; + align-items: center; + gap: 4px; + padding: 2px 4px; + border-radius: 4px; +} + +.version-row.on { + background: var(--ok-bg); +} + +.version-pick { + flex: 1; + display: flex; + flex-direction: column; + align-items: flex-start; + text-align: left; + border: 0; + background: none; + color: inherit; + font: inherit; + padding: 4px; + cursor: pointer; + min-width: 0; +} + +.version-pick:hover .version-name { + text-decoration: underline; +} + +.version-name { + font-weight: 600; + overflow-wrap: anywhere; +} + +.version-none, +.version-warn { + padding: 4px 8px; + margin: 0; +} + +.version-warn { + color: var(--warn); +} + +.version-save { + border-top: 1px solid var(--line); + margin-top: 4px; + padding-top: 6px; +} + +/* ---------- the Hardware area: the code on the left, the board on the right (src/ui/hw/board.ts) ---------- */ +.workspace.workspace-board { grid-template-rows: minmax(0, 1fr); } +.board-side { overflow: auto; padding: 10px 12px 24px; } +.board { display: flex; flex-direction: column; gap: 0.5rem; } +.board-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 0.5rem; position: sticky; top: -10px; z-index: 2; background: var(--paper); padding: 6px 0; } +.board-blurb { margin: 0; } +.board-add-menu { display: flex; flex-direction: column; gap: 6px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--paper-2); } +.board-add-group { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; } +.board-add-name { font-size: 12px; color: var(--ink-2); min-width: 10.5rem; } +.board-grid { display: grid; grid-template-columns: repeat(12, minmax(0, 1fr)); gap: 10px; align-items: start; } +.board-card { min-width: 0; border: 1px solid var(--line); border-radius: 8px; background: var(--paper-2); grid-column: span 6; } +.board-card.wide { grid-column: 1 / -1; } +/* The machine code listing and the encoding of the instruction it marks, side by side (board.ts marks the pair). + The listing needs two thirds of the row to show its operands; on a narrow board the two stack, the encoding under + the listing. Either way the listing scrolls on its own, as tall as the encoding, and keeps the instruction about + to run in view, so the row and its bytes are always on screen together. */ +.board-grid.is-roomy .board-card.pair-code { grid-column: span 8; } +.board-grid.is-roomy .board-card.pair-enc { grid-column: span 4; } +.board-grid:not(.is-roomy) .board-card.pair-code, .board-grid:not(.is-roomy) .board-card.pair-enc { grid-column: 1 / -1; } +.board-card.pair-code .board-card-body { max-height: var(--pair-h, 420px); overflow: auto; } +.board-grid:not(.is-roomy) .board-card.pair-code .board-card-body { max-height: 300px; } +.board-card-head { display: flex; align-items: center; gap: 6px; padding: 4px 6px 4px 8px; border-bottom: 1px solid var(--line); cursor: grab; user-select: none; font-size: 13px; font-weight: 600; } +.board-card-head:active { cursor: grabbing; } +.board-grip { color: var(--ink-3); } +.board-tool { border: 0; background: transparent; color: var(--ink-2); cursor: pointer; padding: 0 5px; font-size: 13px; border-radius: 4px; } +.board-tool:hover:not(:disabled) { background: var(--paper-3); color: var(--ink); } +.board-tool:disabled { opacity: 0.35; cursor: default; } +.board-card-body { padding: 8px 10px; min-width: 0; overflow-x: auto; } +.board-card-body .view, .board-card-body .setup { padding: 0; } +.board-card.dragging { opacity: 0.45; } +.board-card.drop-before { box-shadow: inset 0 3px 0 var(--accent); } +.board-card.drop-after { box-shadow: inset 0 -3px 0 var(--accent); } +.board-card.wide.drop-before { box-shadow: 0 -3px 0 var(--accent); } +.board-card.flash { outline: 2px solid var(--accent); outline-offset: 2px; transition: outline-color 0.6s; } +.board-note { margin: 0; color: var(--ink-2); font-size: 13px; } +.board-empty { grid-column: 1 / -1; } +/* inside a card the course view needs no frame of its own: the card is the frame */ +.board-card-body .board-a86 { font-size: 0.9rem; } +.board-card-body .board-a86 .a86-panel { border: 0; padding: 0; background: transparent; } +.board-card-body .board-a86 .a86-panel-title { display: none; } +@media (max-width: 1100px) { .board-grid { grid-template-columns: minmax(0, 1fr); } .board-card, .board-card.pair-code, .board-card.pair-enc { grid-column: 1 / -1; } } + +/* the area's name in the toolbar, where the switch is when no other area would show the work as it is */ +.area-name { font-weight: 600; font-size: 0.9rem; padding: 0.25rem 0.7rem; border-radius: 999px; background: var(--paper-3); color: var(--ink); white-space: nowrap; } + +/* ---------- the stepper, docked under the editor (same width, part of the editor column) ---------- */ +.step-dock { + flex-shrink: 0; + background: var(--paper); + border-top: 1px solid var(--line); + box-shadow: 0 -1px 0 var(--paper-3); +} +.step-dock .run-bar { border-bottom: 0; padding: 6px 10px 2px; gap: 6px; } +.step-dock .run-bar .run-controls { flex-direction: column; align-items: stretch; gap: 2px; flex: 1 1 100%; } +.step-dock .run-bar .run-controls .stepper { min-width: 0; } +.step-dock .run-bar .run-status { white-space: normal; flex: 1 1 100%; } +.step-dock .next-host { border-bottom: 0; padding: 0 10px 2px; background: transparent; } +.step-dock .next-host .trace-next { margin-bottom: 6px; padding: 4px 10px; font-size: 12.5px; } +.step-dock .next-host:empty { display: none; } + +.side-split.inspect-only { grid-template-rows: minmax(0, 1fr); } + +/* ---------- the Run view (src/ui/views/run.ts): the run top to bottom, the variables followed as columns ---------- */ +.view-trace { display: flex; flex-direction: column; min-height: 0; padding: 0; } +.run-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 14px; padding: 8px 12px 6px; border-bottom: 1px solid var(--line); background: var(--paper); } +.run-follow { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; flex: 1; min-width: 0; } +.run-follow-label { font-size: 11.5px; font-weight: 600; color: var(--ink-2); text-transform: uppercase; letter-spacing: 0.04em; margin-right: 4px; } +.run-fn { font-size: 11.5px; color: var(--ink-3); margin: 0 2px 0 8px; } +.run-chip { font: 12px var(--mono); padding: 1px 8px; border-radius: 999px; border: 1px dashed var(--line-2); background: transparent; color: var(--ink-2); cursor: pointer; } +.run-chip:hover { border-color: var(--accent); color: var(--ink); } +.run-chip.on { border-style: solid; border-color: var(--accent); background: var(--accent-bg); color: var(--ink); } +.run-filter { color: var(--ink-2); white-space: nowrap; } +.run-now { display: flex; flex-wrap: wrap; gap: 6px; padding: 8px 12px; border-bottom: 1px solid var(--line); background: var(--paper-2); max-height: 38%; overflow: auto; flex-shrink: 0; } +.run-now:empty { display: none; } +.run-now > p { margin: 0; } +.run-var { display: flex; flex-wrap: wrap; align-items: baseline; gap: 2px 8px; padding: 4px 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--paper); max-width: 100%; } +.run-var.run-var-wrote { border-color: var(--marker); background: var(--marker-bg); } +.run-var.run-var-read { box-shadow: inset 0 -2px 0 var(--accent); } +.run-var-name { font-weight: 600; font-size: 12.5px; } +.run-var-type { font-size: 11px; color: var(--ink-3); } +.run-var-value { font-size: 12.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 40ch; } +.run-var .ruler { flex-basis: 100%; } +.run-grid { flex-basis: 100%; border-collapse: collapse; font: 11.5px var(--mono); } +.run-grid td, .run-grid th { border: 1px solid var(--line); padding: 1px 5px; text-align: right; min-width: 1.6em; } +.run-grid th { color: var(--ink-3); font-weight: 400; border: 0; } +.run-scroll { flex: 1; min-height: 0; overflow: auto; position: relative; } +.run-tbl { width: 100%; border-collapse: separate; border-spacing: 0; font-size: 12.5px; } +.run-tbl thead th { position: sticky; top: 0; z-index: 1; background: var(--paper); border-bottom: 1px solid var(--line); text-align: left; font-weight: 600; font-size: 11.5px; color: var(--ink-2); padding: 5px 8px; } +.run-tbl th.run-colhead { color: var(--ink); border-left: 1px solid var(--line); } +.run-tbl td { padding: 3px 8px; border-bottom: 1px solid var(--paper-3); vertical-align: top; } +.run-row { cursor: pointer; } +.run-row:hover td { background: var(--paper-3); } +.run-row.row-last td { background: var(--accent-bg); } +.run-row.row-next td { background: var(--marker-bg); } +.run-row.row-next td.run-no { box-shadow: inset 3px 0 0 var(--marker); } +.run-no { width: 3.5em; white-space: nowrap; font-variant-numeric: tabular-nums; } +.run-no .k-dot { margin-right: 4px; } +.run-line { width: 2.5em; } +.run-what { min-width: 14ch; } +.run-indent { display: inline-block; } +.run-note { font-size: 11px; color: var(--ink-3); margin-top: 1px; } +.run-printed { color: var(--ink-2); } +.run-cell { border-left: 1px solid var(--paper-3); color: var(--ink-3); white-space: nowrap; } +.run-cell.wrote { color: var(--ink); font-weight: 600; background: color-mix(in srgb, var(--marker-bg) 70%, transparent); } +.run-cell.read { text-decoration: underline dotted var(--accent); text-underline-offset: 3px; } +.run-cell.out { background: repeating-linear-gradient(135deg, transparent 0 6px, var(--paper-3) 6px 7px); } +.run-life { display: inline-block; margin-right: 4px; font-weight: 700; } +.run-life-made, .run-life-copied { color: #2f8f5b; } +.run-life-moved-in { color: var(--accent); } +.run-life-moved-out { color: #b26a00; } +.run-life-destroyed { color: #c0392b; } +.run-more td { text-align: center; padding: 6px; } +.run-empty, .run-error { padding: 10px 12px; } +.run-now { align-items: flex-start; } +.run-chip { display: inline-flex; align-items: center; gap: 2px; } +.run-chip-fn { color: var(--ink-3); } +.run-chip-x { border: 0; background: transparent; color: var(--ink-3); cursor: pointer; padding: 0 0 0 4px; font-size: 13px; line-height: 1; } +.run-chip-x:hover { color: var(--ink); } +.run-chip-add { border-style: solid; color: var(--accent); } +.run-chip sup { font-size: 9px; color: var(--ink-3); margin-left: 2px; } +.run-picker { flex-basis: 100%; display: flex; flex-direction: column; gap: 4px; padding: 6px 0 2px; border-top: 1px dashed var(--line); max-height: 180px; overflow: auto; } +.run-picker-row { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; } +.run-picker-row .run-fn { min-width: 9ch; margin-left: 0; } +.run-what { overflow-wrap: anywhere; } +.run-what > :not(.run-indent):not(.run-note) { display: -webkit-box; } +.run-at { color: var(--ink-2); font-weight: 400; } +.run-grid td.wrote { background: var(--marker-bg); font-weight: 700; } +.run-grid td.read { box-shadow: inset 0 0 0 1.5px var(--accent); } + +/* ---------- the Tests view: the fuzzer's report (src/ui/views/tests.ts) ---------- */ +.fuzz-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-bottom: 10px; } +.fuzz-bar .fuzz-seed { width: 7em; max-width: 7em; flex: none; } +.fuzz-unit { border: 1px solid var(--line); border-radius: 8px; padding: 6px 12px 10px; margin-bottom: 10px; background: var(--paper-2); } +.fuzz-unit > summary { cursor: pointer; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 4px 0; } +.fuzz-sig { font-weight: 600; } +.fuzz-unit h5 { margin: 14px 0 6px; font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; color: var(--ink-2); } +.fuzz-checks { margin: 0; padding-left: 0; list-style: none; font-size: 13px; } +.fuzz-checks li { padding-left: 1.4em; position: relative; margin: 2px 0; } +.fuzz-checks li::before { content: '✓'; position: absolute; left: 0; color: #2f8f5b; font-weight: 700; } +.fuzz-gens td, .fuzz-gens th { font-size: 12.5px; vertical-align: top; } +.fuzz-strats { margin: 6px 0 0; padding-left: 1.2em; font-size: 12.5px; } +.fuzz-strats li { margin: 2px 0; } +.fuzz-fail { border: 1px solid color-mix(in srgb, #c0392b 40%, var(--line)); border-left: 3px solid #c0392b; border-radius: 6px; padding: 8px 10px; margin: 6px 0; background: var(--paper); } +.fuzz-fail-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; } +.fuzz-msg { margin: 6px 0; font-size: 13px; } +.fuzz-shrink { margin: 4px 0 0; padding-left: 1.6em; font-size: 12.5px; } +.fuzz-shrink li { margin: 1px 0; color: var(--ink-2); } +.fuzz-shrink-last { color: var(--ink) !important; font-weight: 600; } +.fuzz-cov { display: flex; flex-direction: column; gap: 1px; } +.fuzz-cov-row { display: grid; grid-template-columns: 3em 90px 4.5em minmax(0, 1fr); align-items: center; gap: 8px; border: 0; background: transparent; text-align: left; padding: 1px 4px; border-radius: 4px; cursor: pointer; color: var(--ink); font: inherit; font-size: 12.5px; } +.fuzz-cov-row:hover { background: var(--paper-3); } +.fuzz-cov-row.never { background: color-mix(in srgb, #c0392b 10%, transparent); } +.fuzz-cov-line { color: var(--ink-3); text-align: right; } +.fuzz-cov-bar { display: inline-block; height: 8px; background: var(--paper-3); border-radius: 4px; overflow: hidden; } +.fuzz-cov-bar > span { display: block; height: 100%; background: var(--accent); } +.fuzz-cov-n { color: var(--ink-2); } +.fuzz-cov-src { white-space: pre; overflow: hidden; text-overflow: ellipsis; } +.fuzz-results { display: flex; flex-direction: column; gap: 2px; } +.fuzz-result { display: grid; grid-template-columns: minmax(8ch, max-content) 120px 4em; gap: 8px; align-items: center; font-size: 12.5px; } +.fuzz-filter { display: flex; flex-wrap: wrap; gap: 4px; margin-bottom: 6px; } +.fuzz-cases-wrap { max-height: 360px; overflow: auto; border: 1px solid var(--line); border-radius: 6px; } +.fuzz-cases { width: 100%; font-size: 12px; } +.fuzz-cases thead th { position: sticky; top: 0; background: var(--paper); z-index: 1; } +.fuzz-out { font-size: 11px; padding: 0 6px; border-radius: 999px; } +.fuzz-out-pass { color: #2f8f5b; background: color-mix(in srgb, #2f8f5b 12%, transparent); } +.fuzz-out-fail { color: #c0392b; background: color-mix(in srgb, #c0392b 12%, transparent); } +.fuzz-out-skip { color: var(--ink-2); background: var(--paper-3); } +.fuzz-out-raises { color: #b26a00; background: color-mix(in srgb, #b26a00 12%, transparent); } +.fuzz-new { color: var(--accent); } + +/* ---------- the home page's three areas (src/ui/home.ts) ---------- */ +.area-cards { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; margin-top: 8px; align-items: stretch; } +.area-card { display: flex; flex-direction: column; gap: 8px; padding: 16px 16px 14px; border: 1px solid var(--line); border-radius: var(--r-lg); background: var(--paper-2); min-width: 0; } +.area-tagline { margin: 0; color: var(--ink-2); font-size: 14px; } +.area-card .hero-actions { margin-top: auto; padding-top: 6px; } +.area-sample { display: flex; flex-direction: column; gap: 6px; min-width: 0; font-size: 13px; } +.area-sample .sample { margin: 0; font-size: 11.5px; max-height: 12.5em; overflow: auto; } +.area-step { border-left: 3px solid var(--line-2); padding-left: 8px; min-width: 0; } +.area-step.way-matho { border-left-color: var(--lang-matho); } +.area-step.way-pseudo { border-left-color: var(--lang-pseudo); } +.area-step.way-lingo { border-left-color: var(--lang-lingo); } +.area-step.way-mojo { border-left-color: var(--lang-mojo); } +.area-step-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin: 2px 0; font-size: 12.5px; } +.area-arrow { color: var(--ink-3); font-size: 12px; font-family: var(--mono); } +.area-badges { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } +.area-regs { font-size: 12px; } +.area-regs tr.is-changed td { background: var(--accent-bg); font-weight: 600; } +.area-a86.a86 { font-size: 12px; margin: 0; } +.area-a86 .hw-line-cell { min-height: 1.2rem; line-height: 1.2rem; font-size: 0.6rem; } +.feat-area { margin-top: 22px; } +.feat-area-head { display: flex; flex-wrap: wrap; align-items: baseline; gap: 10px; margin-bottom: 10px; } +.feat-area-head h3 { margin: 0; font-size: 18px; } +.feat-area-head p { margin: 0; } +.way-area { font-weight: 400; } +.card { display: flex; flex-direction: column; } +.card-main { color: inherit; display: block; } +.card-main:hover { text-decoration: none; } +.card-areas { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; margin-top: 8px; padding-top: 8px; border-top: 1px dashed var(--line); } +.chip-area { text-decoration: none; } +.chip-area:hover { border-color: var(--accent); text-decoration: none; } +.home-foot p { margin-top: 6px; } +@media (max-width: 1100px) { .area-cards { grid-template-columns: minmax(0, 1fr); } } + +/* ---------- the home page's pitch (src/ui/home.ts): why it exists, then the areas, then why Mojo ---------- */ +.hero.hero-pitch { grid-template-columns: minmax(0, 1.25fr) minmax(0, 1fr); gap: 48px; align-items: center; padding: 48px 0 40px; } +.hero-kicker { margin: 0 0 14px; color: var(--accent); font-weight: 600; font-size: 14px; } +.hero.hero-pitch h1 { font-size: 46px; max-width: 16ch; margin-bottom: 20px; text-wrap: balance; } +.hero.hero-pitch .lede { max-width: 58ch; margin-bottom: 26px; } + +/* the sign-off: who made it changes, the sentence at the bottom does not */ +.signoff { margin: 0; padding: 22px 24px 18px; border: 1px solid var(--line); border-radius: var(--r-lg); background: var(--paper-2); box-shadow: var(--shadow); } +.signoff-head { font-size: 13px; color: var(--ink-3); margin-bottom: 4px; } +.signoff-makers { list-style: none; margin: 0 0 18px; padding: 0; } +.signoff-makers li { padding: 7px 0; border-bottom: 1px solid var(--line); color: var(--ink-2); font-size: 15px; display: flex; align-items: center; gap: 10px; } +.signoff-makers li::before { content: ''; width: 9px; height: 9px; border-radius: 50%; border: 1.5px solid var(--ink-3); flex: none; } +.signoff-line { margin: 0 0 18px; font-size: 22px; line-height: 1.25; font-weight: 600; letter-spacing: -.015em; color: var(--ink); } +.signoff-sign { display: flex; align-items: flex-end; gap: 10px; margin-bottom: 14px; } +.signoff-rule { flex: 1; height: 28px; border-bottom: 1.5px solid var(--ink); } +.signoff figcaption { margin: 0; } + +.why { padding: 8px 0 40px; border-bottom: 1px solid var(--line); } +.why-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 32px; } +.why-col { border-top: 2px solid var(--ink); padding-top: 14px; } +.why-col h3 { margin: 0 0 8px; font-size: 17px; letter-spacing: -.01em; } +.why-col p { margin: 0; color: var(--ink-2); font-size: 14px; line-height: 1.6; max-width: 60ch; } +.why-example { margin: 28px 0 0; padding: 14px 18px; border-left: 3px solid var(--accent); background: var(--paper-2); border-radius: 0 var(--r) var(--r) 0; color: var(--ink-2); font-size: 14.5px; line-height: 1.6; max-width: 92ch; } +.why-example b { color: var(--ink); } + +.areas { padding: 40px 0; border-bottom: 1px solid var(--line); } +.areas h2, .why-mojo h2 { font-size: 24px; letter-spacing: -.02em; margin: 0 0 6px; } +.area-card { gap: 10px; } +.area-card h3 { margin: 0; font-size: 20px; letter-spacing: -.01em; } +.area-tagline { min-height: 3em; } +/* every card's sample sits in a window of the same height, so the three read as a set */ +.area-window { height: 400px; overflow: hidden; padding: 10px; border: 1px solid var(--line); border-radius: var(--r); background: var(--paper); -webkit-mask-image: linear-gradient(#000 88%, transparent); mask-image: linear-gradient(#000 88%, transparent); } +.area-window .area-sample .sample { max-height: none; overflow: hidden; } +.area-card .hero-actions { margin-top: 4px; } + +.why-mojo { display: grid; grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr); gap: 48px; align-items: start; padding: 40px 0; border-bottom: 1px solid var(--line); } +.why-mojo-points { margin: 0 0 14px; display: grid; grid-template-columns: minmax(0, 1fr); gap: 2px; } +.why-mojo-points dt { font-weight: 600; margin-top: 10px; } +.why-mojo-points dd { margin: 0; color: var(--ink-2); max-width: 62ch; } +/* the range of one language, a real sequence from the first program to the far end */ +.mojo-range { list-style: none; margin: 8px 0 0; padding: 0; counter-reset: rung; position: relative; } +.mojo-range::before { content: ''; position: absolute; left: 11px; top: 14px; bottom: 14px; width: 2px; background: linear-gradient(var(--lang-lingo), var(--lang-mojo)); border-radius: 2px; } +.mojo-range li { counter-increment: rung; position: relative; padding: 8px 0 14px 40px; display: flex; flex-direction: column; gap: 2px; } +.mojo-range li::before { content: counter(rung); position: absolute; left: 0; top: 7px; width: 24px; height: 24px; border-radius: 50%; background: var(--paper-2); border: 2px solid var(--lang-mojo); display: grid; place-items: center; font-size: 12px; font-weight: 700; color: var(--ink); } +.mojo-range li span { font-size: 13px; } + +/* the notations: six even boxes, two rows of three */ +.ways.ways-even { grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 14px; } +.ways-even .way { display: flex; flex-direction: column; padding: 14px 14px 12px; } +.ways-even .way h3 { display: flex; align-items: center; gap: 8px; font-size: 15px; margin-bottom: 4px; } +.ways-even .way-area { font-size: 11px; font-weight: 500; padding: 1px 8px; } +.ways-even .way > p { min-height: 4.5em; } +.ways-even .way pre { height: 150px; max-height: none; font-size: 11.5px; } +.ways-even .way-body { height: 158px; border-top: 1px solid var(--line); padding-top: 8px; } +.ways-even .way-body pre { height: auto; border-top: 0; padding-top: 0; -webkit-mask-image: none; mask-image: none; margin-bottom: 10px; } +.ways-even .way .way-note { min-height: 0; margin: 0; font-size: 12px; } + +@media (max-width: 900px) { + .hero.hero-pitch, .why-mojo { grid-template-columns: 1fr; gap: 28px; } + .hero.hero-pitch h1 { font-size: 34px; } + .why-grid { grid-template-columns: 1fr; gap: 20px; } + .ways.ways-even { grid-template-columns: 1fr 1fr; } + .area-window { height: auto; max-height: 420px; } +} +@media (max-width: 560px) { + .ways.ways-even { grid-template-columns: 1fr; } +} + +/* the Run view: a string or list with no ruler yet keeps the ruler's height */ +.ruler.ruler-placeholder { visibility: hidden; } + +/* ---------- With Quarto (#/quarto, src/ui/quarto.ts) and its teaser on the home page ---------- + The extension's own stylesheet (quarto/_extensions/pplus/pplus.css) draws the views as a Quarto page does; it + reads Bootstrap's variables, which here are the app's tokens. */ +.qg, .quarto-teaser { + --bs-body-color: var(--ink); + --bs-body-bg: var(--paper-2); + --bs-secondary-color: var(--ink-3); + --bs-link-color: var(--accent); + --bs-font-monospace: var(--mono); +} +.qg-hero { padding: 40px 0 18px; } +.qg-hero h1 { font-size: 42px; line-height: 1.1; letter-spacing: -.025em; margin: 0 0 16px; max-width: 22ch; text-wrap: balance; } +.qg-hero .lede { font-size: 17px; color: var(--ink-2); max-width: 70ch; line-height: 1.55; margin: 0 0 22px; } +.qg-kinds { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; padding: 8px 0 36px; border-bottom: 1px solid var(--line); } +.qg-kindcard { padding: 14px 16px; border: 1px solid var(--line); border-radius: var(--r-lg); background: var(--paper-2); } +.qg-kindcard p { margin: 8px 0 0; } +.qg-kind { display: inline-block; font-size: 11.5px; font-weight: 600; padding: 1px 9px; border-radius: 10px; line-height: 1.6; } +.qg-kind-chip-rendered { background: var(--ok-bg); color: var(--ok); } +.qg-kind-chip-live { background: var(--accent-bg); color: var(--accent); } +.qg-kind-chip-machine { background: color-mix(in srgb, var(--lang-asm) 16%, var(--paper-2)); color: var(--ink); } +.qg-index a.qg-kind-machine { color: var(--ink); } +.qg-explore { font-family: var(--mono); max-width: 100%; } +.qg-kind-chip-text { background: var(--paper-3); color: var(--ink-2); } +.qg h2 { font-size: 24px; letter-spacing: -.02em; margin: 0 0 6px; } +.qg-gallery-sec { padding: 36px 0 12px; } +.qg-index { display: flex; flex-wrap: wrap; gap: 4px 12px; margin: 0 0 12px; font: 12.5px var(--mono); } +.qg-index a { color: var(--ink-2); } +.qg-index a.qg-kind-rendered { color: var(--ok); } +.qg-index a.qg-kind-live { color: var(--accent); } +.qg-gallery { display: flex; flex-direction: column; gap: 22px; margin-top: 14px; } +.qg-card { scroll-margin-top: 16px; padding: 18px 18px 14px; border: 1px solid var(--line); border-radius: var(--r-lg); background: var(--paper); } +.qg-card-head { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; } +.qg-card-head h3 { margin: 0; font-size: 17px; order: -1; flex-basis: 100%; } +.qg-name { font: 600 14px var(--mono); color: var(--ink); } +.qg-summary { margin: 8px 0 12px; color: var(--ink-2); max-width: 80ch; } +.qg-note { margin: -6px 0 12px; max-width: 80ch; } +.qg-label { font-size: 11px; font-weight: 600; letter-spacing: .05em; text-transform: uppercase; color: var(--ink-3); margin: 10px 0 6px; } +.qg-tabbar { display: flex; flex-wrap: wrap; gap: 2px; border-bottom: 1px solid var(--line); margin-bottom: 8px; } +.qg-tab { font: 12.5px var(--mono); padding: 5px 10px; border: 0; border-bottom: 2px solid transparent; background: none; color: var(--ink-2); cursor: pointer; } +.qg-tab:hover { color: var(--ink); } +.qg-tab.on { color: var(--ink); border-bottom-color: var(--accent); } +.qg-codeblock, .qg-codeblock.pplus-static { position: relative; padding: 0; } +.qg-codeblock .pplus-code { max-height: 22rem; overflow: auto; } +.qg-codeblock .qg-copy { position: absolute; top: 6px; right: 6px; } +.qg-plain { padding: .55rem .8rem !important; white-space: pre-wrap; } +.qg-out .pplus-figure, .qg-out figure.pplus-embed { margin: 0; } +.qg-out .pplus-static { background: var(--paper-2); } +.qg-tabs.pplus-static, .qg-listings.pplus-static { padding: 0; } +.qg-tabs .qg-tabbody { padding: 2px 0 0; } +.qg-listings { display: flex; flex-direction: column; gap: 8px; } +.qg-opts { margin-top: 12px; font-size: 13px; } +.qg-opts summary { cursor: pointer; color: var(--ink-2); } +.qg-opts dl, .qg-optlist { display: grid; grid-template-columns: max-content 1fr; gap: 3px 14px; margin: 8px 0 0; } +.qg-opts dt, .qg-optlist dt { font-weight: 400; } +.qg-opts dd, .qg-optlist dd { margin: 0; color: var(--ink-2); } +.qg-setup, .qg-ref { padding: 36px 0 12px; border-top: 1px solid var(--line); margin-top: 24px; } +.qg-steps { list-style: none; padding: 0; margin: 12px 0 0; display: flex; flex-direction: column; gap: 20px; } +.qg-step { display: grid; grid-template-columns: 32px minmax(0, 1fr); gap: 12px; } +.qg-step-n { width: 28px; height: 28px; border-radius: 50%; display: grid; place-items: center; font-weight: 700; background: var(--accent-bg); color: var(--accent); } +.qg-step h3 { margin: 3px 0 6px; font-size: 16px; } +.qg-step p { margin: 0 0 8px; color: var(--ink-2); max-width: 80ch; } +.qg-step .qg-codeblock { margin-bottom: 8px; max-width: 760px; } +.qg-files { display: flex; flex-wrap: wrap; gap: 4px; } +.qg-files .chip { font-family: var(--mono); } +.qg-tbl td:first-child { white-space: nowrap; } +.qg-ref h3 { margin: 22px 0 4px; font-size: 16px; } + +.quarto-teaser { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.25fr); gap: 36px; align-items: start; padding: 40px 0; border-bottom: 1px solid var(--line); } +.quarto-teaser h2 { font-size: 24px; letter-spacing: -.02em; margin: 0 0 6px; } +.quarto-teaser .qg-chips { display: flex; flex-wrap: wrap; gap: 4px; margin: 0 0 18px; } +.quarto-teaser .qg-chips a { font-family: var(--mono); } +.quarto-teaser .pplus-figure { margin: 0; } +.quarto-teaser .qg-codeblock { margin-bottom: 10px; } + +@media (max-width: 900px) { + .qg-kinds, .quarto-teaser { grid-template-columns: 1fr; } + .qg-hero h1 { font-size: 32px; } +} + +/* ------------------------------------------------------------------ */ +/* The library (#/library) */ +/* ------------------------------------------------------------------ */ +.lib-hero { padding: 32px 0 8px; } +.lib-hero h1 { margin: 6px 0 10px; } +.lib-use { margin-left: 12px; color: var(--ink-2); } +.lib-module { margin: 28px 0; } +.lib-mod-name { font-size: .8em; color: var(--ink-2); } +.lib-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 12px; margin-top: 12px; } +.lib-card { display: block; padding: 14px 16px; border: 1px solid var(--line); border-radius: var(--r-lg); color: inherit; text-decoration: none; } +.lib-card:hover { border-color: var(--accent); } +.lib-card-name { font-weight: 600; margin-bottom: 4px; } +.lib-card p { margin: 0 0 10px; font-size: .92em; } +.lib-chips { display: inline-flex; flex-wrap: wrap; gap: 6px; } +.lib-chip { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: .78em; border: 1px solid var(--line); white-space: nowrap; } +.lib-pass { background: var(--ok-bg); color: var(--ok); } +.lib-open { background: var(--warn-bg); color: var(--warn); } +.lib-unverified, .lib-skipped { background: transparent; color: var(--ink-2); } +.lib-fail { background: var(--err-bg); color: var(--err); } +.lib-sec { margin: 26px 0; } +.lib-table { width: 100%; border-collapse: collapse; font-size: .92em; } +.lib-table th, .lib-table td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--line); vertical-align: top; } +.lib-ref { margin: 10px 0; border: 1px solid var(--line); border-radius: var(--r); padding: 8px 12px; } +.lib-ref summary { cursor: pointer; } +.lib pre.pplus-code { font-family: var(--mono); font-size: .88em; line-height: 1.5; overflow-x: auto; padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--r); } +.lib .pplus-lno { display: inline-block; width: 2.6em; color: var(--ink-2); user-select: none; } + +/* ---------- notices: a note at the foot of the page (ui/notice.ts), and pages that say why there is nothing ---------- */ +.notice { + position: fixed; + left: 50%; + bottom: 16px; + transform: translateX(-50%); + z-index: 50; + display: flex; + gap: 12px; + align-items: flex-start; + width: min(640px, calc(100vw - 32px)); + padding: 12px 14px; + background: var(--paper-2); + color: var(--ink); + border: 1px solid var(--line-2); + border-left: 4px solid var(--warn); + border-radius: var(--r); + box-shadow: var(--shadow); + font-size: 14px; + line-height: 1.45; +} +.notice p { margin: 0; flex: 1; } +.message-page .lib-hero { max-width: 720px; } +.compile-input-note { max-width: 70ch; } +.compile-send-note { max-width: 70ch; } +/* index.html's note for a page whose scripts never ran (opened as a file, scripts blocked, offline on first load) */ +.boot-note { max-width: 640px; margin: 64px auto; padding: 0 16px; color: var(--ink-2); font: 16px/1.5 var(--sans); opacity: 0; animation: boot-note-show 0s 4s forwards; } +@keyframes boot-note-show { to { opacity: 1; } } + +/* the tab rows: the tabs are one tablist (shell.ts tabList) that lays out as if it were not there */ +.tablist { display: contents; } +/* links inside running text are underlined, not told apart by color alone */ +.home p a:not(.btn):not(.chip), .home-foot a, .lib-hero p a:not(.btn) { text-decoration: underline; text-underline-offset: 2px; } + +/* ---------- the site's words: the hero's sentence, the glosses, the footer ---------- */ +/* the one sentence that says what Programming+ is, under the hero's reason */ +.hero-what { font-weight: 500; color: var(--ink); } +/* what each notation is, beside its name, where the names first appear (the Bridge card) */ +.area-gloss { color: var(--ink-3); font-size: 12px; } +/* the footer of the site's pages: license, disclaimer, version, what the site stores and sends */ +.site-foot .site-foot-links { margin-top: 0; } +.site-version { font-family: var(--mono); } +.site-data { margin-top: 10px; max-width: 80ch; } +.site-data summary { cursor: pointer; color: var(--ink); font-weight: 500; } +.site-data ul { margin: 6px 0 0; padding-left: 20px; } +.site-data li { margin: 4px 0; line-height: 1.45; } + +/* ---------- accessibility, second pass ---------- */ +/* read by a screen reader, not shown: the headings a page needs for its outline (the workspaces' h1, the home page's "why") */ +.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; border: 0; } +/* on the yellow "next" row the muted values and the current line number take the second ink, not the third + (--ink-3 is 3.5:1 on the dark theme's marker; --ink-2 is 5.0:1) */ +.run-row.row-next .run-cell:not(.wrote), .ed .cm-gutterElement.ed-gcurrent { color: var(--ink-2); } + +/* ---------- a phone-width screen: one part of the workspace at a time ---------- + Under 700px the workspace's parts would stack below an editor as tall as its program, and the side column or the + Hardware board start several screens down. Here the workspace fills the screen and shows one part, chosen in the + bar at the foot of the toolbar (shell.ts, setNarrow): the code with the stepper under it; the side column (or the + board) with the stepper above it; or the dock. Each part scrolls inside itself. A wider screen never sees the bar. */ +.narrow-bar { display: none; } +@media (max-width: 700px) { + .toolbar { gap: 6px 8px; padding: 6px 10px; } + .narrow-bar { display: flex; flex-basis: 100%; } + .narrow-bar .seg-opt { flex: 1; } + .shell { height: 100vh; height: 100dvh; min-height: 0; } + .workspace, .workspace.workspace-board { flex: 1; min-height: 0; } + .main { flex: 1; min-height: 0; } + .workspace[data-narrow="code"] .side, .workspace[data-narrow="code"] .dock { display: none; } + .workspace[data-narrow="code"] .panes { flex: 1; min-height: 0; } + .workspace[data-narrow="code"] .pane-host .ed { min-height: 0; } + .workspace[data-narrow="side"] .panes { flex: none; min-height: 0; order: -1; } + .workspace[data-narrow="side"] .panes > :not(.step-dock) { display: none; } + /* above the side column the stepper keeps its first row and what runs next; its other controls are with the code */ + .workspace[data-narrow="side"] .step-dock .stepper-row2 { display: none; } + .workspace[data-narrow="side"] .side { flex: 1; min-height: 0; overflow: auto; } + .workspace[data-narrow="side"] .panel-body { max-height: none; } + .workspace[data-narrow="side"] .dock { display: none; } + .workspace[data-narrow="dock"] .main { display: none; } + .workspace[data-narrow="dock"] .dock { flex: 1; min-height: 0; } + .workspace[data-narrow="dock"] .dock-body { display: block; max-height: none; } +} diff --git a/styles/course/README.md b/styles/course/README.md new file mode 100644 index 0000000..15f10b0 --- /dev/null +++ b/styles/course/README.md @@ -0,0 +1,26 @@ +# styles/course + +Stylesheets from the course site (`static/css/` in its repository), copied here unchanged so the vendored engines' widgets (pplus-core's `core/src/engines/asm86/views.js` and `hwviews.js`: registers, memory, caches, pipeline, the out-of-order core) can be shown in the app with the look they have on the course pages. `index.html` loads them, and the Hardware area's machine board (`src/ui/hw/board.ts`) is what uses them. + +| File here | Course path | What it holds | sha256 | +|---|---|---|---| +| `tokens.css` | `static/css/base/tokens.css` | `--course-*` roles and the `--viz-*` chart palette that `shared/viz.js` and the hardware views read | `b2f40ca21e0f0a38aaf3dd096ec91e8afeb2455742f1fe255577cbaecd01a745` | +| `kit.css` | `static/css/widgets/kit.css` | the `--w-*` tokens and controls shared by the widget families | `51b46da837fcf64d20fd497458d2328a1e896913a2d2fededab198b58e889790` | +| `asm86.css` | `static/css/widgets/asm86.css` | every `.a86-*` rule the x86-64 widgets use (needs `kit.css` first) | `dba269f466b33be7621a2156a0db386d24b89927cf3bfa00397b8af58759e576` | +| `bridge.css` | (ours) | gives the course files the page colors and fonts they expect, from the app's tokens | | + +The Quarto extension ships the same three files in `quarto/_extensions/pplus/course/`, with the board's adjustments from `bridge.css` (its `:root` block left out, since a Quarto page has those colors already) as `pplus-hw.css`; `pixi run quarto-css` copies them, and `tests/quarto.test.mjs` fails while the copies differ. + +`tests/course-css.test.mjs` checks that each copied file still has the hash above, so a local edit cannot slip in: a change belongs in the course repository, then copy the file again and update its hash here. + +## Using them + +Load in this order, after `styles.css`: `bridge.css`, `tokens.css`, `kit.css`, `asm86.css`. Then: + +- **The theme.** The course files switch to dark on `body.quarto-dark`, and they follow the operating system only when the body has neither `quarto-light` nor `quarto-dark`. The app therefore puts exactly one of those classes on ``, matching the theme it shows: `syncBodyTheme()` in `src/ui/theme.ts` (the choice itself is the pure `themeBodyClass()`, tested in `tests/hardware.test.mjs`) runs at load, on every theme change, on a host page's forced theme, and when the system preference changes. Without that, a light app on a dark system would draw dark widgets. +- **The root class.** The widgets build their own `.a86` root, so their rules cannot touch the rest of the app. +- **The pseudocode lab** (`pseudo-lab.css`) is not copied: the app draws its own views for pseudo and does not use the engine's `views.js` for it. + +## Updating + +Copy the three files from the course repository's `static/css/` (paths in the table), run `sha256sum styles/course/*.css`, put the new hashes in the table above, and run `pixi run test`. diff --git a/styles/course/asm86.css b/styles/course/asm86.css new file mode 100644 index 0000000..e252773 --- /dev/null +++ b/styles/course/asm86.css @@ -0,0 +1,2773 @@ +/* widgets/asm86.css -- styling for the x86-64 teaching widgets. + + Load AFTER widgets/kit.css, which holds the color roles (amber = something + changed on this step, blue = a memory load, green = a recorded match, + purple = a memory store, red = a mismatch or a branch mispredicting often + enough to cost time), dark mode, and the rules shared with the pseudocode + lab. + + The hardware views keep those meanings. A cache hit is green and a miss + is red, read the same way as a match and a mismatch; a load's path + through the memory hierarchy is blue and a store's is purple. Machine + code needs more categories than five, so the encoding view has its own + small palette (--a86-enc-*), and always writes each byte's role under it + so color is never the only signal. */ + +.a86 { + --a86-enc-prefix: #6b6f76; + --a86-enc-rex: #9a3f7a; + --a86-enc-opcode: #8a5c05; + --a86-enc-modrm: #17618f; + --a86-enc-sib: #266a41; + --a86-enc-disp: #6a4299; + --a86-enc-imm: #93291f; +} + +body.quarto-dark .a86, +[data-bs-theme="dark"] .a86 { + --a86-enc-prefix: #a9aeb5; + --a86-enc-rex: #e39acb; + --a86-enc-opcode: #e0a93a; + --a86-enc-modrm: #6fb4e3; + --a86-enc-sib: #74c391; + --a86-enc-disp: #c0a0e0; + --a86-enc-imm: #e08a80; + + /* a touch stronger than the shared 22%, so green reads against a dark page */ + --w-match-bg: color-mix(in srgb, var(--w-match) 24%, var(--w-page)); +} + +/* Fallback for browsers without color-mix(). */ +@supports not (background: color-mix(in srgb, white 50%, black)) { + .a86 { + --w-surface: #ffffff; + } + + .a86-enc-part { + background: var(--w-surface-2); + } + + body.quarto-dark .a86 { + --w-surface: #1a1e23; + } +} + + +/* --------------------------------------------------- inherited code style + Quarto styles bare with its own background, padding, and color. + Inside a widget every register value, letter, and instruction is a , + so that styling turns each one into a little tinted chip fighting the + panel it sits in. The :not() raises specificity above Quarto's + `code:not(.sourceCode)` regardless of which stylesheet loads first. */ + + + + + + +/* controls -------------------------------------------------------------- */ + + +/* Quarto adds .btn.btn-quarto to buttons in OJS output, and base/site.css + themes those from --bs-btn-*. These rules are the standalone fallback and + deliberately lose to it, so a widget inside the site matches every other + button on the site. */ + + +/* Kept at one class so site styling still wins on padding and background, + while the primary action stays marked. */ + + + +/* layout ---------------------------------------------------------------- */ + + +/* The program listing needs more width than any state panel, because its + longest line is fixed and cannot reflow. An even split clipped + `movzx r8d, byte ptr [rdi + rcx*1]` mid-operand. */ +@media (min-width: 720px) { + .a86-two-column .a86-grid { + grid-template-columns: minmax(0, 1.35fr) minmax(0, 1fr); + } + + .a86-two-column .a86-span-2, + .a86-two-column .a86-mem-panel, + .a86-two-column .a86-vec-panel, + .a86-two-column .a86-flow-panel, + .a86-two-column .a86-path-panel, + .a86-two-column .a86-code-panel.is-wide, + .a86-two-column .a86-bits-panel, + .a86-two-column .a86-cache-panel, + .a86-two-column .a86-pipe-panel, + .a86-two-column .a86-tl-panel, + .a86-two-column .a86-core-panel, + .a86-two-column .a86-chip-panel, + .a86-two-column .a86-uops-panel, + .a86-two-column .a86-bn-panel { + grid-column: 1 / -1; + } +} + +/* ------------------------------------------------------------ fullscreen + A fixed overlay rather than the browser's own fullscreen mode: it behaves + the same in every browser, needs no permission, and leaves the page + exactly as it was on the way out. Above Bootstrap's fixed navbar at 1030. + + The extra room goes to the text first: the widget's one font size grows + with the window, from the page size on a laptop to about 1.3 times it on a + large monitor. The panels then share each row with flexbox rather than a + grid. A grid with a full-width listing keeps every column it made alive, + so three panels in a row of five sat at a fifth of the width each and + left the rest blank; flex rows always fill. */ + + + + +.a86.is-fullscreen .a86-grid>* { + flex: 1 1 calc(var(--w-fs) * 21); +} + +/* A diagram asks for the width at which its labels match the text around + it (see the diagram sizes below), so it shares a row only when there is + room for that, and otherwise takes a row of its own. */ +.a86.is-fullscreen .a86-grid>.a86-path-panel, +.a86.is-fullscreen .a86-grid>.a86-flow-panel { + flex-basis: calc(var(--w-fs) * 60); +} + +.a86.is-fullscreen .a86-grid>.a86-cache-panel, +.a86.is-fullscreen .a86-grid>.a86-mem-panel, +.a86.is-fullscreen .a86-grid>.a86-stack-panel { + flex-basis: calc(var(--w-fs) * 32); +} + +.a86.is-fullscreen .a86-grid>.a86-code-panel, +.a86.is-fullscreen .a86-grid>.a86-pipe-panel, +.a86.is-fullscreen .a86-grid>.a86-tl-panel, +.a86.is-fullscreen .a86-grid>.a86-chip-panel, +.a86.is-fullscreen .a86-grid>.a86-core-panel, +.a86.is-fullscreen .a86-grid>.a86-bits-panel, +.a86.is-fullscreen .a86-grid>.a86-span-2 { + flex-basis: 100%; +} + +/* Never so tall that a diagram pushes the rest of the widget off screen. */ +.a86.is-fullscreen .a86-path-svg, +.a86.is-fullscreen .a86-flow-svg, +.a86.is-fullscreen .a86-chip-svg, +.a86.is-fullscreen .a86-tl-svg { + max-height: 70vh; +} + +/* Diagram sizes. Each diagram is drawn about 700 units wide with 12-unit + labels, so capping it near 58 times the widget's font size makes a label + come out close to the size of the text around it, at any zoom, in the + page or in fullscreen. A fixed pixel cap made the labels shrink to half + the text size in a wide panel. */ +.a86 .a86-path-svg, +.a86 .a86-flow-svg, +.a86 .a86-tl-svg { + max-width: calc(var(--w-fs) * 58); +} + +.a86 .a86-chip-svg { + max-width: calc(var(--w-fs) * 62); +} + + + +.a86-panel { + background: var(--w-surface); + border: 1px solid var(--w-rule); + border-radius: 4px; + padding: 0.55rem 0.65rem; + min-width: 0; + overflow: hidden; +} + + +/* code listing ---------------------------------------------------------- */ + +.a86-code { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.93); + line-height: 1.55; + overflow-x: auto; + + /* Set by codeView from the longest instruction in the program, in + characters. The instruction column is therefore exactly wide enough + and never clips, and comments line up in a column across every row. */ + --a86-code-cols: 48ch; +} + +.a86-code-row { + display: grid; + grid-template-columns: calc(var(--w-fs) * 2.24) calc(var(--w-fs) * 0.94) var(--a86-code-cols) minmax(0, 1fr); + align-items: baseline; + border-left: 2px solid transparent; + padding-left: 0.15rem; + background: color-mix(in srgb, var(--w-change-bg) calc(var(--heat, 0) * 70%), transparent); +} + +/* A comment on a line of its own takes the width of both remaining cells. */ +.a86-code-row.is-note { + grid-template-columns: calc(var(--w-fs) * 2.24) calc(var(--w-fs) * 0.94) minmax(0, 1fr); +} + +.a86-code-count { + color: var(--w-dim); + font-size: calc(var(--w-fs) * 0.85); + text-align: right; + padding-right: 0.3rem; +} + + +.a86-code-text { + white-space: pre; + font-size: inherit; +} + +/* The comment takes whatever width is left and wraps into it, so a narrow + panel costs a comment an extra line rather than costing the instruction + its tail. */ +.a86-code-comment { + color: var(--w-dim); + font-weight: 400; + white-space: normal; + padding-left: 0.5rem; + text-indent: 0; +} + +.a86-code-row.is-note .a86-code-comment { + padding-left: 0; + white-space: pre-wrap; +} + +/* With addresses and bytes, two more columns sit before the instruction, + as in objdump's output. Label and note rows leave them empty. */ +.a86-code.has-machine .a86-code-row { + grid-template-columns: calc(var(--w-fs) * 2.24) calc(var(--w-fs) * 0.94) var(--a86-addr-cols) var(--a86-bytes-cols) var(--a86-code-cols) minmax(0, 1fr); +} + +.a86-code.has-machine .a86-code-row.is-note, +.a86-code.has-machine .a86-code-row.a86-code-label { + grid-template-columns: calc(var(--w-fs) * 2.24) calc(var(--w-fs) * 0.94) minmax(0, 1fr); +} + +.a86-code-addr { + color: var(--w-dim); +} + +.a86-code-bytes { + color: var(--w-read); + white-space: pre; +} + +.a86-code-addr, +.a86-code-bytes { + font-size: inherit; +} + + +.a86-code-row.is-error .a86-code-marker { + color: var(--w-miss); +} + +.a86-code-failed .a86-code-row { + grid-template-columns: calc(var(--w-fs) * 2.24) calc(var(--w-fs) * 0.94) minmax(0, 1fr); +} + +.a86-code-blank .a86-code-text { + color: var(--w-dim); +} + +.a86-code-label .a86-code-text { + color: var(--w-read); +} + + +.a86-code-row.is-next { + border-left-color: var(--w-change); + background: var(--w-change-bg); + font-weight: 600; +} + +/* registers ------------------------------------------------------------- */ + +.a86-regs { + display: grid; + /* Wide enough for 0x and 16 hex digits on one line in the value's own + monospace size (about 0.6em a character), plus the card's padding. */ + grid-template-columns: repeat(auto-fill, minmax(calc(var(--w-fs) * 10.2 + 1.1rem), 1fr)); + gap: 0.35rem; +} + +.a86-reg { + border: 1px solid var(--w-rule); + border-radius: 3px; + padding: 0.3rem 0.4rem; + background: var(--w-surface-2); + display: flex; + flex-direction: column; + gap: 0.05rem; + min-width: 0; +} + +.a86-reg-name { + font-family: var(--w-mono); + font-weight: 700; + font-size: calc(var(--w-fs) * 0.95); +} + +.a86-reg-role { + font-family: var(--w-sans); + font-size: calc(var(--w-fs) * 0.86); + color: var(--w-dim); +} + +.a86-reg-value { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.9); + overflow-wrap: anywhere; + line-height: 1.3; +} + +.a86-reg-prev { + font-size: calc(var(--w-fs) * 0.85); + color: var(--w-dim); + min-height: 0.8rem; +} + +.a86-reg.is-changed { + border-color: var(--w-change); + background: var(--w-change-bg); + animation: a86-pulse 420ms ease-out; +} + +.a86-reg.is-changed .a86-reg-value { + color: var(--w-change); + font-weight: 700; +} + +.a86-reg-widths { + margin-top: 0.3rem; + border-top: 1px dashed var(--w-rule); + padding-top: 0.25rem; +} + +.a86-width-row { + display: grid; + grid-template-columns: calc(var(--w-fs) * 2.83) 1fr auto; + gap: 0.3rem; + font-size: calc(var(--w-fs) * 0.87); +} + +.a86-width-name { + font-family: var(--w-mono); + color: var(--w-read); +} + +.a86-width-bits { + font-family: var(--w-mono); +} + +.a86-width-size { + font-family: var(--w-sans); + color: var(--w-dim); +} + +@keyframes a86-pulse { + from { + box-shadow: 0 0 0 3px var(--w-change-bg); + } + + to { + box-shadow: 0 0 0 0 transparent; + } +} + +@media (prefers-reduced-motion: reduce) { + + .a86-reg.is-changed, + .a86-flag.is-changed, + .a86-cell.is-read { + animation: none; + } +} + +.a86-explain-fault { + color: var(--w-miss); + background: var(--w-miss-bg); + border-left: 3px solid var(--w-miss); + padding: 0.3rem 0.5rem; +} + +/* flags ----------------------------------------------------------------- */ + +.a86-flags { + display: flex; + flex-wrap: wrap; + gap: 0.4rem; +} + +.a86-flag { + display: flex; + align-items: center; + gap: 0.3rem; + border: 1px solid var(--w-rule); + border-radius: 3px; + padding: 0.25rem 0.45rem; + background: var(--w-surface-2); + cursor: help; +} + +.a86-flag-name { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.91); +} + +.a86-flag-dot { + width: calc(var(--w-fs) * 0.65); + height: 0.55rem; + border-radius: 50%; + border: 1px solid var(--w-rule); + background: transparent; +} + +.a86-flag-value { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.88); + color: var(--w-dim); +} + +.a86-flag.is-on { + border-color: var(--w-change); +} + +.a86-flag.is-on .a86-flag-dot { + background: var(--w-change); + border-color: var(--w-change); +} + +.a86-flag.is-changed { + background: var(--w-change-bg); + animation: a86-pulse 420ms ease-out; +} + +/* A flag the last conditional instruction consulted gets a solid read-blue + ring; one the next instruction will consult, a dashed one. */ +.a86-flag.is-consulted { + box-shadow: 0 0 0 2px var(--w-read); +} + +.a86-flag.is-wanted { + outline: 1px dashed var(--w-read); + outline-offset: 2px; +} + +.a86-flag-reading { + color: var(--w-read); +} + +.a86-flag-note { + font-size: calc(var(--w-fs) * 0.9); + color: var(--w-dim); + margin: 0.4rem 0 0; + min-height: 1.1rem; +} + +/* memory strip ---------------------------------------------------------- */ + +.a86-mem { + display: flex; + flex-direction: column; + gap: 0.6rem; +} + +.a86-strip-wrap { + display: flex; + align-items: flex-start; + gap: 0.5rem; + min-width: 0; +} + +.a86-strip-label { + display: flex; + flex-direction: column; + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.93); + padding-top: 0.15rem; +} + +.a86-strip-addr { + font-size: calc(var(--w-fs) * 0.83); + color: var(--w-dim); +} + +.a86-strip { + display: flex; + overflow-x: auto; + padding-bottom: 0.15rem; +} + +.a86-cell { + display: flex; + flex-direction: column; + align-items: center; + min-width: calc(var(--w-fs) * 1.59); + border: 1px solid var(--w-rule); + border-right-width: 0; + background: var(--w-surface); +} + +.a86-cell:last-child { + border-right-width: 1px; +} + +.a86-cell-letter { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.98); + line-height: 1.5; +} + +.a86-cell-pos { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.8); + color: var(--w-dim); + border-top: 1px solid var(--w-rule); + width: 100%; + text-align: center; +} + +.a86-cell.in-window { + background: var(--w-surface-2); +} + +.a86-cell.is-match { + background: var(--w-match-bg); +} + +.a86-cell.is-match .a86-cell-letter { + color: var(--w-match); + font-weight: 700; +} + +.a86-cell.is-read { + background: var(--w-read-bg); + border-color: var(--w-read); + border-right-width: 1px; + margin-right: -1px; + position: relative; + z-index: 1; + animation: a86-pulse 420ms ease-out; +} + +.a86-cell.is-read .a86-cell-letter { + color: var(--w-read); + font-weight: 700; +} + +.a86-cell.is-write { + background: var(--w-write-bg); + border-color: var(--w-write); +} + +.a86-cell.is-write .a86-cell-letter { + color: var(--w-write); + font-weight: 700; +} + +/* address arithmetic ---------------------------------------------------- */ + +.a86-addr-sum { + display: flex; + flex-wrap: wrap; + align-items: stretch; + gap: 0.3rem; +} + +.a86-addr-part { + border: 1px solid var(--w-rule); + border-radius: 3px; + padding: 0.25rem 0.4rem; + background: var(--w-surface-2); + display: flex; + flex-direction: column; + min-width: 0; +} + +.a86-addr-part.is-result { + border-color: var(--w-read); + background: var(--w-read-bg); +} + +.a86-addr-role { + font-family: var(--w-sans); + font-size: calc(var(--w-fs) * 0.83); + color: var(--w-dim); +} + +.a86-addr-expr { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.89); +} + +.a86-addr-val { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.91); + font-weight: 600; +} + +.a86-addr-op { + align-self: center; + color: var(--w-dim); + font-size: calc(var(--w-fs) * 1); +} + +.a86-addr-note { + font-size: calc(var(--w-fs) * 0.91); + color: var(--w-dim); + margin: 0.45rem 0 0; +} + +/* data flow ------------------------------------------------------------- */ + +/* Both diagrams are drawn at a fixed size in their viewBox. Stretched to a + full-width panel they scaled up by a third, which made their labels + larger than the body text around them. Capping the width keeps them in + proportion; the font sizes below are set for that capped size. */ +.a86-flow-svg { + display: block; + width: 100%; + max-width: 820px; + height: auto; + margin: 0 auto; +} + +.a86-flow-box rect { + fill: var(--w-surface-2); + stroke: var(--w-rule); +} + +.a86-flow-box.is-source rect { + stroke: var(--w-read); +} + +.a86-flow-box.is-dest rect { + fill: var(--w-change-bg); + stroke: var(--w-change); +} + +.a86-flow-box.is-flags rect { + fill: var(--w-surface-2); + stroke: var(--w-change); + stroke-dasharray: 3 2; +} + +.a86-flow-box.is-control rect { + fill: var(--w-match-bg); + stroke: var(--w-match); +} + +.a86-flow-label { + font-family: var(--w-mono); + font-size: 12px; + fill: var(--w-dim); +} + +.a86-flow-value { + font-family: var(--w-mono); + font-size: 14px; + fill: var(--w-ink); + font-weight: 600; +} + +/* Only the flow arrows get the flow marker. The earlier combined rule also + matched .a86-path-edge and pointed it at a marker that exists in a + different svg, which silently removed every datapath arrowhead. */ +.a86-flow-arrow { + stroke: var(--w-dim); + stroke-width: 1.2; + fill: none; +} + +.a86-flow-svg path[marker-end] { + fill: none; +} + +.a86-flow-svg marker path { + fill: var(--w-dim); + stroke: none; +} + +.a86-flow-op rect { + fill: var(--w-surface); + stroke: var(--w-ink); + stroke-width: 1.4; +} + +.a86-flow-opname { + font-family: var(--w-mono); + font-size: 16px; + font-weight: 700; + fill: var(--w-ink); +} + +.a86-flow-opkind { + font-family: var(--w-sans); + font-size: 11px; + fill: var(--w-dim); +} + +.a86-flow-gloss { + font-size: calc(var(--w-fs) * 0.93); + color: var(--w-dim); + margin: 0.3rem 0 0; +} + +/* datapath -------------------------------------------------------------- */ + +.a86-path-svg { + display: block; + width: 100%; + max-width: 860px; + height: auto; + margin: 0 auto; +} + +.a86-path-node rect { + fill: var(--w-surface-2); + stroke: var(--w-rule); +} + +.a86-path-label { + font-family: var(--w-sans); + font-size: 12px; + fill: var(--w-dim); +} + +.a86-path-node.is-active rect { + fill: var(--w-change-bg); + stroke: var(--w-change); + stroke-width: 1.6; +} + +.a86-path-node.is-active .a86-path-label { + fill: var(--w-ink); + font-weight: 600; +} + +.a86-path-edge { + stroke: var(--w-rule); + stroke-width: 1.2; + fill: none; +} + +.a86-path-svg marker path { + fill: var(--w-rule); + stroke: none; +} + +.a86-path-edge.is-active { + stroke: var(--w-change); + stroke-width: 2; +} + +.a86-path-caption { + font-size: calc(var(--w-fs) * 0.93); + color: var(--w-dim); + margin: 0.35rem 0 0; +} + +/* explanation ----------------------------------------------------------- */ + +.a86-explain p { + margin: 0 0 0.4rem; +} + +.a86-explain-instr { + font-family: var(--w-mono); + background: var(--w-surface-2); + padding: 0.05rem 0.3rem; + border-radius: 2px; + white-space: pre; +} + +.a86-explain-effect { + color: var(--w-change); +} + +/* counters -------------------------------------------------------------- */ + +.a86-counters { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(calc(var(--w-fs) * 7.3), 1fr)); + gap: 0.4rem; +} + +.a86-counter { + display: flex; + flex-direction: column; + padding: 0.3rem 0.45rem; + border: 1px solid var(--w-rule); + border-radius: 3px; + background: var(--w-surface-2); +} + +.a86-counter-value { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 1.22); + font-weight: 700; +} + +.a86-counter-label { + font-family: var(--w-sans); + font-size: calc(var(--w-fs) * 0.85); + color: var(--w-dim); + line-height: 1.25; +} + +/* tables ---------------------------------------------------------------- */ + +.a86-table { + width: 100%; + border-collapse: collapse; + font-size: calc(var(--w-fs) * 0.91); +} + +.a86-table th { + font-family: var(--w-sans); + text-align: left; + font-weight: 600; + color: var(--w-dim); + border-bottom: 1px solid var(--w-rule); + padding: 0.18rem 0.35rem 0.25rem; + font-size: calc(var(--w-fs) * 0.87); +} + +.a86-table td { + padding: 0.14rem 0.35rem; + border-bottom: 1px solid var(--w-surface-2); +} + +.a86-table tr.is-current { + background: var(--w-change-bg); +} + +.a86-table tr.is-current code { + font-weight: 700; +} + +.a86-table tr.is-costly td { + color: var(--w-miss); +} + +.a86-trace-wrap { + max-height: 15rem; + overflow-y: auto; +} + +.a86-trace-step { + color: var(--w-dim); + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.87); +} + +/* vector registers ------------------------------------------------------ */ + +.a86-vecs { + display: flex; + flex-direction: column; + gap: 0.45rem; +} + +.a86-vec-row { + display: flex; + align-items: flex-start; + gap: 0.5rem; + min-width: 0; +} + +.a86-vec-label { + display: flex; + flex-direction: column; + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.93); + min-width: calc(var(--w-fs) * 4.95); + padding-top: 0.15rem; +} + +.a86-vec-role { + font-family: var(--w-sans); + font-size: calc(var(--w-fs) * 0.82); + color: var(--w-dim); + line-height: 1.2; +} + +.a86-vec-strip { + display: flex; + overflow-x: auto; +} + +.a86-vec-cell { + display: flex; + flex-direction: column; + align-items: center; + min-width: calc(var(--w-fs) * 1.53); + border: 1px solid var(--w-rule); + border-right-width: 0; + background: var(--w-surface); +} + +.a86-vec-cell:last-child { + border-right-width: 1px; +} + +.a86-vec-val { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.94); + line-height: 1.45; +} + +.a86-vec-lane { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.78); + color: var(--w-dim); + border-top: 1px solid var(--w-rule); + width: 100%; + text-align: center; +} + +.a86-vec-cell.is-yes { + background: var(--w-match-bg); +} + +.a86-vec-cell.is-yes .a86-vec-val { + color: var(--w-match); + font-weight: 700; +} + +.a86-vec-cell.is-no .a86-vec-val { + color: var(--w-dim); +} + +.a86-vec-cell.is-letter .a86-vec-val { + color: var(--w-ink); +} + +.a86-vec-cell.is-bit { + background: var(--w-surface-2); +} + +.a86-vec-cell.is-changed { + border-color: var(--w-change); + border-right-width: 1px; + margin-right: -1px; +} + + +.a86-vec-note { + font-size: calc(var(--w-fs) * 0.9); + color: var(--w-dim); + margin: 0.35rem 0 0; + min-height: 1.1rem; +} + +/* ================================================================ hardware + Views from hwviews.js. Same tokens, same rules: everything neutral is + mixed from the page, only the accents are stated. */ + +.a86-hw-machine { + font-size: calc(var(--w-fs) * 0.87); + color: var(--w-dim); + margin: 0.5rem 0 0; +} + +.a86-legend { + display: flex; + flex-wrap: wrap; + gap: 0.25rem 0.9rem; + font-size: calc(var(--w-fs) * 0.88); + color: var(--w-dim); + margin: 0.45rem 0 0; +} + +.a86-legend-item { + display: inline-flex; + align-items: center; + gap: 0.3rem; +} + +.a86-swatch { + display: inline-block; + width: calc(var(--w-fs) * 0.94); + height: 0.65rem; + border-radius: 2px; + border: 1px solid var(--w-rule); + background: var(--w-surface-2); +} + +.a86-hier-label { + font-family: var(--w-sans); + font-size: calc(var(--w-fs) * 0.88); + font-weight: 600; + color: var(--w-dim); + margin: 0.6rem 0 0.3rem; +} + +/* encoding -------------------------------------------------------------- */ + +.a86-enc-head { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 0.6rem; + margin: 0 0 0.5rem; +} + +.a86-enc-addr { + color: var(--w-dim); + font-size: calc(var(--w-fs) * 0.93); +} + +.a86-enc-text { + font-weight: 600; +} + +.a86-enc-strip { + display: flex; + flex-wrap: wrap; + gap: 0.3rem; + margin-bottom: 0.6rem; +} + +.a86-enc-part { + --part: var(--a86-enc-prefix); + display: flex; + flex-direction: column; + align-items: center; + border: 1px solid var(--part); + border-radius: 3px; + background: color-mix(in srgb, var(--part) 12%, var(--w-page)); + padding: 0.2rem 0.3rem 0.15rem; +} + +.a86-enc-part.is-rex, +.a86-enc-detail.is-rex { + --part: var(--a86-enc-rex); +} + +.a86-enc-part.is-opcode, +.a86-enc-detail.is-opcode { + --part: var(--a86-enc-opcode); +} + +.a86-enc-part.is-modrm, +.a86-enc-detail.is-modrm { + --part: var(--a86-enc-modrm); +} + +.a86-enc-part.is-sib, +.a86-enc-detail.is-sib { + --part: var(--a86-enc-sib); +} + +.a86-enc-part.is-disp, +.a86-enc-detail.is-disp, +.a86-enc-part.is-rel, +.a86-enc-detail.is-rel { + --part: var(--a86-enc-disp); +} + +.a86-enc-part.is-imm, +.a86-enc-detail.is-imm { + --part: var(--a86-enc-imm); +} + +.a86-enc-bytes { + display: flex; + gap: 0.25rem; +} + +.a86-enc-byte { + font-size: calc(var(--w-fs) * 1.17); + font-weight: 700; + color: var(--part); +} + +.a86-enc-kind { + font-size: calc(var(--w-fs) * 0.83); + color: var(--w-dim); + font-family: var(--w-sans); +} + +.a86-enc-details { + display: grid; + gap: 0.4rem; +} + +.a86-enc-detail { + --part: var(--a86-enc-prefix); + border-left: 3px solid var(--part); + padding: 0.15rem 0 0.2rem 0.5rem; +} + +.a86-enc-detail-head { + display: flex; + gap: 0.5rem; + align-items: baseline; +} + +.a86-enc-detail-name { + font-weight: 600; + font-size: calc(var(--w-fs) * 0.93); + color: var(--part); +} + +.a86-enc-detail-bytes { + font-size: calc(var(--w-fs) * 0.9); +} + +.a86-enc-detail-text { + font-size: calc(var(--w-fs) * 0.91); +} + +.a86-enc-bits { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; + margin-top: 0.3rem; +} + +.a86-enc-field { + display: flex; + flex-direction: column; + min-width: calc(var(--w-fs) * 3.53); +} + +.a86-enc-field-bits { + display: flex; +} + +.a86-enc-bit { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.95); + width: calc(var(--w-fs) * 1.35); + text-align: center; + border: 1px solid var(--w-rule); + border-right-width: 0; + background: var(--w-surface-2); +} + +.a86-enc-bit:last-child { + border-right-width: 1px; +} + +.a86-enc-field-name { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.85); + color: var(--part); + font-weight: 600; +} + +.a86-enc-field-meaning { + font-size: calc(var(--w-fs) * 0.85); + color: var(--w-dim); + max-width: 16rem; +} + +/* bits ------------------------------------------------------------------ */ + +.a86-bits-title { + margin: 0 0 0.45rem; +} + +.a86-bits-grid { + overflow-x: auto; + padding-bottom: 0.2rem; +} + +.a86-bits-row { + display: flex; + align-items: center; + gap: 0.5rem; + white-space: nowrap; +} + +.a86-bits-label { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.89); + width: calc(var(--w-fs) * 11.19); + flex: none; + text-align: right; + color: var(--w-dim); + overflow: hidden; + text-overflow: ellipsis; +} + +.a86-bits-cells { + display: inline-flex; + flex: none; +} + +.a86-bits-cell { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.9); + width: calc(var(--w-fs) * 0.92); + text-align: center; + line-height: 1.45; + color: var(--w-dim); +} + +.a86-bits-cell.is-nibble { + margin-left: 0.28rem; +} + +.a86-bits-extra { + width: calc(var(--w-fs) * 1.3); + color: var(--w-change); + font-weight: 700; + margin-right: calc(var(--w-fs) * 0.24); + border-right: 1px dashed var(--w-rule); +} + +.a86-bits-row.is-result .a86-bits-cell { + color: var(--w-ink); + border-top: 1px solid var(--w-ink); +} + +.a86-bits-row.is-result .a86-bits-extra { + border-top: 0; +} + +.a86-bits-cell.is-one { + color: var(--w-ink); + font-weight: 700; +} + +.a86-bits-cell.is-top { + background: var(--w-surface-2); +} + +.a86-bits-cell.is-carry { + color: var(--w-change); + font-weight: 700; +} + +.a86-bits-row.is-carries .a86-bits-cell { + font-size: calc(var(--w-fs) * 0.84); +} + +.a86-bits-row.is-muted .a86-bits-cell { + text-decoration: line-through; + opacity: 0.6; +} + +.a86-bits-cell.is-out { + color: var(--w-miss); + font-weight: 700; + outline: 1px solid var(--w-miss); + outline-offset: -1px; +} + +.a86-bits-value { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.89); + flex: none; + min-width: 7rem; +} + +.a86-bits-note { + font-size: calc(var(--w-fs) * 0.85); + color: var(--w-dim); + white-space: normal; +} + +.a86-bits-flags { + list-style: none; + padding: 0; + margin: 0.5rem 0 0; + font-size: calc(var(--w-fs) * 0.91); + display: grid; + gap: 0.15rem; +} + +.a86-bits-flagname { + font-weight: 700; + color: var(--w-dim); +} + +.a86-bits-flagname.is-on { + color: var(--w-change); +} + +.a86-bits-wide p { + margin: 0 0 0.3rem; +} + +/* stack ----------------------------------------------------------------- */ + +.a86-stack-list { + display: flex; + flex-direction: column; +} + +.a86-stack-slot { + /* Address, value, and pointer tag stay on one line; the note takes the + rest of the line, and drops to its own line when the panel is narrow, + instead of being squeezed into a column one word wide. */ + display: flex; + flex-wrap: wrap; + align-items: baseline; + column-gap: 0.8rem; + row-gap: 0.05rem; + border: 1px solid var(--w-rule); + border-bottom-width: 0; + padding: 0.2rem 0.45rem; + font-size: calc(var(--w-fs) * 0.9); +} + +.a86-stack-addr, +.a86-stack-val { + flex: none; +} + +.a86-stack-tags { + order: 2; +} + +.a86-stack-note { + order: 3; + flex: 1 1 calc(var(--w-fs) * 16.49); +} + +.a86-stack-tags:empty { + display: none; +} + +.a86-stack-slot:last-child { + border-bottom-width: 1px; +} + +.a86-stack-addr { + color: var(--w-dim); +} + +.a86-stack-note { + font-size: calc(var(--w-fs) * 0.88); + color: var(--w-dim); + min-width: 0; +} + +.a86-stack-slot.is-free { + opacity: 0.5; + background: repeating-linear-gradient(135deg, transparent 0 6px, var(--w-surface-2) 6px 7px); +} + +.a86-stack-slot.is-write { + background: var(--w-write-bg); + border-color: var(--w-write); + opacity: 1; +} + +.a86-stack-slot.is-write .a86-stack-val { + color: var(--w-write); + font-weight: 700; +} + +.a86-stack-slot.is-read { + background: var(--w-read-bg); + border-color: var(--w-read); +} + +.a86-stack-slot.is-read .a86-stack-val { + color: var(--w-read); + font-weight: 700; +} + +.a86-stack-tags { + display: flex; + gap: 0.25rem; +} + +.a86-stack-ptr { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.85); + font-weight: 700; + padding: 0 0.3rem; + border-radius: 2px; + color: var(--w-page); + background: var(--w-change); +} + +.a86-stack-ptr.is-rbp { + background: var(--w-dim); +} + +.a86-stack-more { + font-size: calc(var(--w-fs) * 0.87); + color: var(--w-dim); + padding: 0 0 0.2rem 0.4rem; +} + +.a86-stack-foot { + font-size: calc(var(--w-fs) * 0.9); + margin: 0.45rem 0 0; +} + +/* cache ----------------------------------------------------------------- */ + +.a86-cache-shape { + font-size: calc(var(--w-fs) * 0.93); + margin: 0 0 0.5rem; +} + +.a86-cache-access { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.6rem; + margin-bottom: 0.55rem; +} + +.a86-cache-access-what { + font-size: calc(var(--w-fs) * 0.93); +} + +.a86-split { + display: inline-flex; +} + +.a86-split-part { + display: flex; + flex-direction: column; + align-items: center; + padding: 0.1rem 0.35rem; + border: 1px solid var(--w-rule); + border-right-width: 0; + background: var(--w-surface-2); +} + +.a86-split-part:last-child { + border-right-width: 1px; +} + +.a86-split-part code { + font-size: calc(var(--w-fs) * 0.93); + letter-spacing: 0.04em; +} + +.a86-split-part span { + font-size: calc(var(--w-fs) * 0.83); + color: var(--w-dim); +} + +.a86-split-part.is-index { + background: var(--w-read-bg); + border-color: var(--w-read); +} + +.a86-split-part.is-index code { + color: var(--w-read); + font-weight: 700; +} + +.a86-split-part.is-offset code { + color: var(--w-dim); +} + +.a86-cache-wrap { + overflow-x: auto; +} + +.a86-cache-grid { + border-collapse: collapse; + font-size: calc(var(--w-fs) * 0.89); +} + +.a86-cache-grid th { + font-family: var(--w-sans); + font-weight: 600; + color: var(--w-dim); + font-size: calc(var(--w-fs) * 0.85); + padding: 0.1rem 0.35rem; + text-align: left; +} + +.a86-cache-grid tbody th { + text-align: right; + font-family: var(--w-mono); +} + +.a86-cache-grid tr.is-active th { + color: var(--w-read); +} + +.a86-cache-grid tr.is-active td { + border-top-color: var(--w-read); + border-bottom-color: var(--w-read); +} + +.a86-cache-cell { + border: 1px solid var(--w-rule); + padding: 0.15rem 0.35rem; + min-width: calc(var(--w-fs) * 11.19); + vertical-align: top; + background: var(--w-surface); +} + +.a86-cache-cell>* { + display: block; +} + +.a86-cache-cell.is-empty { + background: var(--w-surface-2); +} + +.a86-cache-cell.is-hit { + background: var(--w-match-bg); + border-color: var(--w-match); +} + +.a86-cache-cell.is-hit .a86-cache-tag { + color: var(--w-match); + font-weight: 700; +} + +.a86-cache-cell.is-fill { + background: var(--w-change-bg); + border-color: var(--w-change); +} + +.a86-cache-cell.is-fill .a86-cache-tag { + color: var(--w-change); + font-weight: 700; +} + +.a86-cache-cell.is-prefetch { + background: var(--w-surface-2); + border-style: dashed; + border-color: var(--w-change); +} + +.a86-cache-data { + font-size: calc(var(--w-fs) * 0.94); + letter-spacing: 0.06em; +} + +.a86-cache-data.is-hex { + font-size: calc(var(--w-fs) * 0.87); + letter-spacing: 0; + color: var(--w-dim); +} + +.a86-cache-meta { + display: flex !important; + gap: 0.4rem; + font-size: calc(var(--w-fs) * 0.83); + color: var(--w-dim); +} + +.a86-cache-dirty { + color: var(--w-write); + font-weight: 700; +} + +.a86-cache-pf { + color: var(--w-change); +} + +.a86-cache-events { + list-style: none; + padding: 0; + margin: 0.5rem 0 0; + font-size: calc(var(--w-fs) * 0.91); + display: grid; + gap: 0.2rem; +} + +.a86-cache-events li { + border-left: 3px solid var(--w-rule); + padding-left: 0.45rem; +} + +.a86-cache-events li.is-hit { + border-left-color: var(--w-match); +} + +.a86-cache-events li.is-miss { + border-left-color: var(--w-miss); +} + +.a86-cache-events li.is-prefetch { + border-left-color: var(--w-change); + border-left-style: dashed; +} + +.a86-cache-stats { + font-size: calc(var(--w-fs) * 0.9); + color: var(--w-dim); + margin: 0.4rem 0 0; +} + +/* hierarchy ------------------------------------------------------------- */ + +.a86-hier-ladder { + display: flex; + flex-direction: column; + gap: 0.25rem; + container-type: inline-size; +} + +.a86-hier-name { + grid-area: name; +} + +.a86-hier-shape { + grid-area: shape; +} + +.a86-hier-lat { + grid-area: lat; +} + +.a86-hier-count { + grid-area: count; +} + +.a86-hier-row { + display: grid; + /* level | shape (may wrap) | latency bar and label | counts. The latency + column never goes below what "200 cycles" and a short bar need, and + the counts take exactly their own width, so the two cannot overlap. */ + grid-template-areas: "name shape lat count"; + grid-template-columns: calc(var(--w-fs) * 5.5) minmax(0, 1fr) minmax(calc(var(--w-fs) * 9.5), 1.2fr) max-content; + gap: 0.5rem; + align-items: center; + border: 1px solid var(--w-rule); + border-radius: 3px; + padding: 0.2rem 0.45rem; + font-size: calc(var(--w-fs) * 0.9); + background: var(--w-surface); +} + +/* In a narrow panel the shape moves under the level's name, so the latency + and the counts keep enough room to stay on one line. */ +@container (max-width: 34rem) { + .a86-hier-row { + grid-template-areas: "name lat count" "shape lat count"; + grid-template-columns: minmax(0, 1fr) minmax(calc(var(--w-fs) * 8), 1.2fr) max-content; + row-gap: 0; + } +} + +.a86-hier-name { + display: flex; + flex-direction: column; +} + +.a86-hier-name span, +.a86-hier-shape { + font-size: calc(var(--w-fs) * 0.85); + color: var(--w-dim); +} + +.a86-hier-lat { + display: flex; + align-items: center; + gap: 0.35rem; + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.87); +} + +.a86-hier-lat span { + white-space: nowrap; +} + +.a86-hier-bar { + flex: 0 1 auto; + min-width: 0.3rem; + max-width: 65%; +} + +.a86-hier-bar { + height: 0.45rem; + border-radius: 2px; + background: var(--w-rule); +} + +.a86-hier-count { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.85); + color: var(--w-dim); + text-align: right; +} + +.a86-hier-row.is-hit { + border-color: var(--w-match); + background: var(--w-match-bg); +} + +.a86-hier-row.is-hit .a86-hier-bar { + background: var(--w-match); +} + +.a86-hier-row.is-miss { + border-color: var(--w-miss); + background: var(--w-miss-bg); +} + +.a86-hier-row.is-miss .a86-hier-bar { + background: var(--w-miss); +} + +.a86-hier-paths { + list-style: none; + padding: 0; + margin: 0; + font-size: calc(var(--w-fs) * 0.9); + display: grid; + gap: 0.2rem; +} + +.a86-hier-paths li { + border-left: 3px solid var(--w-read); + padding-left: 0.45rem; +} + +.a86-hier-paths li.is-far { + border-left-color: var(--w-miss); +} + +.a86-hier-paths li.is-near { + border-left-color: var(--w-match); +} + +.a86-hier-cost { + font-family: var(--w-mono); + color: var(--w-dim); +} + +.a86-hier-total, +.a86-hier-tlb { + font-size: calc(var(--w-fs) * 0.9); + color: var(--w-dim); + margin: 0.45rem 0 0; +} + +/* paging ---------------------------------------------------------------- */ + +.a86-pg-head { + margin: 0 0 0.35rem; + font-size: calc(var(--w-fs) * 0.94); +} + +.a86-pg-split { + display: flex; + flex-wrap: wrap; +} + +.a86-pg-field { + display: flex; + flex-direction: column; + align-items: center; + padding: 0.1rem 0.4rem; + border: 1px solid var(--w-rule); + border-right-width: 0; + background: var(--w-surface-2); +} + +.a86-pg-field:last-child { + border-right-width: 1px; +} + +.a86-pg-field code { + font-size: calc(var(--w-fs) * 0.9); + letter-spacing: 0.03em; +} + +.a86-pg-field span { + font-size: calc(var(--w-fs) * 0.84); + color: var(--w-dim); +} + +.a86-pg-field.is-offset code { + color: var(--w-dim); +} + +.a86-pg-tlb { + font-size: calc(var(--w-fs) * 0.91); + border-left: 3px solid var(--w-rule); + padding-left: 0.45rem; + margin: 0.5rem 0; +} + +.a86-pg-tlb.is-hit { + border-left-color: var(--w-match); +} + +.a86-pg-tlb.is-miss { + border-left-color: var(--w-miss); +} + +.a86-pg-walk { + display: grid; + gap: 0.25rem; +} + +.a86-pg-step { + display: grid; + grid-template-columns: calc(var(--w-fs) * 7.66) calc(var(--w-fs) * 8.01) minmax(0, 1fr); + gap: 0.1rem 0.5rem; + font-size: calc(var(--w-fs) * 0.89); + border: 1px solid var(--w-rule); + border-radius: 3px; + padding: 0.2rem 0.4rem; +} + +.a86-pg-step>.a86-muted, +.a86-pg-step>strong { + grid-column: 2 / -1; +} + +.a86-pg-table { + font-weight: 600; +} + +.a86-pg-frame { + color: var(--w-read); +} + +.a86-pg-result { + font-size: calc(var(--w-fs) * 0.93); + margin: 0.5rem 0 0; +} + +.a86-pg-tlbtable { + max-width: calc(var(--w-fs) * 30.62); +} + +/* pipeline -------------------------------------------------------------- */ + +.a86-pipe-wrap { + overflow-x: auto; +} + +.a86-pipe-grid { + border-collapse: collapse; + font-size: calc(var(--w-fs) * 0.88); +} + +.a86-pipe-grid th { + font-family: var(--w-mono); + font-weight: 400; + color: var(--w-dim); + font-size: calc(var(--w-fs) * 0.82); + padding: 0 0.1rem 0.15rem; + text-align: center; +} + +.a86-pipe-grid th.is-now { + color: var(--w-change); + font-weight: 700; +} + +.a86-pipe-instr { + text-align: left !important; + white-space: nowrap; + padding-right: 0.6rem !important; +} + +/* One line per instruction, whatever the page does to inline code; a long + one ends in an ellipsis rather than making its row three lines tall. */ +.a86 .a86-pipe-instr code { + display: inline-block; + max-width: calc(var(--w-fs) * 11); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + vertical-align: bottom; +} + +.a86-pipe-cell { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.82); + width: calc(var(--w-fs) * 1.95); + min-width: calc(var(--w-fs) * 1.95); + height: calc(var(--w-fs) * 1.35); + text-align: center; + border: 1px solid var(--w-surface-2); + color: var(--w-ink); +} + +.a86-pipe-cell.is-if, +.a86-pipe-cell.is-id, +.a86-pipe-cell.is-ex, +.a86-pipe-cell.is-mem, +.a86-pipe-cell.is-wb { + background: var(--w-surface-2); + border-color: var(--w-rule); +} + +.a86-pipe-cell.is-mem { + background: var(--w-read-bg); +} + +.a86-pipe-cell.is-busy { + color: var(--w-dim); +} + +.a86-pipe-cell.is-stall { + background: var(--w-change-bg); + border-color: var(--w-change); + color: var(--w-change); +} + +.a86-pipe-cell.is-squashed { + background: var(--w-miss-bg); + border-color: var(--w-miss); + color: var(--w-miss); + text-decoration: line-through; +} + +.a86-pipe-cell.is-now { + box-shadow: inset 0 0 0 1px var(--w-change); +} + +.a86-pipe-grid tr.is-current .a86-pipe-instr { + font-weight: 700; +} + +.a86-pipe-grid tr.is-current .a86-pipe-instr code { + color: var(--w-change); +} + +.a86-pipe-grid tr.is-future { + opacity: 0.55; +} + +.a86-pipe-grid tr.is-ghost .a86-pipe-instr { + color: var(--w-miss); +} + +.a86-pipe-grid tr.is-mispredicted .a86-pipe-instr code { + text-decoration: underline wavy var(--w-miss); +} + +.a86-swatch.is-stage { + background: var(--w-surface-2); +} + +.a86-swatch.is-stall { + background: var(--w-change-bg); + border-color: var(--w-change); +} + +.a86-swatch.is-squashed { + background: var(--w-miss-bg); + border-color: var(--w-miss); +} + +.a86-pipe-now { + display: grid; + grid-template-columns: repeat(5, minmax(0, 1fr)); + gap: 0.3rem; + margin-top: 0.55rem; +} + +.a86-pipe-stage { + border: 1px solid var(--w-rule); + border-radius: 3px; + padding: 0.2rem 0.35rem; + display: flex; + flex-direction: column; + min-width: 0; + font-size: calc(var(--w-fs) * 0.87); +} + +.a86-pipe-stage code { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.a86-pipe-stage-name { + font-weight: 700; + font-size: calc(var(--w-fs) * 0.84); + color: var(--w-dim); +} + +.a86-pipe-notes { + list-style: none; + padding: 0; + margin: 0.5rem 0 0; + font-size: calc(var(--w-fs) * 0.91); + display: grid; + gap: 0.2rem; +} + +.a86-pipe-notes li { + border-left: 3px solid var(--w-change); + padding-left: 0.45rem; +} + +.a86-pipe-notes li.is-control { + border-left-color: var(--w-miss); +} + +.a86-pipe-notes li.is-memory { + border-left-color: var(--w-read); +} + +.a86-pipe-notes li.a86-muted { + border-left-color: var(--w-rule); +} + +.a86-pipe-total { + font-size: calc(var(--w-fs) * 0.9); + color: var(--w-dim); + margin: 0.45rem 0 0; +} + +/* uops ------------------------------------------------------------------ */ + +.a86-uops-wrap { + overflow-x: auto; +} + +.a86-uops-table td { + vertical-align: top; +} + +.a86-uops-note { + color: var(--w-dim); + min-width: calc(var(--w-fs) * 16.49); +} + +.a86-uops-table tr.is-load td:nth-child(2) { + color: var(--w-read); + font-weight: 600; +} + +.a86-uops-table tr.is-store-data td:nth-child(2), +.a86-uops-table tr.is-store-addr td:nth-child(2) { + color: var(--w-write); + font-weight: 600; +} + +.a86-uops-table tr.is-eliminated td:nth-child(2) { + color: var(--w-match); + font-weight: 600; +} + +/* timeline -------------------------------------------------------------- */ + +.a86-tl-svg { + display: block; + width: 100%; + max-width: 980px; + height: auto; +} + +.a86-tl-grid { + stroke: var(--w-surface-2); + stroke-width: 1; +} + +.a86-tl-tick { + font-family: var(--w-mono); + font-size: 11px; + fill: var(--w-dim); +} + +.a86-tl-label { + font-family: var(--w-mono); + font-size: 12px; + fill: var(--w-ink); +} + +.a86-tl-row.is-future .a86-tl-label { + fill: var(--w-dim); +} + +.a86-tl-row.is-future rect { + opacity: 0.45; +} + +.a86-tl-row.is-current .a86-tl-label { + font-weight: 700; +} + +.a86-tl-highlight { + fill: var(--w-change-bg); +} + +.a86-tl-wait { + fill: var(--w-surface-2); + stroke: var(--w-rule); + stroke-width: 0.5; +} + +.a86-tl-exec { + fill: var(--w-change); +} + +.a86-tl-exec.is-load { + fill: var(--w-read); +} + +.a86-tl-exec.is-miss { + fill: var(--w-miss); +} + +.a86-tl-exec.is-elim { + fill: var(--w-match); +} + +.a86-tl-exec.is-store { + fill: var(--w-write); +} + +.a86-swatch.is-tl-store { + background: var(--w-write); +} + +.a86-tl-done { + fill: var(--w-match-bg); + stroke: var(--w-match); + stroke-width: 0.5; +} + +.a86-tl-retire { + stroke: var(--w-ink); + stroke-width: 1.5; +} + +.a86-tl-now { + stroke: var(--w-change); + stroke-width: 1.5; + stroke-dasharray: 3 2; +} + +.a86-tl-refill { + fill: var(--w-miss-bg); + opacity: 0.8; +} + +.a86-tl-flag { + font-family: var(--w-sans); + font-size: 10px; + fill: var(--w-miss); +} + +.a86-swatch.is-tl-wait { + background: var(--w-surface-2); +} + +.a86-swatch.is-tl-exec { + background: var(--w-change); +} + +.a86-swatch.is-tl-load { + background: var(--w-read); +} + +.a86-swatch.is-tl-miss { + background: var(--w-miss); +} + +.a86-swatch.is-tl-done { + background: var(--w-match-bg); + border-color: var(--w-match); +} + +.a86-swatch.is-tl-refill { + background: var(--w-miss-bg); +} + +.a86-tl-caption { + font-size: calc(var(--w-fs) * 0.93); + margin: 0.45rem 0 0; +} + +.a86-tl-total { + font-size: calc(var(--w-fs) * 0.9); + color: var(--w-dim); + margin: 0.25rem 0 0; +} + +/* bottleneck ------------------------------------------------------------ */ + +.a86-bn-row { + display: grid; + grid-template-columns: calc(var(--w-fs) * 10.01) minmax(0, 1fr) calc(var(--w-fs) * 5.3); + gap: 0.1rem 0.5rem; + align-items: center; + font-size: calc(var(--w-fs) * 0.9); + margin-bottom: 0.3rem; +} + +.a86-bn-track { + height: 0.7rem; + background: var(--w-surface-2); + border-radius: 2px; + overflow: hidden; +} + +.a86-bn-bar { + height: 100%; +} + +.a86-bn-bar.is-actual { + background: var(--w-change); +} + +.a86-bn-bar.is-bound { + background: color-mix(in srgb, var(--w-ink) 40%, transparent); +} + +.a86-bn-value { + font-family: var(--w-mono); + text-align: right; +} + +.a86-bn-note { + grid-column: 2 / -1; + font-size: calc(var(--w-fs) * 0.85); + color: var(--w-dim); +} + +.a86-bn-verdict { + font-size: calc(var(--w-fs) * 0.93); + margin: 0.5rem 0 0; +} + +.a86-bn-ports { + display: flex; + gap: 0.5rem; + flex-wrap: wrap; +} + +.a86-bn-port { + display: flex; + flex-direction: column; + align-items: center; + font-size: calc(var(--w-fs) * 0.85); + width: calc(var(--w-fs) * 3.06); +} + +.a86-bn-port-track { + width: calc(var(--w-fs) * 1.3); + height: 3.5rem; + background: var(--w-surface-2); + border: 1px solid var(--w-rule); + display: flex; + align-items: flex-end; +} + +.a86-bn-port-fill { + width: 100%; + background: var(--w-change); +} + +/* core ------------------------------------------------------------------ */ + +.a86-core-controls { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.35rem; + margin-bottom: 0.45rem; +} + +.a86-core-cols { + display: grid; + grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr) minmax(0, 1fr); + gap: 0.8rem; +} + +@media (max-width: 760px) { + .a86-core-cols { + grid-template-columns: 1fr; + } +} + +.a86-core-list { + list-style: none; + padding: 0; + margin: 0; + display: grid; + gap: 0.12rem; + font-size: calc(var(--w-fs) * 0.88); +} + +.a86-core-list li { + display: grid; + grid-template-columns: calc(var(--w-fs) * 2.83) calc(var(--w-fs) * 4.95) minmax(0, 1fr) calc(var(--w-fs) * 4.24); + gap: 0.3rem; + align-items: baseline; + border: 1px solid var(--w-rule); + border-radius: 2px; + padding: 0.05rem 0.3rem; +} + +.a86-core-text { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.a86-core-id { + color: var(--w-dim); +} + +.a86-core-kind { + color: var(--w-dim); +} + +.a86-core-state { + font-size: calc(var(--w-fs) * 0.84); + text-align: right; +} + +.a86-core-list li.is-running { + border-color: var(--w-change); + background: var(--w-change-bg); +} + +.a86-core-list li.is-done { + background: var(--w-match-bg); +} + +.a86-core-list li.is-retiring { + background: var(--w-match-bg); + border-color: var(--w-match); + font-weight: 700; +} + +.a86-core-list li.is-waiting .a86-core-state { + color: var(--w-dim); +} + +.a86-core-portgrid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 0.25rem; +} + +.a86-core-port { + border: 1px solid var(--w-rule); + border-radius: 3px; + padding: 0.15rem 0.3rem; + display: flex; + flex-direction: column; + font-size: calc(var(--w-fs) * 0.85); + min-width: 0; +} + +.a86-core-portname { + font-weight: 700; +} + +.a86-core-units { + color: var(--w-dim); + font-size: calc(var(--w-fs) * 0.82); +} + +.a86-core-portuop { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--w-dim); +} + +.a86-core-port.is-busy { + border-color: var(--w-change); + background: var(--w-change-bg); +} + +.a86-core-port.is-busy .a86-core-portuop { + color: var(--w-ink); +} + +.a86-core-port.is-start .a86-core-portname { + color: var(--w-change); +} + +.a86-core-rat .a86-table td { + font-size: calc(var(--w-fs) * 0.87); +} + +.a86-core-rat tr.is-pending td { + color: var(--w-change); +} + +.a86-core-ready { + white-space: nowrap; +} + +.a86-core-note { + font-size: calc(var(--w-fs) * 0.91); + margin: 0.5rem 0 0; +} + +/* console --------------------------------------------------------------- */ + +.a86-console-screen { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.95); + background: #16191d; + color: #e6e9ec; + border-radius: 4px; + padding: 0.5rem 0.65rem; + min-height: 3.2rem; + margin: 0; + white-space: pre-wrap; + overflow-wrap: anywhere; +} + +.a86-console-cursor { + display: inline-block; + width: 0.55em; + background: #e6e9ec; + animation: a86-blink 1s steps(1) infinite; +} + +@keyframes a86-blink { + 50% { + opacity: 0; + } +} + +@media (prefers-reduced-motion: reduce) { + .a86-console-cursor { + animation: none; + } +} + +.a86-console-log { + font-size: calc(var(--w-fs) * 0.9); + margin: 0.45rem 0 0; + padding-left: 1.4rem; +} + +.a86-console-log li.is-current code { + color: var(--w-change); + font-weight: 700; +} + +.a86-console-note { + font-size: calc(var(--w-fs) * 0.9); + color: var(--w-dim); + margin: 0.4rem 0 0; +} + +/* perf ------------------------------------------------------------------ */ + +.a86-perf-out { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.9); + line-height: 1.5; + background: var(--w-surface-2); + border-radius: 3px; + padding: 0.5rem 0.6rem; + overflow-x: auto; + margin: 0 0 0.4rem; + white-space: pre; +} + +/* the whole chip -------------------------------------------------------- */ + +.a86-chip-svg { + display: block; + width: 100%; + max-width: 980px; + height: auto; + margin: 0 auto; +} + +.a86-chip-group { + fill: none; + stroke: var(--w-rule); + stroke-dasharray: 4 3; +} + +.a86-chip-grouplabel { + font-family: var(--w-sans); + font-size: 11px; + fill: var(--w-dim); + letter-spacing: 0.04em; +} + +.a86-chip-node rect { + fill: var(--w-surface-2); + stroke: var(--w-rule); +} + +.a86-chip-label { + font-family: var(--w-sans); + font-size: 12px; + fill: var(--w-dim); +} + +.a86-chip-sub { + font-family: var(--w-sans); + font-size: 9px; + fill: var(--w-dim); +} + +.a86-chip-node.is-active rect { + fill: var(--w-change-bg); + stroke: var(--w-change); + stroke-width: 1.6; +} + +.a86-chip-node.is-active .a86-chip-label { + fill: var(--w-ink); + font-weight: 600; +} + +.a86-chip-node.is-hit rect { + fill: var(--w-match-bg); + stroke: var(--w-match); +} + +.a86-chip-node.is-miss rect, +.a86-chip-node.is-bad rect { + fill: var(--w-miss-bg); + stroke: var(--w-miss); +} + +.a86-chip-node.is-far rect { + fill: var(--w-read-bg); + stroke: var(--w-read); +} + +.a86-chip-node.is-store rect { + fill: var(--w-write-bg); + stroke: var(--w-write); +} + +.a86-chip-edge { + stroke: var(--w-rule); + stroke-width: 1.2; + fill: none; +} + +.a86-chip-svg marker path { + fill: var(--w-rule); + stroke: none; +} + +.a86-chip-edge.is-active { + stroke: var(--w-change); + stroke-width: 2; +} + +.a86-chip-edge.is-load { + stroke: var(--w-read); +} + +.a86-chip-edge.is-store { + stroke: var(--w-write); +} + +.a86-chip-caption { + font-size: calc(var(--w-fs) * 0.94); + margin: 0.4rem 0 0; +} + +.a86-swatch.is-chip-active { + background: var(--w-change-bg); + border-color: var(--w-change); +} + +.a86-swatch.is-chip-hit { + background: var(--w-match-bg); + border-color: var(--w-match); +} + +.a86-swatch.is-chip-miss { + background: var(--w-miss-bg); + border-color: var(--w-miss); +} + +.a86-swatch.is-chip-load { + background: var(--w-read); +} + +.a86-swatch.is-chip-store { + background: var(--w-write); +} + + + + +/* sandbox --------------------------------------------------------------- */ + +.a86-sandbox { + margin: 1rem 0 2rem; +} + +.a86-sb-grid { + display: grid; + grid-template-columns: minmax(0, 1.6fr) minmax(0, 1fr); + gap: 0.9rem; + margin-bottom: 0.8rem; +} + +@media (max-width: 760px) { + .a86-sb-grid { + grid-template-columns: 1fr; + } +} + +.a86-sb-label { + display: block; + font-family: var(--w-sans); + font-size: calc(var(--w-fs) * 0.88); + font-weight: 600; + color: var(--w-dim); + margin: 0.5rem 0 0.2rem; +} + +.a86-sb-code, +.a86-sb-setup { + width: 100%; + box-sizing: border-box; + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.94); + line-height: 1.5; + color: var(--w-ink); + background: var(--w-surface-2); + border: 1px solid var(--w-rule); + border-radius: 4px; + padding: 0.5rem 0.6rem; + resize: vertical; + tab-size: 8; +} + +.a86-sb-code:focus, +.a86-sb-setup:focus { + outline: 2px solid var(--w-change-bg); + border-color: var(--w-change); +} + +.a86-sb-row { + display: flex; + flex-wrap: wrap; + gap: 0.4rem; + align-items: center; + margin-bottom: 0.35rem; +} + +.a86-sb-select { + font: inherit; + font-size: calc(var(--w-fs) * 0.94); + color: var(--w-ink); + background: var(--w-surface-2); + border: 1px solid var(--w-rule); + border-radius: 3px; + padding: 0.2rem 0.35rem; + max-width: 100%; +} + +.a86-sb-check { + font-size: calc(var(--w-fs) * 0.93); + display: inline-flex; + align-items: center; + gap: 0.2rem; + cursor: pointer; +} + +.a86-sb-check input { + accent-color: var(--w-change); +} + +.a86-sb-actions { + margin-top: 0.6rem; +} + +.a86-sb-status { + display: block; + font-size: calc(var(--w-fs) * 0.91); + color: var(--w-dim); + min-height: 1.1rem; + margin-top: 0.3rem; +} + +.a86-sb-status.is-error { + color: var(--w-miss); +} + +.a86-sb-help { + font-size: calc(var(--w-fs) * 0.88); + color: var(--w-dim); + margin: 0.6rem 0 0; +} + +.a86-sb-spec { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.89); + background: var(--w-surface-2); + border: 1px solid var(--w-rule); + border-radius: 4px; + padding: 0.5rem 0.6rem; + overflow-x: auto; + white-space: pre; + margin: 0 0 0.8rem; +} + +.a86-sb-out>.a86 { + margin-top: 0.4rem; +} + +/* ------------------------------------------------------- outside Quarto + A page that never declares a theme may still have an OS preference worth + honoring. Gated on both Quarto classes being absent, so it can never + contradict a page that has chosen. */ + +@media (prefers-color-scheme: dark) { + body:not(.quarto-light):not(.quarto-dark) .a86 { + --w-page: #1a1e23; + --w-ink: #e6e9ec; + --w-change: #e0a93a; + --w-read: #6fb4e3; + --w-write: #c0a0e0; + --w-match: #74c391; + --w-miss: #e08a80; + --a86-enc-prefix: #a9aeb5; + --a86-enc-rex: #e39acb; + --a86-enc-opcode: #e0a93a; + --a86-enc-modrm: #6fb4e3; + --a86-enc-sib: #74c391; + --a86-enc-disp: #c0a0e0; + --a86-enc-imm: #e08a80; + --w-rule: color-mix(in srgb, var(--w-ink) 28%, transparent); + --w-surface-2: color-mix(in srgb, var(--w-ink) 9%, var(--w-page)); + --w-change-bg: color-mix(in srgb, var(--w-change) 22%, var(--w-page)); + --w-read-bg: color-mix(in srgb, var(--w-read) 22%, var(--w-page)); + --w-write-bg: color-mix(in srgb, var(--w-write) 22%, var(--w-page)); + --w-match-bg: color-mix(in srgb, var(--w-match) 24%, var(--w-page)); + --w-miss-bg: color-mix(in srgb, var(--w-miss) 22%, var(--w-page)); + } +} + +/* Fullscreen pipeline: wider, taller cells, so the diagram uses the room. */ +.a86.is-fullscreen .a86-pipe-cell { + width: calc(var(--w-fs) * 2.5); + min-width: calc(var(--w-fs) * 2.5); + height: calc(var(--w-fs) * 1.6); +} + +.a86.is-fullscreen .a86 .a86-pipe-instr code, +.a86.is-fullscreen .a86-pipe-instr code { + max-width: calc(var(--w-fs) * 16); +} + +/* An instruction quoted inside a sentence keeps the listing's column + padding under Quarto's pre-wrap ("push rbp"); in prose one space + between the mnemonic and its operands reads better. */ +.a86 .a86-explain code { + white-space: nowrap; +} diff --git a/styles/course/bridge.css b/styles/course/bridge.css new file mode 100644 index 0000000..318d156 --- /dev/null +++ b/styles/course/bridge.css @@ -0,0 +1,142 @@ +/* ============================================================================ + styles/course/bridge.css -- the app's side of the course stylesheets. + + tokens.css, kit.css and asm86.css are the course site's own files, copied + unchanged (styles/course/README.md). They were written for Quarto pages and + read three things a Quarto page provides: + + --bs-body-bg, --bs-body-color the page colors every neutral is mixed from + --bs-font-monospace, --bs-font-sans-serif + body.quarto-light / body.quarto-dark which theme the page shows + + This file supplies the first two from the app's own tokens (styles.css), + which already swap with the theme, so nothing here needs a dark rule. + The body classes are set from script (src/ui/theme.ts), because the app's + theme can be "system" and a class cannot be chosen by CSS alone. + + Load order: styles.css, bridge.css, tokens.css, kit.css, asm86.css. + ==========================================================================*/ + +:root { + --bs-body-bg: var(--paper-2); + --bs-body-color: var(--ink); + --bs-font-monospace: var(--mono); + --bs-font-sans-serif: var(--sans); +} + +/* --------------------------------------------------------------------------- + The Hardware area's machine board (src/ui/hw/board.ts) puts the course's + views in the app's dock. Adjustments for that home, never in the course files. + ------------------------------------------------------------------------ */ + +/* A register card that also shows its narrower names needs room for the + name, sixteen hex digits, and the width on one line. */ +.board-a86 .a86-regs { + grid-template-columns: repeat(auto-fill, minmax(calc(var(--w-fs) * 17), 1fr)); +} + +.board-a86 .a86-width-row { + grid-template-columns: calc(var(--w-fs) * 2.83) minmax(0, 1fr) auto; +} +.board-a86 .a86-regs { align-items: start; } + +/* The "was ..." line under a register's value is empty until the register + changes. asm86.css gives it a min-height (0.8rem) shorter than its own line + box, so a card grew a few pixels the step it changed and shrank on the next, + moving every card below it. Reserve the whole line, filled or not. */ +.board-a86 .a86-reg-prev { + line-height: 1.35; + min-height: 1.35em; +} + +.board-a86.a86 { + margin: 0; +} + +/* The board's own "Cache lines" view (src/ui/hw/lines.ts): a line as a row of + byte cells, in the course's load, store and match colors. */ +.hw-line + .hw-line { + margin-top: 0.6rem; + padding-top: 0.6rem; + border-top: 1px dashed var(--w-rule); +} + +.hw-line-head, +.hw-line-use { + margin: 0.2rem 0; +} + +.hw-line-cells { + display: grid; + grid-template-columns: repeat(var(--hw-line, 16), minmax(0, 1fr)); + gap: 2px; + max-width: calc(var(--hw-line, 16) * 1.9rem); +} + +.hw-line-cell { + display: block; + min-height: 1.6rem; + border: 1px solid var(--w-rule); + border-radius: 2px; + background: var(--w-surface); + color: var(--w-dim); + font-family: var(--w-mono); + font-size: 0.7rem; + line-height: 1.6rem; + text-align: center; + overflow: hidden; +} + +.hw-line-cell.is-read { background: var(--w-read-bg); border-color: var(--w-read); color: var(--w-read); } +.hw-line-cell.is-write { background: var(--w-write-bg); border-color: var(--w-write); color: var(--w-write); } +.hw-line-cell.is-used { background: var(--w-match-bg); } +.hw-line-cell.is-later { background: var(--w-surface-2); border-style: dashed; } + +.hw-swatch { + display: inline-block; + width: 1rem; + min-height: 0.9rem; + height: 0.9rem; + vertical-align: middle; + margin-right: 0.3rem; +} + +.hw-hit { color: var(--w-match); font-weight: 600; } +.hw-miss { color: var(--w-miss); font-weight: 600; } + +/* The whole core (machineView in hwviews.js): a lit edge's arrowhead takes the + edge's color, so the head shows which way that instruction's data moved. */ +.a86-chip-svg marker.is-active path { fill: var(--w-change); } +.a86-chip-svg marker.is-load path { fill: var(--w-read); } +.a86-chip-svg marker.is-store path { fill: var(--w-write); } +.a86-chip-edge.is-active { stroke-width: 2.2; } + +/* The sentence under the core is one line for some instructions and two for + others; hold two, so the legend under it stays put while stepping. */ +.board-a86 .a86-chip-caption { + line-height: 1.45; + min-height: 4.35em; +} + +/* A port's box is 29 units wide; at 9px "alu mul" fits only in a narrow face, + and spills into the next port in the wider fallback fonts. */ +.a86-chip-node.is-port .a86-chip-sub { font-size: 7px; } + +/* Address arithmetic is one line ("named no memory address") on most steps and + a two-row sum with a note on the others. Hold the taller shape, so the card + and everything below it keep their place. */ +.board-a86 .a86-addr { min-height: calc(var(--w-fs) * 14.5); } + +/* The cache-line view lists the lines the last access touched: none before the + first access, one or two after. Hold two, so the legend under it stays put. */ +.board-a86 .hw-lines { min-height: 78px; } + +/* A listing row's trailing comment takes what width is left. In a narrow card + that is nothing, and a wrapping comment then stood one character per line, + leaving tall blank rows. Cut it with an ellipsis instead (a comment on its + own line still wraps). */ +.board-a86 .a86-code-row:not(.is-note) > .a86-code-comment { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} diff --git a/styles/course/kit.css b/styles/course/kit.css new file mode 100644 index 0000000..f76ae6a --- /dev/null +++ b/styles/course/kit.css @@ -0,0 +1,302 @@ +/* ============================================================================ + widgets/kit.css -- what the two teaching-widget families have in common. + + Two families of interactive widgets are built by static/js: + .a86 the x86-64 assembly widgets (js/asm86, css/widgets/asm86.css) + .pl the pseudocode lab (js/pseudo, css/widgets/pseudo-lab.css) + They were written as twins and shared a design system by copy and paste. + This file holds the shared half, written once, so a change to a color + role or a button reaches both. The two family stylesheets keep only what + is specific to them and must be loaded AFTER this one. + + Color roles carry meaning, so they are worth learning once: + amber the step about to run, and anything the last step changed + blue a value that was read + purple a value that was written + green a match, a pass, a proof + red a mismatch, an error, a claim a run broke + The roles are stated once per theme below. Everything neutral is mixed + from the page colors (--bs-body-bg / --bs-body-color), so a widget sits + on whatever background the page gives it. + + Dark mode keys off `body.quarto-dark`, which is what Quarto actually sets. + `[data-bs-theme="dark"]` is grouped in only as a fallback. Reading the OS + preference (prefers-color-scheme) on a Quarto page is the bug that once + made a light page render a dark widget, so nothing here does. + + Tokens (--w-*) + --w-page --w-ink --w-dim --w-rule --w-surface --w-surface-2 + --w-change --w-read --w-write --w-match --w-miss and their -bg washes + --w-mono --w-sans --w-fs + --w-fs is the one size that drives every piece of text in a widget. Each + rule states its size as a multiple of it, so fullscreen raises them all at + once. At 0.95rem a widget reads a step below the page's body text. + ==========================================================================*/ + + +/* ------------------------------------------------------------------ tokens */ + +:is(.a86, .pl) { + --w-page: var(--bs-body-bg, #ffffff); + --w-ink: var(--bs-body-color, #1b1f24); + + /* 70%, matching the muted gray in base/site.css and bio.css: at 60% the + result fails WCAG AA for normal-size text on a white background. */ + --w-dim: color-mix(in srgb, var(--w-ink) 70%, transparent); + --w-rule: color-mix(in srgb, var(--w-ink) 20%, transparent); + --w-surface: var(--w-page); + --w-surface-2: color-mix(in srgb, var(--w-ink) 6%, var(--w-page)); + + --w-change: #8a5c05; + --w-read: #17618f; + --w-write: #6a4299; + --w-match: #266a41; + --w-miss: #93291f; + + --w-change-bg: color-mix(in srgb, var(--w-change) 13%, var(--w-page)); + --w-read-bg: color-mix(in srgb, var(--w-read) 13%, var(--w-page)); + --w-write-bg: color-mix(in srgb, var(--w-write) 13%, var(--w-page)); + --w-match-bg: color-mix(in srgb, var(--w-match) 15%, var(--w-page)); + --w-miss-bg: color-mix(in srgb, var(--w-miss) 13%, var(--w-page)); + + --w-mono: var(--bs-font-monospace, ui-monospace, "SF Mono", Menlo, Consolas, monospace); + --w-sans: var(--bs-font-sans-serif, system-ui, sans-serif); + --w-fs: 0.95rem; + + color: var(--w-ink); + font-size: var(--w-fs); + line-height: 1.45; + margin: 1.4rem 0; + outline: none; +} + +/* A tinted panel needs a stronger wash to read against a dark page, and the + accents have to lighten to stay legible on it. */ +body.quarto-dark :is(.a86, .pl), +[data-bs-theme="dark"] :is(.a86, .pl) { + --w-change: #e0a93a; + --w-read: #6fb4e3; + --w-write: #c0a0e0; + --w-match: #74c391; + --w-miss: #e08a80; + + --w-rule: color-mix(in srgb, var(--w-ink) 28%, transparent); + --w-surface-2: color-mix(in srgb, var(--w-ink) 9%, var(--w-page)); + + --w-change-bg: color-mix(in srgb, var(--w-change) 22%, var(--w-page)); + --w-read-bg: color-mix(in srgb, var(--w-read) 22%, var(--w-page)); + --w-write-bg: color-mix(in srgb, var(--w-write) 22%, var(--w-page)); + --w-match-bg: color-mix(in srgb, var(--w-match) 22%, var(--w-page)); + --w-miss-bg: color-mix(in srgb, var(--w-miss) 22%, var(--w-page)); +} + +/* Fallback for browsers without color-mix(). */ +@supports not (background: color-mix(in srgb, white 50%, black)) { + :is(.a86, .pl) { + --w-dim: #666f78; + --w-rule: #d5dae0; + --w-surface-2: #f4f6f8; + --w-change-bg: #fdf1d8; + --w-read-bg: #e1eef9; + --w-write-bg: #efe6f7; + --w-match-bg: #dcefe2; + --w-miss-bg: #f8e3e1; + } + + body.quarto-dark :is(.a86, .pl) { + --w-dim: #98a2ab; + --w-rule: #3a424b; + --w-surface-2: #21262c; + --w-change-bg: #453518; + --w-read-bg: #1b3348; + --w-write-bg: #33254a; + --w-match-bg: #1d3a28; + --w-miss-bg: #3f2320; + } +} + + +/* ------------------------------------------------------------- shared rules + Each rule below was identical in both stylesheets. Rules that differ + between the families (panels, code rows, cells, legends...) stay in the + family file that owns them. */ + +/* --- Widget shell ------------------------------------------------------ */ + +.a86:focus-visible, +.pl:focus-visible { + box-shadow: 0 0 0 3px var(--w-change-bg); + border-radius: 4px; +} + +.a86 code, +.a86 code:not(.sourceCode), +.pl code, +.pl code:not(.sourceCode) { + background: none; + border: 0; + padding: 0; + border-radius: 0; + font-size: inherit; + color: inherit; + font-family: var(--w-mono); +} + +/* --- Text -------------------------------------------------------------- */ + +.a86-title, +.pl-title { + font-size: calc(var(--w-fs) * 1.13); + margin: 0 0 0.2rem; +} + +.a86-blurb, +.pl-blurb { + color: var(--w-dim); + margin: 0 0 0.7rem; + max-width: 62ch; +} + +.a86-muted, +.pl-muted { + color: var(--w-dim); +} + +.a86-error, +.pl-error { + color: var(--w-miss); + background: var(--w-miss-bg); + border-left: 3px solid var(--w-miss); + padding: 0.4rem 0.6rem; + margin: 0.5rem 0; +} + +/* --- Controls ---------------------------------------------------------- */ + +.a86-controls, +.pl-controls { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.35rem; + padding: 0.4rem 0.5rem; + margin-bottom: 0.7rem; + background: var(--w-surface-2); + border: 1px solid var(--w-rule); + border-radius: 4px; +} + +.a86-btn, +.pl-btn { + font: inherit; + font-size: calc(var(--w-fs) * 0.96); + padding: 0.22rem 0.62rem; + color: var(--w-ink); + background: var(--w-surface-2); + border: 1px solid var(--w-rule); + border-radius: 3px; + cursor: pointer; +} + +.a86-btn:hover, +.pl-btn:hover { + border-color: var(--w-change); +} + +.a86-btn-primary, +.pl-btn-primary { + border-color: var(--w-change); + font-weight: 600; +} + +.a86-slider, +.pl-slider { + flex: 1 1 140px; + min-width: 110px; + accent-color: var(--w-change); +} + +.a86-readout, +.pl-readout { + font-family: var(--w-mono); + font-size: calc(var(--w-fs) * 0.93); + color: var(--w-dim); + white-space: nowrap; +} + +.a86-btn-full, +.pl-btn-full { + margin-left: auto; +} + +/* --- Layout ------------------------------------------------------------ */ + +.a86-grid, +.pl-grid { + display: grid; + gap: 0.7rem; + grid-template-columns: 1fr; +} + +.a86-panel-title, +.pl-panel-title { + font-family: var(--w-sans); + font-size: calc(var(--w-fs) * 0.89); + font-weight: 600; + letter-spacing: 0.02em; + color: var(--w-dim); + margin: 0 0 0.45rem; +} + +/* --- Fullscreen -------------------------------------------------------- */ + +.a86.is-fullscreen, +.pl.is-fullscreen { + --w-fs: clamp(1rem, 0.35rem + 0.62vw, 1.3rem); + position: fixed; + inset: 0; + z-index: 1090; + margin: 0; + padding: 0.9rem 1.1rem 2rem; + background: var(--w-page); + overflow: auto; + overscroll-behavior: contain; +} + +.a86.is-fullscreen .a86-controls, +.pl.is-fullscreen .pl-controls { + position: sticky; + top: 0; + z-index: 2; +} + +.a86.is-fullscreen .a86-grid, +.pl.is-fullscreen .pl-grid { + display: flex; + flex-wrap: wrap; + align-items: stretch; +} + +.a86.is-fullscreen .a86-trace-wrap, +.pl.is-fullscreen .pl-trace-wrap { + max-height: 28rem; +} + +/* --- Code listing ------------------------------------------------------ */ + +.a86-code-marker, +.pl-code-marker { + color: var(--w-change); + font-weight: 700; +} + +.a86-code-row.is-last, +.pl-code-row.is-last { + background: var(--w-surface-2); +} + +.a86-code-row.is-error, +.pl-code-row.is-error { + background: var(--w-miss-bg); + border-left-color: var(--w-miss); +} diff --git a/styles/course/tokens.css b/styles/course/tokens.css new file mode 100644 index 0000000..535f83e --- /dev/null +++ b/styles/course/tokens.css @@ -0,0 +1,99 @@ +/* ============================================================================ + base/tokens.css -- design tokens shared by the course kit + (blocks, algorithms, worked examples, page furniture, figures and the + viz.js chart helpers). Custom properties only: loading this file changes + nothing on a page that does not use them. + + Everything is derived from --bs-body-color / --bs-body-bg, which Quarto + sets for each theme and swaps on the light/dark toggle, so a token that + mixes them needs no dark-mode rule of its own. Hue tokens (role colors, + the categorical palette) do have a dark value, set on body.quarto-dark. + ==========================================================================*/ + +:root { + /* ---- surfaces and text ---- */ + --course-ink: var(--bs-body-color, #212529); + --course-paper: var(--bs-body-bg, #fff); + --course-muted: color-mix(in srgb, var(--course-ink) 68%, transparent); + --course-rule: color-mix(in srgb, var(--course-ink) 18%, transparent); + --course-wash: color-mix(in srgb, var(--course-ink) 4%, var(--course-paper)); + --course-radius: 6px; + + /* ---- role colors: which kind of block a reader is looking at ---- */ + --course-key: #2563eb; + /* key idea, definition, theorem */ + --course-intuition: #7c3aed; + /* intuition, why it matters */ + --course-caution: #b45309; + /* pitfall, misconception */ + --course-practice: #047857; + /* in practice, worked example, checkpoint */ + --course-algorithm: #0f766e; + /* algorithm cards */ + --course-history: #78716c; + /* history, going deeper */ + --course-draft: #c026d3; + /* author notes, never shown to students */ + + /* ---- categorical palette (Okabe & Ito), safe for color-vision deficiency. + viz.js and any hand-written figure take colors from here, in order. ---- */ + --viz-1: #0072b2; + /* blue */ + --viz-2: #d55e00; + /* vermillion */ + --viz-3: #009e73; + /* bluish green */ + --viz-4: #cc79a7; + /* reddish purple */ + --viz-5: #e69f00; + /* orange */ + --viz-6: #56b4e9; + /* sky blue */ + --viz-7: #f0e442; + /* yellow */ + --viz-8: #000000; + /* black */ + + /* diverging (negative .. positive) and the single-hue ramp for magnitudes */ + --viz-neg: #0072b2; + --viz-pos: #d55e00; + --viz-ramp: #0072b2; + + /* axes, gridlines, labels inside a chart */ + --viz-ink: var(--course-ink); + --viz-muted: var(--course-muted); + --viz-grid: color-mix(in srgb, var(--course-ink) 12%, transparent); + --viz-bg: var(--course-paper); +} + +body.quarto-dark { + --course-key: #7aa2ff; + --course-intuition: #b79cff; + --course-caution: #f0a04b; + --course-practice: #4cc9a0; + --course-algorithm: #4fd1c5; + --course-history: #b4aca5; + --course-draft: #e879f9; + + --viz-1: #56b4e9; + --viz-2: #f28e4b; + --viz-3: #2fc99a; + --viz-4: #e9a3c8; + --viz-5: #f5b942; + --viz-6: #8fd0f5; + --viz-7: #f5ec6a; + --viz-8: #e5e5e5; + --viz-neg: #56b4e9; + --viz-pos: #f28e4b; + --viz-ramp: #56b4e9; +} + +/* Fallback for browsers without color-mix(). */ +@supports not (background: color-mix(in srgb, white 50%, black)) { + :root { + --course-muted: rgba(33, 37, 41, 0.68); + --course-rule: rgba(128, 128, 128, 0.3); + --course-wash: rgba(128, 128, 128, 0.06); + --viz-grid: rgba(128, 128, 128, 0.25); + } +} diff --git a/tests/a11y.test.mjs b/tests/a11y.test.mjs new file mode 100644 index 0000000..b2bfafb --- /dev/null +++ b/tests/a11y.test.mjs @@ -0,0 +1,58 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// The structure a screen reader navigates by, on the pages that render outside a browser: one main landmark, a +// labeled navigation, a footer, one h1, and headings that do not skip a level. (The workspaces are checked by axe in +// a browser: their main, header and h1 come from src/ui/shell.ts.) +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { installDocument } from '../dist/quarto/dom.js'; + +installDocument(); +const store = new Map(); +globalThis.localStorage = { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, String(v)), removeItem: (k) => store.delete(k), key: () => null, get length() { return store.size; } }; +const { homeView } = await import('../dist/ui/home.js'); +const { libraryView } = await import('../dist/ui/library.js'); +const { messagePage } = await import('../dist/ui/notice.js'); +const { highlighted } = await import('../dist/quarto/render.js'); + +function outline(root) { + // every heading in document order (the small document's querySelectorAll returns one list per selector) + const out = []; + const walk = (n) => { for (const c of n.children ?? []) { if (/^h[1-6]$/.test(c.localName)) out.push(Number(c.localName[1])); walk(c); } }; + walk(root); + return out; +} + +for (const [name, view] of [['home', () => homeView()], ['library', () => libraryView()], ['a library routine', () => libraryView('md.LennardJones')]]) { + test(`${name}: one main, a labeled nav, a footer, one h1, and no heading skips a level`, () => { + const root = view(); + assert.equal(root.querySelectorAll('main').length, 1); + const nav = root.querySelectorAll('nav').filter((n) => n.getAttribute('class')?.includes('home-nav')); + assert.equal(nav.length, 1); + assert.equal(nav[0].getAttribute('aria-label'), 'Site'); + assert.equal(root.querySelectorAll('footer').length, 1); + const levels = outline(root); + assert.equal(levels.filter((l) => l === 1).length, 1, `one h1 in ${levels.join(' ')}`); + assert.equal(levels[0], 1); + for (let i = 1; i < levels.length; i++) assert.ok(levels[i] <= levels[i - 1] + 1, `h${levels[i - 1]} then h${levels[i]} at heading ${i}`); + }); +} + +test('a message page is a main landmark with its h1', () => { + const page = messagePage('No such problem', 'text'); + assert.equal(page.querySelectorAll('main').length, 1); + assert.equal(page.querySelector('h1').textContent, 'No such problem'); +}); + +test('a listing that scrolls can be reached from the keyboard; so can an editor that is read-only', () => { + assert.equal(highlighted('OUTPUT 1', 'pseudo').getAttribute('tabindex'), '0'); + assert.match(readFileSync(new URL('../src/ui/editor.ts', import.meta.url), 'utf8'), /contentAttributes\.of\(\{.*tabindex: '0' \}\)/); + const shell = readFileSync(new URL('../src/ui/shell.ts', import.meta.url), 'utf8'); + assert.match(shell, /el\('header', \{ class: 'toolbar' \}\)/, 'the toolbar is the workspace\'s banner'); + assert.match(shell, /el\('main', \{ class: 'workspace'/, 'the workspace is its main landmark'); + assert.match(shell, /el\('h1', \{ class: 'sr-only' \}/, 'and it has an h1'); + const embed = readFileSync(new URL('../src/ui/embed.ts', import.meta.url), 'utf8'); + assert.match(embed, /const root = el\('main', \{ class: 'embed' \}\)/, 'an embedded view is a main landmark'); + assert.match(embed, /el\('h1', \{ class: 'sr-only' \}/, 'with an h1'); +}); diff --git a/tests/areas.test.mjs b/tests/areas.test.mjs new file mode 100644 index 0000000..5f18996 --- /dev/null +++ b/tests/areas.test.mjs @@ -0,0 +1,153 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// Stage 9: three areas, each with its own route, panes, views and layout. A problem is one state shared by all +// three; the area comes from the route. Anything that is not a route in the plan is home. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { areasFor, AREAS, AREA_ORDER, defaultAreaFor, paneForArea, isAreaId, areaHasPane } from '../dist/core/areas.js'; +import { parseRoute, routeFor, normalize, emptyState, applyEmbedParams } from '../dist/core/state.js'; +import { PROBLEMS, stateForProblem } from '../dist/core/catalog.js'; +import { Session } from '../dist/core/session.js'; +import { EXERCISES } from '../core/dist/exercises/index.js'; + +globalThis.localStorage = { getItem() { return null; }, setItem() { }, removeItem() { } }; + +test('every route shape parses and prints back', () => { + for (const area of AREA_ORDER) { + assert.deepEqual(parseRoute(`#/${area}/p/count-base`), { kind: 'problem', area, id: 'count-base' }); + assert.equal(routeFor({ kind: 'problem', area, id: 'count-base' }), `#/${area}/p/count-base`); + assert.deepEqual(parseRoute(`#/${area}/s/~abc`), { kind: 'shared', area, blob: '~abc' }); + assert.equal(routeFor({ kind: 'shared', area, blob: '~abc' }), `#/${area}/s/~abc`); + } + assert.deepEqual(parseRoute(''), { kind: 'home' }); + assert.deepEqual(parseRoute('#/'), { kind: 'home' }); + const e = parseRoute('#/embed/trace/p/match?t=12'); + assert.equal(e.kind, 'embed'); assert.equal(e.view, 'trace'); assert.equal(e.problem, 'match'); assert.equal(e.params.get('t'), '12'); + const b = parseRoute('#/embed/life/~blob?area=dev'); + assert.equal(b.kind, 'embed'); assert.equal(b.blob, '~blob'); assert.equal(b.params.get('area'), 'dev'); + assert.equal(routeFor(b), '#/embed/life/~blob?area=dev'); + assert.equal(routeFor(parseRoute('#/embed/playground/p/demo?panel=life')), '#/embed/playground/p/demo?panel=life'); + assert.deepEqual(parseRoute('#/bridge/p/a%20b'), { kind: 'problem', area: 'bridge', id: 'a b' }); +}); + +test('an unknown route is home: the old links and the retired names do not work', () => { + for (const h of ['#/p/count-base', '#/s/~abc', '#/learn', '#/learn/loops', '#/playground/p/demo', '#/bridge', '#/bridge/p', '#/bridge/x/y', '#/dev/s', '#/nowhere', '#/#problems', '#/#reference']) + assert.deepEqual(parseRoute(h), { kind: 'home' }, h); +}); + +test('the area table: three areas with the panes, views and docks of the plan', () => { + assert.deepEqual(AREA_ORDER, ['bridge', 'dev', 'hw']); + assert.ok(AREA_ORDER.every(isAreaId) && !isAreaId('learn') && !isAreaId('playground')); + for (const id of AREA_ORDER) { assert.equal(AREAS[id].id, id); assert.equal(AREAS[id].route, id); assert.ok(AREAS[id].name && AREAS[id].tagline); } + assert.deepEqual(AREAS.bridge.panes, ['lingo', 'matho', 'pseudo', 'speco', 'mojo']); + assert.deepEqual(AREAS.dev.panes, ['mojo']); + assert.deepEqual(AREAS.hw.panes, ['mojo', 'asm']); + assert.ok(AREAS.dev.inspect.includes('trace') && AREAS.bridge.inspect.includes('trace'), 'both have the Run view, which shows the variables and their lifetimes'); + assert.ok(!AREAS.dev.inspect.includes('table') && !AREAS.dev.inspect.includes('life') && !AREAS.bridge.inspect.includes('table'), 'the Run view replaces the table of values and the lifetimes'); + assert.ok(AREAS.bridge.inspect.includes('proof') && !AREAS.dev.inspect.includes('proof')); + assert.equal(AREAS.hw.workspace, 'board', 'Hardware is two panes: the code, and the board'); + assert.ok(AREAS.bridge.workspace === 'ide' && AREAS.dev.workspace === 'ide'); + assert.deepEqual([AREAS.hw.inspect, AREAS.hw.dock], [[], []], 'its views are cards on the board, not tabs'); + assert.ok(!AREAS.bridge.dock.includes('asm') && !AREAS.dev.dock.includes('asm')); + assert.ok(areaHasPane(AREAS.hw, 'asm') && !areaHasPane(AREAS.dev, 'pseudo')); +}); + +test('each problem names its area: Hardware for asm-*, Developer for Mojo-only, Bridge otherwise', () => { + for (const e of EXERCISES) { + const p = PROBLEMS.find((x) => x.id === e.id); + assert.ok(isAreaId(p.area), e.id); + const raw = (l) => !!(e.sources[l] ?? '').trim(); + if (e.area) assert.equal(p.area, e.area, e.id); + else if (e.id.startsWith('asm-')) assert.equal(p.area, 'hw', e.id); + else if ((raw('mojo') || e.mojoProgram) && !raw('pseudo') && !raw('lingo') && !raw('matho')) assert.equal(p.area, 'dev', e.id); + else assert.equal(p.area, 'bridge', e.id); + } + assert.ok(PROBLEMS.some((p) => p.area === 'bridge') && PROBLEMS.some((p) => p.area === 'hw')); + assert.equal(defaultAreaFor({ id: 'x', sources: { pseudo: 'OUTPUT 1' }, area: 'hw' }), 'hw', 'an exercise that says so wins'); +}); + +test('the pane a state opens on follows the area', () => { + const count = stateForProblem(PROBLEMS.find((p) => p.id === 'count-base')); + assert.equal(count.lang, 'mojo', 'the exercise\'s own default is its Mojo'); + assert.equal(paneForArea(AREAS.bridge, count, true), 'pseudo', 'a problem opening in the Bridge begins with the idea'); + assert.equal(paneForArea(AREAS.bridge, { ...count, lang: 'speco' }, true), 'speco', 'a linked pane the student left open is kept'); + assert.equal(paneForArea(AREAS.bridge, { ...count, lang: 'mojo' }), 'mojo', 'a shared link at the Mojo tab keeps it'); + assert.equal(paneForArea(AREAS.dev, { ...count, lang: 'pseudo' }), 'mojo'); + const asm = stateForProblem(PROBLEMS.find((p) => p.id.startsWith('asm-'))); + assert.equal(paneForArea(AREAS.hw, { ...asm, lang: 'pseudo' }), 'asm'); + assert.equal(paneForArea(AREAS.hw, { ...count, lang: 'pseudo', sources: { ...count.sources, asm: '' } }), 'mojo', 'no assembly: Mojo'); + assert.equal(paneForArea(AREAS.hw, { ...asm, lang: 'mojo' }), 'mojo', 'a pane of the area is kept'); +}); + +test('layout is kept per area, and a state normalizes it that way', () => { + const s = normalize({ v: 3, layout: { bridge: { split: 0.4, dockTab: 'problems' }, dev: { split: 0.7, dockCollapsed: true }, hw: { dock: 0.5, right: 7 }, nowhere: { split: 0.1 }, split: 0.9 } }); + assert.deepEqual(Object.keys(s.layout).sort(), ['bridge', 'dev', 'hw']); + assert.equal(s.layout.bridge.split, 0.4); assert.equal(s.layout.bridge.dockTab, 'problems'); + assert.equal(s.layout.dev.split, 0.7); assert.equal(s.layout.dev.dockCollapsed, true); + assert.equal(s.layout.hw.dock, 0.5); assert.equal(s.layout.hw.right, undefined, 'a fraction outside 0..1 is dropped'); + assert.equal(normalize({ v: 3, layout: { split: 0.5, dockTab: 'output' } }).layout, undefined, 'a layout that is not per area is not read'); + assert.equal(emptyState().layout, undefined); +}); + +test('a session lays out the area it is open in, and the other areas keep their own', () => { + const st = stateForProblem(PROBLEMS.find((p) => p.id === 'count-base')); + const bridge = new Session(st, { area: 'bridge', storageId: null }); + bridge.setLayout({ split: 0.3 }); + assert.equal(bridge.layout().split, 0.3); + const dev = new Session(st, { area: 'dev', storageId: null }); + assert.equal(dev.layout().split, undefined, 'the Developer area has not been arranged yet'); + dev.setLayout({ split: 0.7, dockTab: 'compiler' }); + assert.equal(bridge.layout().split, 0.3, 'the same state: the Bridge arrangement is still there'); + assert.equal(st.layout.dev.dockTab, 'compiler'); + assert.equal(new Session(st, { storageId: null }).area, null, 'a session with no area is not a workspace: every pane counts'); +}); + +test('an embed query arranges one area, chosen with area=', () => { + const s = applyEmbedParams(emptyState(), new URLSearchParams('editor=0.6&dock=closed'), 'dev'); + assert.deepEqual(s.layout, { dev: { split: 0.6, dockCollapsed: true } }); +}); + +test('allDiagnostics reports only the panes of the area', () => { + const st = stateForProblem(PROBLEMS.find((p) => p.id === 'count-base')); + st.sources.mojo = 'def main(:\n'; + st.sources.pseudo = 'FUNCTION BROKEN(\n'; + const dev = new Session(structuredClone(st), { area: 'dev', storageId: null }); + assert.ok(dev.allDiagnostics().every((d) => d.lang === 'mojo'), 'Developer: Mojo only'); + assert.ok(dev.allDiagnostics().length); + const bridge = new Session(structuredClone(st), { area: 'bridge', storageId: null }); + assert.ok(bridge.allDiagnostics().some((d) => d.lang === 'pseudo')); + const hw = new Session(structuredClone(st), { area: 'hw', storageId: null }); + assert.ok(hw.allDiagnostics().every((d) => d.lang === 'mojo' || d.lang === 'asm')); +}); + +test('the toolbar offers only the areas that would show the open pane exactly as it is', async () => { + const { safeSwitches } = await import('../dist/core/areas.js'); + const open = (id, area) => { const st = stateForProblem(PROBLEMS.find((p) => p.id === id)); return new Session(st, { area, storageId: null }); }; + const s = open('count-base', 'dev'); + const shown = (a, l) => s.shownIn(a, l); + assert.deepEqual(safeSwitches('dev', 'mojo', shown), ['hw'], 'Developer and Hardware share the Mojo'); + assert.deepEqual(safeSwitches('hw', 'mojo', shown), ['dev']); + assert.deepEqual(safeSwitches('hw', 'asm', shown), [], 'only Hardware has x86-64'); + assert.deepEqual(safeSwitches('hw', 'mojo', () => ''), [], 'an empty pane offers no switch: the move would show other work'); + for (const l of ['lingo', 'matho', 'pseudo', 'speco']) assert.deepEqual(safeSwitches('bridge', l, shown), [], `only the Bridge has ${l}`); + assert.notEqual(s.shownIn('bridge', 'mojo'), s.shownIn('dev', 'mojo'), 'the exercise\'s own Mojo is not the translation of its pseudo'); + assert.deepEqual(safeSwitches('bridge', 'mojo', shown), [], 'so the Bridge\'s Mojo tab does not offer Developer'); + // once the generated Mojo is copied into the Developer area, the Bridge and the others show the same text + const b = open('count-base', 'bridge'); + assert.ok(b.adoptGeneratedMojo()); + assert.deepEqual(safeSwitches('bridge', 'mojo', (a, l) => b.shownIn(a, l)), ['dev', 'hw']); + assert.deepEqual(safeSwitches('dev', 'lingo', shown), [], 'a pane the area does not have offers nothing'); +}); + +test('each problem opens in its own area first, then every other area it has something to show in', () => { + for (const p of PROBLEMS) { + const a = areasFor(p); + assert.equal(a[0], p.area, p.id); + assert.equal(new Set(a).size, a.length, `${p.id}: each area once`); + assert.equal(a.includes('hw'), p.area === 'hw' || !!(p.sources.asm ?? '').trim(), `${p.id}: Hardware when it has x86-64`); + assert.equal(a.includes('bridge'), p.area === 'bridge' || ['pseudo', 'lingo', 'matho', 'speco'].some((l) => (p.sources[l] ?? '').trim()), `${p.id}: the Bridge when it has an idea to translate`); + } + assert.deepEqual(areasFor({ area: 'bridge', sources: { pseudo: 'OUTPUT 1', mojo: 'def main(): pass', asm: 'ret' } }), ['bridge', 'dev', 'hw']); + assert.deepEqual(areasFor({ area: 'hw', sources: { asm: 'ret' } }), ['hw']); + assert.deepEqual(areasFor({ area: 'dev', sources: {}, mojo: { source: 'def main(): pass' } }), ['dev']); +}); diff --git a/tests/badges.test.mjs b/tests/badges.test.mjs new file mode 100644 index 0000000..86193a8 --- /dev/null +++ b/tests/badges.test.mjs @@ -0,0 +1,167 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// Stage 12: the Mojo badges. The generated label (where the Mojo came from) and the godbolt badge (whether the real +// compiler was asked about exactly this source) are independent, both are data a view reads from the session, and +// neither can come from a link or a file. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { Session } from '../dist/core/session.js'; +import { stateForProblem, problemById, PROBLEMS } from '../dist/core/catalog.js'; +import { mojoProvenance } from '../dist/core/provenance.js'; +import { compiledStatus, compileHash, forgetCompiles } from '../dist/core/compiles.js'; +import { normalize } from '../dist/core/state.js'; +import { GENERATED_HEADER } from '../core/dist/sync/header.js'; +import { mojoFromPseudo } from '../core/dist/sync/hub.js'; + +const store = new Map(); +globalThis.localStorage = { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, String(v)), removeItem: (k) => store.delete(k) }; +const open = (id, area = 'bridge') => new Session(stateForProblem(problemById(id)), { area, storageId: null }); +const answer = (over = {}) => async () => ({ error: null, seconds: 1, answer: { compiled: true, buildStderr: '', executed: true, exitCode: 0, stdout: '1\n', stderr: '', timedOut: false, asm: [], ...over } }); + +test('the Bridge\'s Mojo is always generated; elsewhere the state says', () => { + const b = open('count-base', 'bridge'); + assert.equal(b.provenance(), 'generated'); + assert.equal(mojoProvenance(b, 'bridge'), 'generated'); + assert.equal(open('count-base', 'dev').provenance(), null, 'an exercise\'s own Mojo is nobody\'s translation'); + assert.equal(open('count-base', 'hw').provenance(), null); + assert.equal(mojoProvenance({ area: 'dev', state: { mojoOrigin: 'generated-edited' } }), 'generated-edited'); +}); + +test('copying sets generated, editing sets generated-edited, and only the button clears it', async () => { + const s = open('count-base'); + assert.ok(s.adoptGeneratedMojo()); + assert.equal(s.state.mojoOrigin, 'generated'); + const dev = new Session(s.state, { area: 'dev', storageId: null }); + assert.equal(dev.provenance(), 'generated'); + dev.setSource('mojo', dev.source('mojo') + '\n# my note'); + assert.equal(dev.provenance(), 'generated-edited'); + forgetCompiles(); + await dev.compile(answer()); + assert.equal(dev.provenance(), 'generated-edited', 'a successful compile does not clear it'); + assert.ok(dev.clearMojoOrigin()); + assert.equal(dev.provenance(), null); + assert.equal(dev.state.mojoOrigin, undefined); + assert.ok(!dev.source('mojo').includes(GENERATED_HEADER), 'the header comment goes with it'); + assert.ok(dev.source('mojo').includes('# my note'), 'the student\'s own lines stay'); + assert.equal(dev.clearMojoOrigin(), false, 'nothing left to clear'); +}); + +test('the Bridge cannot clear provenance, and a translation always starts with the header', () => { + const s = open('count-base'); + assert.equal(s.clearMojoOrigin(), false); + let n = 0; + for (const p of PROBLEMS) { + const pseudo = stateForProblem(p).sources.pseudo; + if (!pseudo) continue; + const m = mojoFromPseudo(pseudo, null).source; + if (m) { n++; assert.ok(m.startsWith(GENERATED_HEADER), p.id); } + } + assert.ok(n > 5); +}); + +test('the godbolt badge: shown for the compiled source, not for one more character, level or input', async () => { + forgetCompiles(); + const s = open('count-base', 'dev'); + assert.equal(s.compileBadge(), null, 'never compiled: no badge'); + await s.compile(answer()); + const b = s.compileBadge(); + assert.equal(b.kind, 'compiled'); + assert.equal(b.status.outcome, 'ran'); + assert.equal(b.status.exit, 0); + const original = s.source('mojo'); + s.setSource('mojo', original + ' '); + assert.equal(s.compileBadge().kind, 'edited', 'a one-character edit removes the badge'); + s.setSource('mojo', original); + assert.equal(s.compileBadge().kind, 'compiled', 'the same text again is the same compile'); + const back = open('count-base', 'dev'); + assert.equal(back.compileBadge().kind, 'compiled', 'the same text again is the same compile'); + back.setBuildLevel('default'); + assert.equal(back.compileBadge(), null, 'another build level was never asked'); + back.setBuildLevel('O0'); + back.setInput('3\n'); + assert.equal(back.compileBadge(), null, 'another input was never asked'); +}); + +test('outcomes: did not compile, exit N, timed out', async () => { + forgetCompiles(); + const s = open('count-base', 'dev'); + await s.compile(answer({ compiled: false, executed: false, exitCode: null })); + assert.equal(s.compileBadge().status.outcome, 'did-not-compile'); + forgetCompiles(); + await s.compile(answer({ exitCode: 3 })); + assert.deepEqual([s.compileBadge().status.outcome, s.compileBadge().status.exit], ['ran', 3]); + forgetCompiles(); + await s.compile(answer({ timedOut: true })); + assert.equal(s.compileBadge().status.outcome, 'timed-out'); +}); + +test('a failed request (no answer) leaves no badge', async () => { + forgetCompiles(); + const s = open('count-base', 'dev'); + await s.compile(async () => ({ answer: null, error: 'offline', seconds: 1 })); + assert.equal(s.compileBadge(), null); +}); + +test('the badge survives a new Session and the full answers being dropped, but is not in the state, a link or a file', async () => { + forgetCompiles(); + const s = open('count-base', 'dev'); + await s.compile(answer()); + const src = s.source('mojo'); + assert.equal(compiledStatus(src, '', 'O0').outcome, 'ran'); + assert.equal(compiledStatus(src, '', 'O0').level, 'O0'); + assert.ok(store.has('pplus.compiled')); + store.delete('pplus.compiles'); // the full answers are gone; the summary index stays + assert.equal(open('count-base', 'dev').compileBadge().kind, 'compiled'); + const text = JSON.stringify(s.state); + assert.ok(!/compiled|godbolt|pplus\./i.test(text.replace(/"compiler"/g, '')), 'nothing about a compile in the state'); + forgetCompiles(); // someone else's browser: the same link, no compile + const theirs = new Session(normalize(JSON.parse(text)), { area: 'dev', storageId: null }); + assert.equal(theirs.compileBadge(), null); +}); + +test('both badges can show together, and the hash covers source, input and level', async () => { + forgetCompiles(); + const s = open('count-base', 'bridge'); + await s.compile(answer()); + assert.equal(s.provenance(), 'generated'); + assert.equal(s.compileBadge().kind, 'compiled'); + assert.notEqual(compileHash('a', '', 'O0'), compileHash('a', '', 'default')); + assert.notEqual(compileHash('a', '', 'O0'), compileHash('a', 'x', 'O0')); + assert.notEqual(compileHash('a', '', 'O0'), compileHash('a ', '', 'O0')); +}); + +test('Compile & run on unchanged work shows the kept answer and sends nothing; asking again is a choice', async () => { + forgetCompiles(); + const s = open('count-base', 'dev'); + assert.equal(s.keptCompile(), null, 'nothing kept before the first answer'); + let sent = 0; + const fake = async () => { sent++; return { error: null, seconds: 1, answer: { compiled: true, buildStderr: '', executed: true, exitCode: 0, stdout: `${sent}\n`, stderr: '', timedOut: false, asm: [] } }; }; + const first = await s.compile(fake); + assert.equal(sent, 1); + assert.equal(s.keptCompile(), first, 'the same source, input and level: the kept answer'); + assert.equal(s.reusedCompile(), null); + s.reuseCompile(s.keptCompile()); + assert.equal(sent, 1, 'nothing sent'); + assert.equal(s.reusedCompile(), first, 'the view can say the answer was kept, not asked'); + assert.equal(s.lastCompile().record, first); + // another level, another input, one more character: nothing kept for them + assert.equal(s.keptCompile('default'), null); + s.setInput('7'); + assert.equal(s.keptCompile(), null); + s.setInput(''); + assert.equal(s.keptCompile(), first); + const src = s.source('mojo'); + s.setSource('mojo', src + ' '); + assert.equal(s.keptCompile(), null); + s.setSource('mojo', src); + // asking again, on purpose, sends and is no longer "kept" + const again = await s.compile(fake); + assert.equal(sent, 2); + assert.equal(s.reusedCompile(), null); + assert.equal(s.keptCompile(), again); + // a request that failed is not an answer to show again + forgetCompiles(); + const t = open('match', 'dev'); + await t.compile(async () => ({ answer: null, error: 'offline', seconds: 0 })); + assert.equal(t.keptCompile(), null); +}); diff --git a/tests/bridge.test.mjs b/tests/bridge.test.mjs new file mode 100644 index 0000000..04fda42 --- /dev/null +++ b/tests/bridge.test.mjs @@ -0,0 +1,134 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// Stage 10 (and the part of stage 11 it needs): the Bridge's session behavior, without a DOM. In the Bridge the +// Mojo pane is the literal translation of the pseudo, computed and never stored; the views that read a program +// (trace, checker, tests, proof) work on the hub's pseudo; a pane that is not in step is not stepped; "Edit in +// Developer" copies the generated Mojo out and records that it was generated. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { Session } from '../dist/core/session.js'; +import { PROBLEMS, stateForProblem, problemById } from '../dist/core/catalog.js'; +import { SyncHub } from '../core/dist/sync/hub.js'; +import { normalize } from '../dist/core/state.js'; +import { GENERATED_HEADER } from '../core/dist/sync/header.js'; + +globalThis.localStorage = { getItem() { return null; }, setItem() { }, removeItem() { } }; +const open = (id, area = 'bridge') => new Session(stateForProblem(problemById(id)), { area, storageId: null }); + +test('in the Bridge the Mojo pane is the generated Mojo, not the stored Mojo; elsewhere it is the state\'s own', () => { + const own = stateForProblem(problemById('count-base')).sources.mojo; + assert.ok(own && !own.startsWith('# Generated'), 'the exercise has its own Mojo'); + const bridge = open('count-base', 'bridge'); + assert.ok(bridge.source('mojo').startsWith(GENERATED_HEADER), 'the Bridge shows the literal translation, header first'); + assert.equal(bridge.source('mojo'), bridge.derivedMojo().source); + assert.equal(bridge.state.sources.mojo, own, 'the stored Mojo is untouched'); + assert.equal(open('count-base', 'dev').source('mojo'), own); + assert.equal(open('count-base', 'hw').source('mojo'), own); + assert.equal(new Session(stateForProblem(problemById('count-base')), { storageId: null }).source('mojo'), own, 'a session with no area (an embed of one pane) shows the state\'s own Mojo'); +}); + +test('the Bridge\'s Mojo follows an edit in any linked pane, and every view of it reads the generated source', () => { + const s = open('count-base'); + const before = s.source('mojo'); + s.setSource('pseudo', s.source('pseudo').replace('Total <- 0', 'Total <- 3')); + assert.notEqual(s.source('mojo'), before); + assert.match(s.source('mojo'), /total = 3/); + // the checker, the stepper and the tests read it + s.setLang('mojo'); + assert.equal(s.parsedMojo().program.source ?? s.source('mojo'), s.source('mojo')); + assert.deepEqual(s.parsedMojo().diagnostics.filter((d) => d.severity === 'error'), []); + const tr = s.trace(); + assert.ok(tr && !tr.error, 'the generated Mojo steps in the interpreter'); + assert.ok(tr.output.some((l) => /3|4|5|6|7|8|9/.test(l)), 'and prints a count that includes the changed start'); + assert.ok(s.tests().length >= 0); + // an edit in lingo reaches it too + const lingo = s.source('lingo'); + assert.match(lingo, /Start with Total at 3\./, 'the English was regenerated from the pseudo'); + s.setSource('lingo', lingo.replace('Start with Total at 3.', 'Start with Total at 10.')); + assert.match(s.source('mojo'), /total = 10/); +}); + +test('trace steps the pseudo, not a stale pane', () => { + const s = open('count-base'); + s.setLang('lingo'); + assert.equal(s.traceLang(), 'lingo', 'an in-step lingo pane is stepped as English'); + s.setSource('pseudo', 'FUNCTION BROKEN(\nRETURN'); // pseudo has errors: lingo is now stale + assert.equal(s.linkState('lingo').kind, 'stale'); + assert.equal(s.traceLang(), 'pseudo', 'lingo holds text the pseudo has moved on from'); +}); + +test('prove and tests work on the hub\'s pseudo, with the speco woven', () => { + const s = open('count-base-proved'); + s.setLang('lingo'); + s.setSource('lingo', s.source('lingo').replace('Add 1 to Total.', 'Add 1 to Total.')); // no change: nothing to do + const lingo = s.source('lingo'); + s.setSource('lingo', lingo + '\n'); // an edit in English + assert.equal(s.state.sync.authority, 'lingo'); + assert.match(s.source('pseudo'), /ENSURE/, 'the contracts are in the pseudo the English lowered to'); + const proof = s.proof(); + assert.ok(proof && proof.report.counts.total > 0, 'there is something to prove'); + assert.equal(proof.report.counts.broken, 0); + assert.ok(s.tests().length > 0, 'tests are generated from the pseudo'); +}); + +test('Edit in Developer copies the generated Mojo into the state and records that it was generated', () => { + const s = open('count-base'); + const generated = s.derivedMojo().source; + assert.ok(s.wouldReplaceMojo(), 'the exercise\'s own Mojo would be replaced: the shell asks first'); + assert.equal(s.state.mojoOrigin, undefined); + assert.ok(s.adoptGeneratedMojo()); + assert.equal(s.state.sources.mojo, generated); + assert.equal(s.state.mojoOrigin, 'generated'); + assert.equal(s.state.lang, 'mojo'); + assert.equal(s.wouldReplaceMojo(), false, 'it already holds this program'); + // the Developer area shows it, and the first edit makes it theirs + const dev = new Session(s.state, { area: 'dev', storageId: null }); + assert.equal(dev.source('mojo'), generated); + dev.setSource('mojo', generated + '\n# mine\n'); + assert.equal(dev.state.mojoOrigin, 'generated-edited'); + dev.setSource('mojo', generated + '\n# mine again\n'); + assert.equal(dev.state.mojoOrigin, 'generated-edited'); + // a state with no pseudo has nothing to adopt + const empty = new Session(normalize({ v: 3 }), { area: 'bridge', storageId: null }); + assert.equal(empty.adoptGeneratedMojo(), false); + assert.equal(empty.state.mojoOrigin, undefined); +}); + +test('mojoOrigin is validated, and is only ever set on Mojo the student did not write', () => { + assert.equal(normalize({ v: 3, mojoOrigin: 'generated' }).mojoOrigin, 'generated'); + assert.equal(normalize({ v: 3, mojoOrigin: 'generated-edited' }).mojoOrigin, 'generated-edited'); + assert.equal(normalize({ v: 3, mojoOrigin: 'hand-written' }).mojoOrigin, undefined); + const s = open('count-base', 'dev'); + s.setSource('mojo', s.source('mojo') + '\n# note\n'); + assert.equal(s.state.mojoOrigin, undefined, 'editing the exercise\'s own Mojo does not make it generated'); +}); + +test('line maps reach the Mojo: a pseudo line finds its Mojo lines and back', () => { + const s = open('count-base'); + const maps = s.lineMaps(); + const pseudo = s.source('pseudo').split('\n'); + const at = pseudo.findIndex((l) => /Total <- Total \+ 1/.test(l)) + 1; + const mojoLines = SyncHub.relate(maps, 'pseudo', at, 'mojo'); + assert.ok(mojoLines.length, 'the line has a Mojo line'); + assert.match(s.source('mojo').split('\n')[mojoLines[0] - 1], /total = total \+ 1/); + assert.ok(SyncHub.relate(maps, 'mojo', mojoLines[0], 'pseudo').includes(at)); + // lingo line -> pseudo line, for a problem whose lingo was authored + const lingo = s.source('lingo').split('\n'); + const l = lingo.findIndex((t) => /add 1 to Count/.test(t)) + 1; + const p = SyncHub.relate(maps, 'lingo', l, 'pseudo'); + assert.ok(Array.isArray(p)); +}); + +test('every Bridge problem opens with generated Mojo that names itself and checks clean', () => { + let n = 0; + for (const p of PROBLEMS) { + if (p.area !== 'bridge') continue; + const s = new Session(stateForProblem(p), { area: 'bridge', storageId: null }); + if (!s.source('pseudo').trim()) continue; + const m = s.source('mojo'); + if (!m) continue; // pseudo that does not read (five-bugs, by design) + assert.ok(m.startsWith(GENERATED_HEADER), p.id); + n++; + } + assert.ok(n >= 12, `${n} problems`); +}); diff --git a/tests/chain.test.mjs b/tests/chain.test.mjs new file mode 100644 index 0000000..59475b3 --- /dev/null +++ b/tests/chain.test.mjs @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// pplus-web pins pplus-core (core/) and core pins pplus-library (core/library/), each by commit. A pointer that names +// a commit the checkout does not have, or a checkout left behind its pointer, builds and tests the site from other +// sources than the commits say: the chain sat broken that way on main for five weeks once, and nothing said so +// (docs/deploy.md, "Moving the pointers"). These run the cheap half of `pixi run release-check` (scripts/release.mjs): +// no network, no build. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { quickCheck } from '../scripts/release.mjs'; + +test('every pointer names a commit its checkout has, and no checkout is behind its pointer', (t) => { + const found = quickCheck(); + for (const f of found.filter((x) => x.level === 'note')) t.diagnostic(f.text); + // under CI there is always a checkout to read: a pointer nobody could read is a gap, not a pass + if (process.env.CI) assert.ok(!found.some((x) => x.unread), found.map((x) => x.text).join('\n')); + assert.deepEqual(found.filter((x) => x.level === 'problem').map((x) => x.text), []); +}); + +const git = (dir, ...args) => { + const r = spawnSync('git', ['-c', 'user.name=test', '-c', 'user.email=test@example.invalid', '-c', 'commit.gpgsign=false', '-C', dir, ...args], { encoding: 'utf8' }); + assert.equal(r.status, 0, r.stderr); + return r.stdout.trim(); +}; + +/** A parent repository whose submodule `child` (a repository of two commits) is pinned at `pin` and checked out at `at`. */ +function fakeChain(pin, at) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'pplus-chain-')); + git(root, 'init', '-q'); + fs.writeFileSync(path.join(root, 'package.json'), '{"name":"parent"}\n'); + const child = path.join(root, 'child'); + fs.mkdirSync(child); + git(child, 'init', '-q'); + const commits = []; + for (const n of ['one', 'two']) { fs.writeFileSync(path.join(child, 'f'), n); git(child, 'add', 'f'); git(child, 'commit', '-q', '-m', n); commits.push(git(child, 'rev-parse', 'HEAD')); } + fs.writeFileSync(path.join(root, '.gitmodules'), '[submodule "child"]\n\tpath = child\n\turl = https://example.invalid/child.git\n\tbranch = main\n'); + const sha = pin === 'missing' ? 'f'.repeat(40) : commits[pin]; + git(root, 'update-index', '--add', '--cacheinfo', `160000,${sha},child`); + git(child, 'checkout', '-q', commits[at]); + return { root, commits }; +} + +test('a pointer to a commit the checkout lacks, or a checkout behind its pointer, is a problem that names the fix', () => { + if (spawnSync('git', ['--version']).status !== 0) assert.fail('git is not on the PATH'); + const cases = [ + { pin: 'missing', at: 1, want: /does not have that commit\. Fix: git submodule update --init --recursive/ }, + { pin: 1, at: 0, want: /behind the pinned .* Fix: git submodule update --recursive/ }, + ]; + for (const c of cases) { + const { root } = fakeChain(c.pin, c.at); + try { + const problems = quickCheck(root).filter((x) => x.level === 'problem'); + assert.equal(problems.length, 1, JSON.stringify(problems)); + assert.match(problems[0].text, c.want); + } finally { fs.rmSync(root, { recursive: true, force: true }); } + } + // at the pointer: nothing to say; ahead of it (work in progress, not yet pinned): a note, not a problem + for (const [pin, at, notes] of [[1, 1, 0], [0, 1, 1]]) { + const { root } = fakeChain(pin, at); + try { + const found = quickCheck(root); + assert.deepEqual(found.filter((x) => x.level === 'problem'), []); + assert.equal(found.filter((x) => x.level === 'note').length, notes); + } finally { fs.rmSync(root, { recursive: true, force: true }); } + } +}); + +test('build-info names the three commits the site is built from, as git has them', async () => { + const { buildInfo } = await import('../scripts/build-info.mjs'); + const ROOT = new URL('..', import.meta.url).pathname; + if (!fs.existsSync(path.join(ROOT, '.git')) && !process.env.CI) return; // a package has no commits to name + const info = buildInfo(); + const head = (dir) => spawnSync('git', ['-C', dir, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).stdout.trim(); + assert.equal(info.web.commit, head(ROOT)); + assert.equal(info.core.commit, head(path.join(ROOT, 'core'))); + assert.equal(info.library.commit, head(path.join(ROOT, 'core', 'library'))); + assert.equal(info.web.version, JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version); + assert.equal(info.core.version, JSON.parse(fs.readFileSync(path.join(ROOT, 'core', 'package.json'), 'utf8')).version); + assert.match(info.mojo, /^\d+\.\d+\.\d+$/); +}); diff --git a/tests/copy.test.mjs b/tests/copy.test.mjs new file mode 100644 index 0000000..e91a4be --- /dev/null +++ b/tests/copy.test.mjs @@ -0,0 +1,125 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// The site's own words (the home page, index.html, the README, docs/app.md, the library and the Quarto pages) say +// what is held and no more: the claims ledger (pplus-core work/release/claims.md) found sentences that claimed more. +// These tests hold the sentences that a test can hold, and keep the overstated ones from coming back. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { installDocument } from '../dist/quarto/dom.js'; + +installDocument(); +const store = new Map(); +globalThis.localStorage = { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, String(v)), removeItem: (k) => store.delete(k), key: (i) => [...store.keys()][i] ?? null, get length() { return store.size; } }; +const { homeView } = await import('../dist/ui/home.js'); +const { libraryView } = await import('../dist/ui/library.js'); +const { DESCRIPTION } = await import('../dist/core/site.js'); +const { AREAS } = await import('../dist/core/areas.js'); +const { PROBLEMS, problemById, stateForProblem } = await import('../dist/core/catalog.js'); +const { Session } = await import('../dist/core/session.js'); +const { machineView } = await import('../dist/ui/views/panels.js'); +const { generatedLabel } = await import('../dist/ui/provenance.js'); + +const read = (p) => readFileSync(new URL(`../${p}`, import.meta.url), 'utf8'); +const squash = (s) => s.replace(/\s+/g, ' '); +const home = homeView(); +const homeText = squash(home.textContent); +const html = read('index.html'); +const meta = / { + assert.match(DESCRIPTION, /^Programming\+ takes a procedure from an idea to Mojo to the machine\.$/); + assert.ok(meta.startsWith(DESCRIPTION), 'the meta description starts with it'); + assert.match(html, /Programming\+: from an idea to Mojo to the machine<\/title>/); + const hero = squash(home.querySelector('.hero').textContent); + assert.ok(hero.includes(DESCRIPTION), 'the hero says it'); + const firstParagraph = (md) => md.split('\n\n').find((p) => !p.startsWith('#')); + assert.ok(firstParagraph(read('README.md')).startsWith(DESCRIPTION), 'the README opens with it'); + assert.ok(firstParagraph(read('docs/app.md')).startsWith(DESCRIPTION), 'docs/app.md opens with it'); +}); + +test('each invented notation name is said what it is where the home page first uses it', () => { + const gloss = { lingo: /plain[- ]English/i, matho: /equations/i, pseudo: /pseudocode/i, speco: /specification/i }; + for (const [name, what] of Object.entries(gloss)) { + const at = homeText.search(new RegExp(`\\b${name}\\b`)); + assert.ok(at >= 0, `${name} is on the page`); + const around = homeText.slice(Math.max(0, at - 80), at + 80); + assert.match(around, what, `the first "${name}" is glossed: …${around}…`); + } + // the Bridge's tagline names them with what they are, and it is the first place on the page they appear + assert.match(AREAS.bridge.tagline, /plain-English steps \(lingo\), equations \(matho\) or pseudocode \(pseudo\)/); +}); + +test('the home page\'s samples are real runs: each card shows what the engines made as the page loaded', () => { + const cards = home.querySelectorAll('.area-card'); + assert.equal(cards.length, 3); + const bridge = home.querySelector('.area-card-bridge'); + assert.equal(bridge.querySelectorAll('.area-step').length, 4, 'matho, pseudo, lingo and Mojo'); + for (const pre of bridge.querySelectorAll('pre')) assert.ok(pre.textContent.trim().length > 5, 'each notation has text'); + const steps = home.querySelector('.area-card-dev').querySelectorAll('.feat-steps li'); + assert.ok(steps.length >= 5, 'the first steps of count_base'); + const regs = home.querySelector('.area-card-hw').querySelectorAll('.area-regs tr'); + assert.equal(regs.length, 5, 'five registers of the machine at the first load'); + assert.match(squash(home.querySelector('.proof-counts').textContent), /^[1-9]\d* proved ?0 broken ?0 open$/); +}); + +test('every problem with Mojo has Mojo verified on the real compiler, as the problem list says', () => { + assert.match(homeText, /each one with Mojo has a program verified on the real compiler/); + const withMojo = PROBLEMS.filter((p) => p.mojo || p.sources.mojo); + assert.ok(withMojo.length > 10); + for (const p of withMojo) assert.ok(p.mojo?.verified, `${p.id}: verified on the pinned compiler`); +}); + +test('where the Hardware area states a cost, it says it is the model machine\'s', () => { + assert.match(homeText, /the cycles each instruction costs on the model machine/); + assert.match(AREAS.hw.tagline, /model machine/); + assert.match(meta, /Hardware steps its x86-64 on a model machine/); + // the Counters card (the board, the machine embed, the Quarto pplus-machine view all draw it) + const st = stateForProblem(problemById('asm-two-pointers')); st.lang = 'asm'; + const root = document.createElement('div'); + machineView(new Session(st), root)(); + const text = squash(root.textContent); + assert.match(text, /cycles/); + assert.match(text, /a model machine: every count here is the model's, not a measurement of a real processor/); +}); + +test('the generated label promises nothing a compiler did not answer', () => { + const tip = generatedLabel('generated').getAttribute('title'); + assert.doesNotMatch(tip, /\bIt runs\b/); + assert.match(tip, /stops there with an error instead of guessing/); +}); + +test('the overstatements the claims ledger found stay gone', () => { + const surfaces = { + 'home page': homeText, + 'index.html': html, + 'README.md': read('README.md'), + 'AGENTS.md': read('AGENTS.md'), + 'docs/app.md': read('docs/app.md'), + 'docs/deploy.md': read('docs/deploy.md'), + 'quarto/README.md': read('quarto/README.md'), + 'library page': squash(libraryView().textContent), + 'src/ui/quarto.ts': read('src/ui/quarto.ts'), + }; + const never = [ + [/Everything runs in the browser/i, 'H1: Compile & run goes to godbolt.org'], + [/checked against the real compiler/i, 'H2: held to its answers on the corpus, asked about the rest'], + [/every step and every value in one Run view|every step and value in view|Every step, every value/i, 'H3: the interpreter reads a subset'], + [/it runs and it can be compiled/i, 'H4'], + [/completely specify any procedure|the notation is for any procedure/i, 'H5'], + [/registers, caches and pipeline it runs on/i, 'H7'], + [/It is built for the sciences/i, 'H8: an opinion'], + [/every short input|the smallest input/i, 'H9, A12: every DNA string up to three letters; a smaller input'], + [/The first group is computational biology/i, 'H10: the groups are by technique'], + [/no runtime dependenc/i, 'R4, R19: CodeMirror is vendored'], + [/gives `nan` in Mojo/i, 'A1: inf, -inf or nan'], + [/a program that stops printing what it should fails the render/i, 'Q1: only with pplus-strict'], + [/The prover is sound/i, 'A5: meant to be sound'], + [/checked at every level/i, 'library: open, skipped and unverified checks exist'], + [/interpreter are still JavaScript|typed only by their tests/i, "core's pseudo parser, checker and interpreter are strict TypeScript (core/src/engines/pseudo/*.ts)"], + [/interpreter declines `chr`, `ord`|a string doubled in a loop/i, "core's Mojo interpreter runs ord and chr, and its run limits stop a doubled String (core/docs/limits.md)"], + [/restructure plan|The plan said/i, 'a plan that is not in the repository'], + [/labelled|colour|behaviour|optimis/i, 'US English'], + ]; + for (const [where, text] of Object.entries(surfaces)) for (const [re, why] of never) assert.doesNotMatch(text, re, `${where}: ${why}`); +}); diff --git a/tests/course-css.test.mjs b/tests/course-css.test.mjs new file mode 100644 index 0000000..42244c9 --- /dev/null +++ b/tests/course-css.test.mjs @@ -0,0 +1,29 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// The course stylesheets in styles/course/ are copies of the course site's files. +// Each must still have the hash its README records, so a change is made upstream and copied, not edited here. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import crypto from 'node:crypto'; + +const DIR = new URL('../styles/course/', import.meta.url); + +test('the course stylesheets are the course site\'s files, unchanged', () => { + const readme = fs.readFileSync(new URL('README.md', DIR), 'utf8'); + const rows = [...readme.matchAll(/^\| `([\w-]+\.css)` \| `static\/css\/[^`]+` \|[^|]*\| `([0-9a-f]{64})` \|$/gm)]; + assert.deepEqual(rows.map((r) => r[1]).sort(), ['asm86.css', 'kit.css', 'tokens.css']); + for (const [, file, want] of rows) { + const got = crypto.createHash('sha256').update(fs.readFileSync(new URL(file, DIR))).digest('hex'); + assert.equal(got, want, `styles/course/${file} differs from the copy the README records`); + } +}); + +test('the bridge supplies every page variable the course stylesheets read', () => { + const bridge = fs.readFileSync(new URL('bridge.css', DIR), 'utf8'); + const read = new Set(); + for (const f of ['tokens.css', 'kit.css', 'asm86.css']) { + for (const m of fs.readFileSync(new URL(f, DIR), 'utf8').matchAll(/var\((--bs-[\w-]+)/g)) read.add(m[1]); + } + for (const v of read) assert.match(bridge, new RegExp(`${v}\\s*:`), `bridge.css does not set ${v}`); +}); diff --git a/tests/csp.test.mjs b/tests/csp.test.mjs new file mode 100644 index 0000000..82e954c --- /dev/null +++ b/tests/csp.test.mjs @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// The Content-Security-Policy in docs/Caddyfile is the one the site runs under: these tests hold it to index.html +// (every inline script is allowed by its hash, nothing loads from another origin) and to what the app sends. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { createHash } from 'node:crypto'; +import { GODBOLT_BASE } from '../core/dist/mojo/generated/pin.js'; + +const caddy = readFileSync(new URL('../docs/Caddyfile', import.meta.url), 'utf8'); +const html = readFileSync(new URL('../index.html', import.meta.url), 'utf8'); +const header = (name) => { const m = new RegExp(`^\\s*${name}\\s+"([^"]*)"`, 'm').exec(caddy); return m ? m[1] : null; }; +const csp = header('Content-Security-Policy'); +const directive = (name) => (csp ?? '').split(';').map((d) => d.trim().split(/\s+/)).find((d) => d[0] === name)?.slice(1) ?? null; + +test('the Caddy block sets a CSP and the other security headers', () => { + assert.ok(csp, 'Content-Security-Policy'); + assert.equal(header('Referrer-Policy'), 'no-referrer'); + assert.equal(header('X-Content-Type-Options'), 'nosniff'); + assert.match(header('Permissions-Policy') ?? '', /camera=\(\)/); + assert.doesNotMatch(caddy, /^\s*X-Frame-Options\s/m, 'course pages embed the app: framing is decided by frame-ancestors alone'); + for (const d of ['default-src', 'script-src', 'style-src', 'font-src', 'connect-src', 'object-src', 'base-uri', 'frame-ancestors']) assert.ok(directive(d), d); + assert.deepEqual(directive('object-src'), ["'none'"]); +}); + +test('every inline script of index.html is allowed by its hash, and scripts allow nothing looser', () => { + const inline = [...html.matchAll(/<script(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/g)].map((m) => m[1]); + assert.ok(inline.length >= 2, 'the theme script and the import map'); + const allowed = directive('script-src'); + for (const body of inline) { + const hash = `'sha256-${createHash('sha256').update(body, 'utf8').digest('base64')}'`; + assert.ok(allowed.includes(hash), `index.html changed an inline script: put ${hash} in script-src (docs/Caddyfile)`); + } + for (const loose of ["'unsafe-inline'", "'unsafe-eval'", '*', 'data:', 'https:']) assert.ok(!allowed.includes(loose), `script-src ${loose}`); +}); + +test('the page loads nothing from another origin (the fonts are the site\'s own)', () => { + const refs = [...html.matchAll(/\b(?:href|src)="([^"]+)"/g)].map((m) => m[1]).filter((u) => !u.startsWith('data:')); + assert.ok(refs.length > 3); + for (const u of refs) assert.ok(!/^(https?:)?\/\//.test(u), `index.html loads ${u}`); + assert.doesNotMatch(html, /fonts\.googleapis|fonts\.gstatic/); + assert.deepEqual(directive('font-src'), ["'self'"]); +}); + +test('connect-src allows the compile backend and nothing else outside the site', () => { + const origin = new URL(GODBOLT_BASE).origin; + const allowed = directive('connect-src'); + assert.ok(allowed.includes(origin), `Compile & run posts to ${origin}`); + assert.deepEqual(allowed.filter((s) => s !== "'self'"), [origin]); +}); + +test('the fonts the page names are in the repository, with their license', () => { + const css = readFileSync(new URL('../fonts/plex.css', import.meta.url), 'utf8'); + const files = [...css.matchAll(/url\("\.\/([^"]+)"\)/g)].map((m) => m[1]); + assert.equal(files.length, 7); + for (const f of files) assert.ok(readFileSync(new URL(`../fonts/${f}`, import.meta.url)).length > 10000, f); + assert.match(readFileSync(new URL('../fonts/LICENSE.txt', import.meta.url), 'utf8'), /SIL Open Font License, Version 1\.1/); + assert.match(readFileSync(new URL('../scripts/assemble.sh', import.meta.url), 'utf8'), /\bfonts\b/, 'assemble.sh copies fonts/ into the site'); +}); diff --git a/tests/editor.test.mjs b/tests/editor.test.mjs new file mode 100644 index 0000000..62b35f2 --- /dev/null +++ b/tests/editor.test.mjs @@ -0,0 +1,33 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// Every code pane is the CodeMirror editor (src/ui/editor.ts), never a plain <textarea>. +// A textarea loses highlighting, line numbers, the teaching gutter (diagnostics, breakpoints, +// run counts, the current line), hover help, and search, so these checks fail loudly if a +// refactor swaps one in or the vendored CodeMirror stops being built. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; + +const src = (p) => fs.readFileSync(new URL(`../${p}`, import.meta.url), 'utf8'); + +test('the editor is CodeMirror 6, vendored and built into dist/', () => { + assert.match(src('src/ui/editor.ts'), /from '\.\.\/vendor\/codemirror\.js'/); + assert.ok(fs.existsSync(new URL('../dist/vendor/codemirror.js', import.meta.url)), 'dist/vendor/codemirror.js is missing: the build no longer ships the editor'); + assert.ok(fs.statSync(new URL('../dist/vendor/codemirror.js', import.meta.url)).size > 100_000, 'dist/vendor/codemirror.js is too small to be CodeMirror'); +}); + +test('the workspace and the embeds make their code panes with Editor', () => { + for (const f of ['src/ui/shell.ts', 'src/ui/embed.ts']) { + const text = src(f); + assert.match(text, /import \{[^}]*\bEditor\b[^}]*\} from '\.\/editor\.js'/, `${f} no longer imports Editor`); + assert.match(text, /new Editor\(/, `${f} no longer makes an Editor`); + } +}); + +test('textareas are only for the small setup and input boxes, never for code', () => { + for (const f of ['src/ui/shell.ts', 'src/ui/embed.ts']) { + for (const m of src(f).matchAll(/el\('textarea',\s*\{([^}]*)\}/g)) { + assert.match(m[1], /setup-ta/, `${f} makes a textarea that is not a setup or input box: ${m[0].slice(0, 80)}`); + } + } +}); diff --git a/tests/hardening.test.mjs b/tests/hardening.test.mjs new file mode 100644 index 0000000..85887bd --- /dev/null +++ b/tests/hardening.test.mjs @@ -0,0 +1,234 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// What anyone on the internet can hand the app: a link, a file, a saved state, a program. Each must end in a +// message or a working page, never an exception, a hang, or someone else's work saved over the reader's. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { decodeState, encodeState, normalize, parseRoute, isUnknownRoute, readStateFile, StateError, LIMITS, emptyState } from '../dist/core/state.js'; +import { Session, sharedSession, engineStopMessage } from '../dist/core/session.js'; +import { markBusy, takeCrashed, settle, setAside, clearBusy } from '../dist/core/guard.js'; +import { listVersions } from '../dist/core/versions.js'; + +const b64url = (bytes) => Buffer.from(bytes).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +async function deflate(text) { + const s = new Blob([text]).stream().pipeThrough(new CompressionStream('deflate-raw')); + return new Uint8Array(await new Response(s).arrayBuffer()); +} +const fakeStore = () => { + const m = new Map(); + return { m, getItem: (k) => m.get(k) ?? null, setItem: (k, v) => void m.set(k, String(v)), removeItem: (k) => void m.delete(k), key: (i) => [...m.keys()][i] ?? null, get length() { return m.size; } }; +}; +async function rejectsWith(p, re) { + await assert.rejects(p, (e) => { assert.ok(e instanceof StateError, `a StateError, not ${e?.name}: ${e?.message}`); assert.match(e.message, re); return true; }); +} + +test('a link that inflates past the limit (a decompression bomb) is refused before it is read', async () => { + const bomb = await deflate(JSON.stringify({ v: 3, sources: { pseudo: 'x'.repeat(LIMITS.stateBytes * 4) } })); + assert.ok(bomb.length < 40_000, 'the blob itself is small'); + await rejectsWith(decodeState(b64url(bomb)), /more than Programming\+ opens/); + // uncompressed, behind the plain-text marker, a link cannot hold that much at all + await rejectsWith(decodeState('~' + b64url(Buffer.from('{"v":3,"sources":{"pseudo":"' + 'x'.repeat(LIMITS.stateBytes) + '"}}'))), /longer than any Programming\+ makes/); +}); + +test('a link longer than any the app writes is refused without decoding it', async () => { + await rejectsWith(decodeState('A'.repeat(LIMITS.linkChars + 1)), /longer than any Programming\+ makes/); +}); + +test('a cut-short, changed or garbage link says it is damaged', async () => { + const good = await encodeState({ ...emptyState(), sources: { pseudo: 'OUTPUT 1\n'.repeat(40) } }); + await rejectsWith(decodeState(good.slice(0, Math.floor(good.length / 2))), /damaged/); + await rejectsWith(decodeState('not base64!'), /damaged/); + await rejectsWith(decodeState('~' + b64url(Buffer.from('{"v":3,'))), /damaged/); + await rejectsWith(decodeState('~' + b64url(Buffer.from([0xff, 0xfe, 0x00]))), /damaged/); + await rejectsWith(decodeState('AAAA'), /damaged/); + // a whole link still opens + assert.equal((await decodeState(good)).sources.pseudo, 'OUTPUT 1\n'.repeat(40)); + // a state from another format is empty, as before (docs/app.md) + assert.deepEqual(await decodeState('~' + b64url(Buffer.from('{"v":2}'))), emptyState()); +}); + +test('a malformed escape in an address does not throw; an unknown embed view is the problems view', () => { + assert.doesNotThrow(() => parseRoute('#/library/%E0%A4')); + assert.deepEqual(parseRoute('#/bridge/p/%E0%A4'), { kind: 'problem', area: 'bridge', id: '%E0%A4' }); + assert.deepEqual(parseRoute('#/library/%E0'), { kind: 'library', id: '%E0' }); + const r = parseRoute('#/embed/<img onerror=x>/p/count-base'); + assert.equal(r.kind, 'embed'); assert.equal(r.view, 'problems'); + assert.doesNotThrow(() => parseRoute('#/embed/trace/p/%')); +}); + +test('an address that names no page is told apart from the home page and its anchors', () => { + for (const h of ['#/s/abc', '#/bridge/x', '#/p/count-base', '#/nope', '#/bridge/p/', '#/embed']) assert.ok(isUnknownRoute(h), h); + for (const h of ['', '#', '#/', '#/#problems', '#/#reference', '#ref-pseudo', '#/bridge/p/count-base', '#/library', '#/quarto', '#/quarto#setup', '#/dev/s/abc']) assert.ok(!isUnknownRoute(h), h); +}); + +test('only an anchor on the page already shown scrolls in place; from the library, #/#problems opens the home page', async () => { + const { anchorOnly } = await import('../dist/core/state.js'); + assert.equal(anchorOnly('#/#problems', ['home', 'home-page']), true); + assert.equal(anchorOnly('#/#problems', ['home', 'lib']), false, 'the library page is not the home page'); + assert.equal(anchorOnly('#/#problems', ['home', 'message-page']), false); + assert.equal(anchorOnly('#/#reference', null), false); + assert.equal(anchorOnly('#/nope/x', ['home', 'home-page']), false, 'an unknown address is rebuilt, with its note'); + assert.equal(anchorOnly('#/quarto#setup', ['home', 'qg']), true); + assert.equal(anchorOnly('#/quarto#setup', ['home', 'home-page']), false); + assert.equal(anchorOnly('#/bridge/p/count-base', ['home', 'home-page']), false); +}); + +test('a problem id from a link is only ever an id', () => { + assert.equal(normalize({ v: 3, problem: 'count-base' }).problem, 'count-base'); + assert.equal(normalize({ v: 3, problem: 'lib:md.LennardJones' }).problem, 'lib:md.LennardJones'); + for (const bad of ['', '../x', 'a b', '<script>', 'x'.repeat(200), 'a/b']) assert.equal(normalize({ v: 3, problem: bad }).problem, undefined, bad); +}); + +test('a shared link never saves over the reader\'s own work on the problem it names', () => { + const store = fakeStore(); + globalThis.localStorage = store; + try { + store.setItem('pplus.count-base', JSON.stringify({ v: 3, problem: 'count-base', sources: { pseudo: 'MY WORK' } })); + const s = sharedSession(normalize({ v: 3, problem: 'count-base', sources: { pseudo: 'OUTPUT 1' } }), 'bridge'); + s.setSource('pseudo', 'OUTPUT 2'); s.setView('proof'); s.setT(3); + assert.match(store.getItem('pplus.count-base'), /MY WORK/); + assert.deepEqual([...store.m.keys()], ['pplus.count-base']); + } finally { delete globalThis.localStorage; settle(null); } +}); + +test('a .pplus.json that is not one says so; a real one opens with its versions', () => { + assert.throws(() => readStateFile('hello'), (e) => e instanceof StateError && /not JSON/.test(e.message)); + for (const t of ['[1,2]', '{}', 'null', '42', '{"name":"package","version":"1.0.0"}']) assert.throws(() => readStateFile(t), (e) => e instanceof StateError && /not a Programming\+ state/.test(e.message), t); + assert.throws(() => readStateFile(' '.repeat(LIMITS.stateBytes + 1)), (e) => e instanceof StateError && /larger than Programming\+ opens/.test(e.message)); + const file = JSON.stringify({ pplus: 1, savedAt: 'x', state: { v: 3, sources: { pseudo: 'OUTPUT 1' }, lang: 'pseudo' }, versions: [{ id: 'v1', name: 'a', at: 1, area: 'bridge', edits: {} }] }); + const r = readStateFile(file); + assert.equal(r.state.sources.pseudo, 'OUTPUT 1'); assert.equal(r.versions.length, 1); + // a bare state (no wrapper) opens too, and one from an earlier format opens empty, as a link does + assert.equal(readStateFile('{"v":3,"sources":{"mojo":"def main():\\n pass"}}').state.sources.mojo, 'def main():\n pass'); + assert.deepEqual(readStateFile('{"v":2,"sources":{"pseudo":"OUTPUT 1"}}').state, emptyState()); +}); + +test('a pane nested past what a reader can follow gets a located answer from the reader, and the page keeps working', () => { + // core's readers have limits of their own now (core docs/limits.md), so each of these is the reader's answer; the + // session's catch is the net under them, and engineStopMessage is what it would say + const deep = (o, c, n, mid = '1') => o.repeat(n) + mid + c.repeat(n); + const ids = (s, lang) => s.diagnostics(lang).filter((d) => d.severity !== 'note' || d.id === 'unread').map((d) => d.id); + const mojo = new Session(normalize({ v: 3, lang: 'mojo', sources: { mojo: `def main():\n print(${deep('(', ')', 30000)})\n` } }), { area: 'dev', storageId: null }); + const d = mojo.diagnostics('mojo'); + // Mojo: not an error (the compiler takes thousands of levels), one note that Programming+ does not read it + assert.equal(d.length, 1); assert.equal(d[0].id, 'unread'); assert.equal(d[0].line, 2); assert.match(d[0].message, /nested more than 200 levels deep/); + assert.equal(mojo.trace().error.kind, 'unsupported'); + assert.deepEqual(mojo.trace().steps, []); + assert.deepEqual(mojo.fuzz(), []); + // a linked pane: opening it and editing it carry no exception to the views + const lingo = new Session(normalize({ v: 3, lang: 'lingo', sources: { lingo: 'To f with n:\n the answer is ' + deep('(', ')', 30000) } }), { area: 'bridge', storageId: null }); + assert.deepEqual(ids(lingo, 'lingo'), ['too-long', 'too-deep']); + assert.doesNotThrow(() => { lingo.source('pseudo'); lingo.trace(); lingo.proof(); lingo.allDiagnostics(); }); + const nested = new Session(normalize({ v: 3, lang: 'lingo', sources: { lingo: 'To f with n:\n the answer is ' + deep('(', ')', 300, 'n') + '.' } }), { area: 'bridge', storageId: null }); + assert.deepEqual(ids(nested, 'lingo'), ['too-deep']); + const typed = new Session(normalize({ v: 3, lang: 'lingo', sources: { pseudo: 'OUTPUT 1' } }), { area: 'bridge', storageId: null }); + assert.doesNotThrow(() => typed.setSource('lingo', 'To f with n:\n the answer is ' + deep('(', ')', 30000))); + assert.equal(typed.linkState('pseudo').kind, 'stale'); + assert.match(typed.linkState('pseudo').reason ?? '', /does not read yet \(This sentence has more than 1,000 words and symbols/); + const matho = new Session(normalize({ v: 3, lang: 'matho', sources: { matho: 'f(x) = ' + deep('{', '}', 30000, 'x') } }), { area: 'bridge', storageId: null }); + assert.deepEqual(ids(matho, 'matho'), ['matho-too-long']); + assert.doesNotThrow(() => { matho.allDiagnostics(); matho.trace(); }); + // the net: a reader that still overflowed the stack, or threw anything else, would be worded like this + assert.match(engineStopMessage(new RangeError('Maximum call stack size exceeded')), /nested more deeply than Programming\+ can read/); + assert.match(engineStopMessage(new Error('boom')), /stopped reading this pane: boom\. This is a fault in Programming\+/); +}); + +test('work that was running when the page died is set aside as a version, and the problem opens as written', () => { + const store = fakeStore(); + markBusy('count-base', store); + assert.equal(store.getItem('pplus.busy'), 'count-base'); + // the page died: the mark is still there at the next load, read once + assert.equal(takeCrashed(store), 'count-base'); + assert.equal(takeCrashed(store), null); + const saved = normalize({ v: 3, problem: 'count-base', sources: { mojo: 'def main():\n var t = String("x")\n while True:\n t = t + t\n' } }); + store.setItem('pplus.count-base', JSON.stringify(saved)); + const name = setAside('count-base', saved, 'dev', 'stopped', store, Date.UTC(2026, 10, 12, 15, 42)); + assert.match(name, /^When the page stopped \(/); + assert.equal(store.getItem('pplus.count-base'), null, 'the save is gone, so the problem opens as written'); + const v = listVersions('pplus.versions.count-base', store); + assert.equal(v.length, 1); assert.equal(v[0].name, name); assert.equal(v[0].auto, undefined, 'a named version: never the first to make room'); + assert.match(v[0].edits.sources.mojo, /t = t \+ t/); + // a store that refuses the version keeps the save where it is + const full = { ...fakeStore(), setItem() { throw new Error('QuotaExceededError'); } }; + assert.equal(setAside('count-base', saved, 'dev', 'stopped', full), null); + // a page that settled or closed normally leaves nothing + markBusy('x', store); clearBusy('x', store); assert.equal(takeCrashed(store), null); + markBusy('x', store); settle(store); assert.equal(takeCrashed(store), null); + // no storage at all: nothing to mark, nothing to find + assert.doesNotThrow(() => { markBusy('x', null); takeCrashed(null); settle(null); }); + settle(null); +}); + +test('a session marks its save busy when it saves, so a run that kills the page is found at the next load', () => { + const store = fakeStore(), tab = fakeStore(); + globalThis.localStorage = store; globalThis.sessionStorage = tab; + try { + const s = new Session(normalize({ v: 3, problem: 'count-base', sources: { pseudo: 'OUTPUT 1' } }), { area: 'bridge' }); + s.setSource('pseudo', 'OUTPUT 2'); + assert.equal(tab.getItem('pplus.busy'), 'count-base', 'in this tab\'s storage'); + assert.equal(store.getItem('pplus.busy'), null, 'not among the saved work'); + } finally { settle(null); delete globalThis.localStorage; delete globalThis.sessionStorage; } +}); + +test('storage that throws on every call (disabled, or full) is survived by every save path', () => { + const throwing = { getItem() { throw new Error('SecurityError'); }, setItem() { throw new Error('QuotaExceededError'); }, removeItem() { throw new Error('SecurityError'); }, key() { throw new Error('SecurityError'); }, get length() { throw new Error('SecurityError'); } }; + globalThis.localStorage = throwing; globalThis.sessionStorage = throwing; + try { + const s = new Session(normalize({ v: 3, problem: 'count-base', sources: { pseudo: 'OUTPUT 1' } }), { area: 'bridge' }); + assert.doesNotThrow(() => { s.setSource('pseudo', 'OUTPUT 2'); s.saveVersion('mine'); s.versions(); s.hasUnsavedEdits(); }); + assert.doesNotThrow(() => { markBusy('count-base'); takeCrashed(); settle(); }); + } finally { delete globalThis.localStorage; delete globalThis.sessionStorage; settle(null); } +}); + +test('the first Compile & run asks before anything is sent, and the answer stays in this browser', async () => { + const { sendAllowed, allowSend, forgetSend } = await import('../dist/core/prefs.js'); + const store = fakeStore(); + globalThis.localStorage = store; + try { + forgetSend(); + assert.equal(sendAllowed(), false, 'nothing is sent before the reader agrees'); + allowSend(); + assert.equal(sendAllowed(), true); + assert.equal(store.getItem('pplus.send.godbolt'), '1'); + // never in a state, a link or a file + assert.ok(!JSON.stringify(normalize({ v: 3, sendGodbolt: true, send: true })).includes('send')); + forgetSend(); + assert.equal(sendAllowed(), false); + } finally { delete globalThis.localStorage; } +}); + +test('a title from a link cannot end the shortcode the Share dialog writes for a page author', async () => { + const { shortcodeTitle } = await import('../dist/quarto/shortcodes.js'); + const evil = 'Mean" >}}\n<script>alert(1)</script>{{< pplus-embed'; + const t = shortcodeTitle(evil); + assert.doesNotMatch(t, /[<>{}"\n]/); + assert.equal(t, 'Mean" scriptalert(1)/script pplus-embed'); + assert.equal(shortcodeTitle('Find a pattern, stepped through'), 'Find a pattern, stepped through'); + assert.equal(shortcodeTitle('x'.repeat(300)).length, 120); +}); + +test('the trace\'s CSV and the table\'s copied text cannot start a spreadsheet formula', async () => { + const { csvCell, toCsv, toTsv, safeCell } = await import('../dist/core/csv.js'); + for (const bad of ['=HYPERLINK("http://x","y")', '+1+1', '-2+3', '@SUM(A1)', '\t=1', '\r=1']) assert.ok(safeCell(bad).startsWith("'"), JSON.stringify(bad)); + for (const ok of ['-3', '+2.5', '1e-9', '-0.5', 'count_base', 'x = 1', '']) assert.equal(safeCell(ok), ok, 'numbers and ordinary text stay as they are'); + assert.equal(csvCell('say "hi"'), '"say ""hi"""'); + assert.equal(csvCell(12), '"12"'); + assert.equal(toCsv([['step', 'what ran'], [1, '=cmd|\' /C calc\'!A0']]), '"step","what ran"\n"1","\'=cmd|\' /C calc\'!A0"'); + assert.equal(toTsv([['N', '=1+1', 'a\tb']]), "N\t'=1+1\ta b"); + const src = (p) => fs.readFileSync(new URL(`../src/ui/views/${p}`, import.meta.url), 'utf8'); + assert.match(src('trace.ts'), /new Blob\(\[toCsv\(rows\)\]/, 'the CSV button writes through toCsv'); + assert.match(src('viz.ts'), /writeText\(toTsv\(rows\)\)/, 'the table\'s copy goes through toTsv'); +}); + +test('a framed view can grow its frame on a Quarto page, to a cap, and only with a finite height', async () => { + const { runInNewContext } = await import('node:vm'); + const window = { addEventListener() {} }; + const document = { body: null, documentElement: {}, addEventListener() {}, querySelectorAll: () => [] }; + runInNewContext(fs.readFileSync(new URL('../quarto/_extensions/pplus/pplus.js', import.meta.url), 'utf8'), { window, document, MutationObserver: class { observe() {} } }); + const h = window.PPlus.frameHeight; + assert.equal(h(500), 502); + assert.equal(h(10), 120, 'never smaller than 120px'); + assert.equal(h(1e9), 4000, 'never taller than 4000px'); + for (const bad of [Infinity, NaN, '900', null, undefined, {}]) assert.equal(h(bad), null, String(bad)); +}); diff --git a/tests/hardware.test.mjs b/tests/hardware.test.mjs new file mode 100644 index 0000000..a882b2b --- /dev/null +++ b/tests/hardware.test.mjs @@ -0,0 +1,235 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// Stage 15: the Hardware area's machine board. The course's views draw it (src/engines/asm86/views.js and +// hwviews.js) and need a DOM, so they are checked by hand; what they are given is decided DOM-free in +// core/hardware.ts and is tested here, for every problem that has assembly: which views each preset mounts and with +// what options, and the frame each one draws at every step. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { themeBodyClass } from '../dist/ui/theme.js'; +import { BOARD_PRESETS, BOARD_VIEWS, BOARD_GROUPS, MACHINE_PRESETS, boardPreset, boardView, boardFrame, subRegisterWidths, normalizeBoard, presetOf, moveItem, addItem, removeItem, toggleWide, isWide, courseViews, parseMachine, machineName, machineSpec, machineLabel, lineTouches, asmMojoLines, relateAsmMojo } from '../dist/core/hardware.js'; +import { stageOccupancy, STAGES } from '../core/dist/engines/asm86/pipeline.js'; +import { coreAt } from '../core/dist/engines/asm86/ooo.js'; +import { decompose } from '../core/dist/engines/asm86/uops.js'; +import fs from 'node:fs'; +import { stripHeader, buildListing } from '../core/scripts/mojo/listings.mjs'; +import { forSimulator, simulatorSetup } from '../core/dist/mojo/att.js'; +import { listingFunctions, mojoBuildArgs } from '../core/dist/services/godbolt.js'; +import { hardwareFor, resolveMachine } from '../core/dist/engines/asm86/machine.js'; +import { viewNames } from '../core/dist/engines/asm86/views.js'; +import { PROBLEMS, stateForProblem } from '../dist/core/catalog.js'; +import { Session } from '../dist/core/session.js'; +import { normalize, emptyState } from '../dist/core/state.js'; +import { SERVICES } from '../core/dist/services/index.js'; + +globalThis.localStorage = { getItem() { return null; }, setItem() { }, removeItem() { } }; + +/** Every catalog problem with an x86-64 pane, run as the Hardware area runs it. */ +const WITH_ASM = PROBLEMS.filter((p) => (p.sources?.asm ?? '').trim()); +const traceOf = (p, machine) => { + const st = stateForProblem(p); + if (machine) st.machine = machine; + st.lang = 'asm'; + const s = new Session(st, { area: 'hw', storageId: null }); + const tr = s.trace(); + assert.ok(tr && tr.lang === 'asm', `${p.id}: the x86-64 pane runs`); + return { session: s, tr, raw: tr.raw.trace }; +}; + +test('the body class follows what the page shows: the setting, the system, or a host page that forces one', () => { + assert.equal(themeBodyClass('light', true), 'quarto-light', 'a light app on a dark system draws light widgets'); + assert.equal(themeBodyClass('dark', false), 'quarto-dark'); + assert.equal(themeBodyClass('system', true), 'quarto-dark'); + assert.equal(themeBodyClass('system', false), 'quarto-light'); + for (const setting of ['light', 'dark', 'system']) for (const sys of [true, false]) { + assert.equal(themeBodyClass(setting, sys, 'dark'), 'quarto-dark', 'an embed\'s ?theme= (or the host\'s switch) wins'); + assert.equal(themeBodyClass(setting, sys, 'light'), 'quarto-light'); + } +}); + +test('every card the board offers is a course view or one of the app\'s own, in a group, and every preset is made of them', () => { + const known = new Set(viewNames()); + const APP = new Set(['setup', 'output', 'problems', 'compiler', 'run', 'counters', 'lines']); + assert.ok(WITH_ASM.length >= 10, 'the problems with assembly are found'); + assert.equal(new Set(BOARD_VIEWS.map((v) => v.id)).size, BOARD_VIEWS.length, 'each card once'); + for (const v of BOARD_VIEWS) { + assert.ok(BOARD_GROUPS.includes(v.group), `${v.id}: a group of the add menu`); + assert.ok(v.label && v.blurb, `${v.id}: a label and a line saying what it shows`); + if (v.course) assert.ok(known.has(v.course.name), `${v.id} mounts "${v.course.name}", which views.js does not have`); + else assert.ok(APP.has(v.id), `${v.id}: drawn by the app`); + } + for (const preset of BOARD_PRESETS) { + assert.ok(preset.items.length >= 3 && preset.items.every((it) => boardView(it.id)), `${preset.id}: cards that exist`); + assert.equal(presetOf(preset.items), preset.id, 'a preset is recognized as itself'); + for (const p of WITH_ASM) { + const { raw } = traceOf(p); + for (const machine of ['teaching', 'teaching+paging']) for (const c of courseViews(preset.items, raw, parseMachine(machine))) { + assert.ok(known.has(c.name)); + assert.equal(typeof c.options, 'object', `${preset.id}/${c.id}: options for ${p.id}`); + } + } + } + assert.equal(boardPreset(undefined).id, 'regs', 'the board opens on registers and memory'); + assert.equal(boardPreset('nonsense').id, 'regs'); + assert.ok(BOARD_PRESETS.some((p) => p.items.some((it) => it.id === 'run')), 'a preset for the Mojo side'); +}); + +test('the student\'s own arrangement: move, add, remove, widen, and what a saved one may hold', () => { + const regs = boardPreset('regs').items; + const moved = moveItem(regs, regs.length - 1, 0); + assert.equal(moved[0].id, regs[regs.length - 1].id); + assert.equal(moved.length, regs.length); + assert.equal(presetOf(moved), null, 'a changed arrangement is the student\'s own'); + assert.deepEqual(moveItem(moved, 0, regs.length - 1).map((x) => x.id), regs.map((x) => x.id), 'and moves back'); + assert.deepEqual(moveItem(regs, 9, 0), regs, 'a move from nowhere changes nothing'); + const added = addItem(regs, 'pipeline', 0); + assert.equal(added[0].id, 'pipeline'); + assert.deepEqual(addItem(added, 'pipeline'), added, 'a card is on the board once'); + assert.deepEqual(addItem(regs, 'warp-drive'), regs, 'an unknown card is not added'); + assert.ok(!removeItem(added, 'pipeline').some((x) => x.id === 'pipeline')); + const flags = regs.find((x) => x.id === 'flags'); + assert.equal(isWide(toggleWide(regs, 'flags').find((x) => x.id === 'flags')), !isWide(flags)); + assert.deepEqual(normalizeBoard([{ id: 'flags', wide: true }, 'memory', { id: 'flags' }, { id: 'nope' }, 7, null]), [{ id: 'flags', wide: true }, { id: 'memory' }], 'known cards, each once, widths kept'); + assert.equal(normalizeBoard('regs'), undefined); + assert.equal(normalizeBoard(Array.from({ length: 40 }, () => 'flags')).length, 1); + assert.ok(normalizeBoard(BOARD_VIEWS.map((v) => v.id)).length <= 24, 'at most 24 cards'); + // virtual memory's card mounts only with virtual memory on + const { raw } = traceOf(PROBLEMS.find((x) => x.id === 'asm-two-pointers')); + assert.deepEqual(courseViews([{ id: 'paging' }], raw, parseMachine('teaching')), []); + assert.equal(courseViews([{ id: 'paging' }], raw, parseMachine('teaching+paging')).length, 1); +}); + +test('the frame at every step is the one the course views expect, for every problem with assembly', () => { + for (const p of WITH_ASM) { + const { raw } = traceOf(p); + for (let t = -1; t <= raw.count + 1; t++) { + const f = boardFrame(raw, t); + const tt = Math.max(0, Math.min(t, raw.count)); + assert.equal(f.t, tt); + assert.equal(f.state, raw.states[tt]); + assert.equal(f.last, tt ? raw.steps[tt - 1] : null, `${p.id}: the step that just ran`); + if (f.next) assert.equal(f.next, raw.program.instrs[f.state.pc]); + } + } +}); + +test('the register cards show every width the program uses', () => { + const asm = SERVICES.asm.parse(' mov eax, 7\n mov cl, byte ptr [rdi]\n add r8d, 1\n mov rbx, rsi\n ret'); + assert.ok(asm.ok); + assert.deepEqual(new Set(subRegisterWidths(asm.program)), new Set(['rax', 'rcx', 'r8']), 'rbx and rsi are only used whole'); + const widths = PROBLEMS.find((p) => p.id === 'asm-register-widths'); + assert.ok(widths, 'the register-widths problem exists'); + const { raw } = traceOf(widths); + assert.ok(subRegisterWidths(raw.program).length > 1, 'its registers show their narrower names'); +}); + +test('the arrangement is part of the area\'s layout and normalizes', () => { + const st = emptyState(); + st.layout = { hw: { board: [{ id: 'cache', wide: false }, 'flags'], dock: 0.5 } }; + assert.deepEqual(normalize(JSON.parse(JSON.stringify(st))).layout.hw.board, [{ id: 'cache', wide: false }, { id: 'flags' }]); + st.layout = { hw: { board: 'warp-drive' } }; + assert.equal(normalize(JSON.parse(JSON.stringify(st))).layout.hw.board, undefined); + const s = new Session(emptyState(), { area: 'hw', storageId: null }); + s.setLayout({ board: [{ id: 'counters' }] }); + assert.deepEqual(s.layout().board, [{ id: 'counters' }]); +}); + + +test('each load and store shows the line it touched and how much of the line the program uses', () => { + let touched = 0, missed = 0, partial = 0; + for (const p of WITH_ASM) for (const machine of ['teaching', 'realistic', 'teaching+paging']) { + const { raw } = traceOf(p, machine); + const hw = hardwareFor(raw); + const L = hw.memory().hierarchy.line; + assert.deepEqual(lineTouches(hw, 0), [], 'nothing has run at step 0'); + for (let t = 1; t <= raw.count; t++) { + const step = raw.steps[t - 1]; + const xs = lineTouches(hw, t); + if (!machine.includes('paging')) { + // without virtual memory the caches see the program's own addresses: every access of the step is there + const want = step.accesses.reduce((n, a) => n + (Math.floor((a.addr + Math.max(1, a.size) - 1) / L) - Math.floor(a.addr / L) + 1), 0); + assert.equal(xs.length, want, `${p.id} step ${t}: one entry per line per access`); + } + for (const x of xs) { + touched++; + if (!x.hit) missed++; + assert.equal(x.lineSize, L); + assert.equal(x.lineAddr % L, 0); + assert.ok(x.from >= 0 && x.from < x.to && x.to <= L, `${p.id} step ${t}: the bytes are inside the line`); + assert.equal(x.hit, x.level === 'L1d', 'a hit is a line found in L1d'); + for (let b = x.from; b < x.to; b++) assert.ok(x.usedSoFar.includes(b), 'the bytes used now count as used'); + assert.ok(x.usedSoFar.every((b) => x.usedInRun.includes(b)), 'used so far is part of used in the run'); + assert.ok(x.usedInRun.length <= L); + if (x.usedInRun.length < L) partial++; + if (!machine.includes('paging')) assert.equal(x.vaddr, x.addr); + } + } + } + assert.ok(touched > 50, 'the problems load and store'); + assert.ok(missed > 0, 'the teaching machine misses on small data'); + assert.ok(partial > 0, 'some lines are only partly used, which is what the view is for'); +}); + +test('virtual memory: the line is the physical one, and the access keeps the address the program wrote', () => { + const p = PROBLEMS.find((x) => x.id === 'asm-two-pointers'); + const { raw } = traceOf(p, 'teaching+paging'); + const hw = hardwareFor(raw); + const all = []; + for (let t = 1; t <= raw.count; t++) all.push(...lineTouches(hw, t).map((x) => ({ x, step: raw.steps[t - 1] }))); + assert.ok(all.length); + for (const { x, step } of all) assert.ok(step.accesses.some((a) => x.vaddr >= a.addr && x.vaddr < a.addr + Math.max(1, a.size)), 'the virtual address is one the instruction used'); + assert.ok(all.some(({ x }) => x.vaddr !== x.addr), 'and at least one is translated to another physical address'); +}); + + +test('Mojo beside x86-64: the line table the compiler left in the pane links each instruction to its Mojo line', () => { + const asm = 'add: ; add(Int, Int)\n mov rax, rdi ; mojo line 2\n add rax, rsi ; mojo line 2\n ret\n call add ; mojo line 6'; + assert.deepEqual([...asmMojoLines(asm)], [[2, 2], [3, 2], [5, 6]]); + assert.deepEqual(relateAsmMojo(asm, 'asm', 3), [2]); + assert.deepEqual(relateAsmMojo(asm, 'asm', 4), [], 'an instruction the compiler added belongs to no line'); + assert.deepEqual(relateAsmMojo(asm, 'mojo', 2), [2, 3]); + assert.deepEqual(relateAsmMojo(asm, 'mojo', 9), []); + assert.equal(asmMojoLines(' mov rax, 7 ; a constant\n ret').size, 0, 'hand-written x86-64 is not linked'); + // a real listing, as Open in Hardware makes it from godbolt's saved answer + const ROOT = new URL('..', import.meta.url).pathname; + let checked = 0; + for (const f of fs.readdirSync(ROOT + 'core/library/mojo/probes').filter((x) => x.endsWith('.mojo'))) { + const text = fs.readFileSync(ROOT + 'core/library/mojo/probes/' + f, 'utf8'); + if (!/^# mode: (asm|both)/m.test(text)) continue; + const r = buildListing(text, ROOT + 'core/library/mojo/golden', { forSimulator, simulatorSetup, listingFunctions, mojoBuildArgs }); + if (r.why) continue; + const table = asmMojoLines(r.asm); + if (!table.size) continue; + checked++; + const mojoLines = stripHeader(text).source.split('\n'); + for (const [a, m] of table) { + assert.ok(m >= 1 && m <= mojoLines.length, `${f}: x86-64 line ${a} points at Mojo line ${m}, inside the program`); + assert.ok(relateAsmMojo(r.asm, 'mojo', m).includes(a), `${f}: and back`); + } + } + assert.ok(checked >= 1, 'a committed listing carries a line table'); +}); + +test('Open in Hardware on a compiled function: the work it makes can be shared, whatever data the function brings', async () => { + // a function sent to the x86-64 pane brings the read-only data its code addresses in the setup; with the compiler's + // half-megabyte table of source locations that was 2.5 MB for three of demo's functions, and the link the app + // wrote for such work was one it refused to open (core writes a long block as quoted text now) + const { encodeState, decodeState, LIMITS } = await import('../dist/core/state.js'); + const ROOT = new URL('..', import.meta.url).pathname; + const status = JSON.parse(fs.readFileSync(ROOT + 'core/library/mojo/golden/status.json', 'utf8')); + const golden = JSON.parse(fs.readFileSync(`${ROOT}core/library/mojo/golden/${status.items.find((x) => x.id === 'local/demo').key}.json`, 'utf8')); + const fns = listingFunctions(golden.result.asm); + for (const name of ['cell', 'Grid::__init__', 'align', 'main']) { + const fn = fns.find((f) => f.kind === 'user' && f.name.startsWith(name)); + assert.ok(fn, `demo has no function ${name}`); + const s = new Session(stateForProblem(PROBLEMS.find((p) => p.id === 'demo')), { area: 'hw', storageId: null }); + const { source, data } = forSimulator(fns, fn); + s.setSource('asm', source); s.setSetup(simulatorSetup(fn, data)); s.setLang('asm'); + assert.ok(s.trace().count >= 1, `${name} does not step`); + const size = JSON.stringify(s.state).length; + assert.ok(size < LIMITS.stateBytes / 2, `${name}: a state of ${size} bytes, against the ${LIMITS.stateBytes} a link may unpack to`); + const back = await decodeState(await encodeState(s.state)); + assert.equal(back.setup, s.state.setup, `${name}: the setup does not come back from its own link`); + assert.equal(back.sources.asm, s.state.sources.asm); + } +}); diff --git a/tests/inputnote.test.mjs b/tests/inputnote.test.mjs new file mode 100644 index 0000000..e5b29e6 --- /dev/null +++ b/tests/inputnote.test.mjs @@ -0,0 +1,71 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// Mojo 1.2.0's input() and a pipe (the plan's gate G5): the Compiler view says why the compiler's run may stop with +// EOF where the Run view does not, exactly when a program that may call input() more than once was sent with input. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { inputReads, inputNote } from '../dist/core/inputnote.js'; +import { installDocument } from '../dist/quarto/dom.js'; + +const prog = (body) => `def main():\n${body.split('\n').map((l) => ' ' + l).join('\n')}\n`; + +test('one input() call in main reads input once: no note', () => { + assert.deepEqual(inputReads(prog('var s = input()\nprint(s)')), { lines: [2], why: null }); + assert.equal(inputNote(prog('var s = input()\nprint(s)'), '1\n2\n'), null); +}); + +test('two call sites, a loop, a comprehension, or a helper function may read more than once', () => { + assert.equal(inputReads(prog('var a = input()\nvar b = input()\nprint(a + b)')).why, 'several'); + assert.deepEqual(inputReads(prog('var a = input()\nvar b = input()')).lines, [2, 3]); + assert.equal(inputReads(prog('for i in range(3):\n print(input())')).why, 'loop'); + assert.equal(inputReads(prog('var n = 0\nwhile n < 3:\n if True:\n var s = input()\n n += 1')).why, 'loop'); + assert.equal(inputReads(prog('for i in range(3): print(input())')).why, 'loop', 'a loop on one line'); + assert.equal(inputReads(prog('var xs = [input() for _ in range(3)]')).why, 'loop', 'a comprehension'); + assert.equal(inputReads('def ask() -> String:\n return input()\n\ndef main():\n print(ask())\n').why, 'function'); +}); + +test('strings, comments, methods and a def named input are not calls', () => { + assert.equal(inputReads(prog('print("input() input()") # input()\nvar s = input()')).why, null); + assert.equal(inputReads(prog('var s = String("x")\nprint(s.input())\nvar t = input()')).why, null); + assert.equal(inputReads(prog('"""\ninput()\ninput()\n"""\nvar t = input()')).why, null); + assert.deepEqual(inputReads(prog('print(1)')), { lines: [], why: null }); + // after the loop ends, a single call outside it is once + assert.equal(inputReads('def main():\n for i in range(3):\n print(i)\n var s = input()\n').why, null); +}); + +test('the note: only when input was sent, and it names the lines and the reason', () => { + const two = prog('var a = input()\nvar b = input()'); + assert.equal(inputNote(two, ''), null, 'no input sent: nothing to explain'); + assert.equal(inputNote(two, '\n'), null); + const note = inputNote(two, '3\n4\n'); + assert.match(note, /lines 2 and 3/); + assert.match(note, /first call takes every line/); + assert.match(note, /EOF/); + assert.match(inputNote(prog('for i in range(3):\n print(input())'), '1\n'), /in a loop \(line 3\)/); + assert.equal(inputNote('def main(:\n input(\n', '1\n') === null || typeof inputNote('def main(:\n input(\n', '1\n') === 'string', true, 'text that does not lex still answers'); +}); + +test('the Compiler view shows the note under the output of such a compile, and not for a single read', async () => { + installDocument(); + const { Session } = await import('../dist/core/session.js'); + const { normalize } = await import('../dist/core/state.js'); + const { compilerView } = await import('../dist/ui/views/compiler.js'); + const answer = (stdout, stderr = '') => ({ answer: { compiled: true, buildStderr: '', executed: true, exitCode: stderr ? 1 : 0, stdout, stderr, timedOut: false, asm: [] }, error: null, seconds: 0.1 }); + const draw = async (mojo, input, outcome) => { + const s = new Session(normalize({ v: 3, lang: 'mojo', sources: { mojo }, input }), { area: 'dev', storageId: null }); + await s.compile(async () => outcome); + const root = document.createElement('div'); + const off = compilerView(s, root, { reveal() {}, fix() {}, sendToAsm() {}, compile() {} }); + off(); + return root; + }; + const two = prog('var a = input()\nvar b = input()\nprint(a, b)'); + const shown = await draw(two, '3\n4', answer('', 'Unhandled exception caught during execution: EOF')); + const note = shown.querySelector('.compile-input-note'); + assert.ok(note, 'the note is shown'); + assert.match(note.textContent, /lines 2 and 3/); + const once = await draw(prog('var a = input()\nprint(a)'), '3', answer('3\n')); + assert.equal(once.querySelector('.compile-input-note'), null); + const noInput = await draw(two, '', answer('', 'EOF')); + assert.equal(noInput.querySelector('.compile-input-note'), null); +}); diff --git a/tests/library.test.mjs b/tests/library.test.mjs new file mode 100644 index 0000000..80d28cc --- /dev/null +++ b/tests/library.test.mjs @@ -0,0 +1,59 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// The library page (#/library, src/ui/library.ts) and a library routine opened in the Bridge (src/core/library.ts): +// every routine of core's registry is listed with its checks, and opens as a problem that runs. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { installDocument } from '../dist/quarto/dom.js'; + +installDocument(); +const { parseRoute, routeFor } = await import('../dist/core/state.js'); +const { libraryModules, libraryState, checksOf, tally, LIBRARY_PREFIX } = await import('../dist/core/library.js'); +const { Session } = await import('../dist/core/session.js'); + +test('routes: #/library and #/library/<id>, and a routine opens under the problem id lib:<id>', () => { + assert.deepEqual(parseRoute('#/library'), { kind: 'library' }); + assert.deepEqual(parseRoute('#/library/md.LennardJones'), { kind: 'library', id: 'md.LennardJones' }); + assert.equal(routeFor({ kind: 'library', id: 'md.LennardJones' }), '#/library/md.LennardJones'); + assert.deepEqual(parseRoute('#/bridge/p/lib:md.LennardJones'), { kind: 'problem', area: 'bridge', id: 'lib:md.LennardJones' }); + assert.equal(libraryState('lib:md.NoSuch'), null); + assert.equal(libraryState('count-base'), null); +}); + +test('every routine opens in the Bridge with its pseudo and its first case, and runs to that case\'s result', () => { + let n = 0; + for (const m of libraryModules()) for (const r of m.routines) { + n++; + const st = libraryState(`${LIBRARY_PREFIX}${r.id}`); + assert.equal(st.sources.pseudo, r.source); + assert.equal(st.call, r.cases[0].call); + const session = new Session(st, { area: 'bridge' }); + const tr = session.trace('pseudo'); + assert.equal(tr.error, null, `${r.id}: ${tr.error?.message}`); + assert.equal(tr.output.at(-1), `${r.name} returned ${r.cases[0].result}`, r.id); + // stepping into the routine is the point of opening it: its own lines are in the run + assert.ok(tr.steps.some((s) => s.line > 1 && s.kind !== 'call'), `${r.id}: the run shows none of the routine's lines`); + } + assert.ok(n >= 16); +}); + +test('the page lists every routine with its checks, and each routine\'s page shows its source, cases, references and checks', async () => { + const { libraryView } = await import('../dist/ui/library.js'); + const index = libraryView(); + const text = index.textContent; + for (const m of libraryModules()) { + assert.ok(text.includes(m.title), m.title); + for (const r of m.routines) assert.ok(text.includes(r.name), r.id); + } + const r = libraryModules().find((m) => m.name === 'md').routines.find((x) => x.name === 'LennardJones'); + const page = libraryView(r.id); + const t = page.textContent; + assert.ok(t.includes('Open in the Bridge')); + assert.ok(t.includes(`USE ${r.id}`)); + for (const c of r.cases) assert.ok(t.includes(c.call) && t.includes(c.result), c.call); + for (const ref of r.references) assert.ok(t.includes(`${ref.lang} · ${ref.level}`), `${ref.lang}/${ref.level}`); + assert.equal(page.querySelectorAll('.lib-chip').length >= checksOf(r).length, true); + assert.ok(libraryView('md.NoSuch').textContent.includes('No such routine')); + const t2 = tally(r); + assert.equal(t2.fail, 0); +}); diff --git a/tests/load.test.mjs b/tests/load.test.mjs new file mode 100644 index 0000000..054f0be --- /dev/null +++ b/tests/load.test.mjs @@ -0,0 +1,62 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// What a first visit asks for, and what a browser may keep (docs/deploy.md): the assembled page preloads every module +// its imports reach and names its commit (scripts/assemble-page.mjs), and the Caddy block caches only what may be cached. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { createHash } from 'node:crypto'; +import { fileURLToPath } from 'node:url'; +import { modulePreloads, assemblePage } from '../scripts/assemble-page.mjs'; + +const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url))); +const read = (p) => fs.readFileSync(path.join(ROOT, p), 'utf8'); +const html = read('index.html'); +const inlineHashes = (h) => [...h.matchAll(/<script(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/g)].map((m) => createHash('sha256').update(m[1]).digest('base64')); + +test('the preload list is every module the page imports, each once, and only files that exist', () => { + const list = modulePreloads(ROOT); + assert.ok(list.length > 100, `${list.length} modules`); + assert.equal(new Set(list).size, list.length); + assert.ok(!list.includes('./dist/main.js'), 'the entry loads itself'); + for (const href of ['./dist/ui/shell.js', './dist/vendor/codemirror.js', './core/dist/mojo/interp.js', './dist/ui/footer.js']) assert.ok(list.includes(href), href); + for (const href of list) assert.ok(fs.existsSync(path.join(ROOT, href)), href); + // every import in every listed module is listed too (or is the entry) + const listed = new Set(list.map((h) => path.join(ROOT, h))); + listed.add(path.join(ROOT, 'dist/main.js')); + for (const f of listed) for (const m of fs.readFileSync(f, 'utf8').matchAll(/\bfrom\s*['"](\.[^'"]+|#core\/[^'"]+)['"]/g)) { + const t = m[1].startsWith('#core/') ? path.join(ROOT, 'core/dist', m[1].slice(6)) : path.resolve(path.dirname(f), m[1]); + assert.ok(listed.has(t), `${path.relative(ROOT, f)} imports ${m[1]}, which the list misses`); + } +}); + +test('the assembled page adds the version and the preloads after the import map, and changes no inline script', () => { + const out = assemblePage(html, { version: '0123456789abcdef0123456789abcdef01234567', preloads: ['./dist/a.js', './core/dist/b.js'] }); + assert.match(out, /<meta name="pplus-version" content="0123456789abcdef0123456789abcdef01234567">\n<\/head>/); + const map = out.indexOf('<script type="importmap">'); + const first = out.indexOf('rel="modulepreload"'); + assert.ok(map > 0 && first > map, 'a module preload before the import map would make the browser ignore the map'); + assert.ok(first < out.indexOf('<script type="module"')); + assert.deepEqual(inlineHashes(out), inlineHashes(html), 'the CSP allows the inline scripts by their hashes'); + assert.doesNotMatch(assemblePage(html, { version: 'dev' }), /pplus-version/, 'a checkout without a commit names none'); + assert.match(read('scripts/assemble.sh'), /node scripts\/assemble-page\.mjs site/); +}); + +test('the page asks for its two everyday faces with the stylesheet, and every face swaps in when it arrives', () => { + const pre = [...html.matchAll(/<link rel="preload" href="\.\/fonts\/([^"]+)" as="font" type="font\/woff2" crossorigin>/g)].map((m) => m[1]); + assert.deepEqual(pre, ['IBMPlexSans-Regular.woff2', 'IBMPlexMono-Regular.woff2']); + const css = read('fonts/plex.css'); + const faces = css.match(/@font-face/g).length; + assert.equal(css.match(/font-display: swap/g).length, faces); +}); + +test('the Caddy block caches nothing as immutable, revalidates the page and the code, and keeps the fonts', () => { + const caddy = read('docs/Caddyfile'); + assert.doesNotMatch(caddy, /Cache-Control "[^"]*immutable/, 'no file name here changes with its content'); + assert.match(caddy, /@page path \/ \/index\.html\n\s*header @page Cache-Control "no-cache"/); + assert.match(caddy, /@code path \*\.js \*\.css\n\s*header @code Cache-Control "no-cache"/); + assert.match(caddy, /@fonts path \/fonts\/\*\.woff2\n\s*header @fonts Cache-Control "public, max-age=\d+"/); + assert.match(caddy, /header \/VERSION Cache-Control "no-store"/); + assert.doesNotMatch(read('src/main.ts') + html, /serviceWorker/, 'no service worker (offline reload is a later decision)'); +}); diff --git a/tests/mojo.test.mjs b/tests/mojo.test.mjs new file mode 100644 index 0000000..961ec53 --- /dev/null +++ b/tests/mojo.test.mjs @@ -0,0 +1,118 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { normalize } from '../dist/core/state.js'; + +import { Session } from '../dist/core/session.js'; +import { MOJO_VERSION, GODBOLT_COMPILER } from '../core/dist/mojo/generated/pin.js'; + +// godbolt's stored answers, in pplus-core +const goldens = fs.readdirSync(new URL('../core/library/mojo/golden/', import.meta.url)).filter((f) => /^[0-9a-f]{64}\.json$/.test(f)) + .map((f) => JSON.parse(fs.readFileSync(new URL(`../core/library/mojo/golden/${f}`, import.meta.url), 'utf8'))); + +test('the session keeps each answer with the source it answered, and says when it is stale', async () => { + const s = new Session(normalize({ v: 3, lang: 'mojo', sources: { mojo: 'fn main():\n print(1)\n' } })); + assert.equal(s.diagnostics('mojo')[0].id, 'removed-syntax'); + const stderr = goldens.find((g) => g.firstItem === 'probes/dialect-fn').result.buildStderr; + let asked = null; + const fake = async (source, opts) => { asked = { source, ...opts }; return { answer: { compiled: false, buildStderr: stderr.replace('<source>:3:', '<source>:1:'), executed: false, exitCode: null, stdout: '', stderr: '', timedOut: false, asm: [] }, error: null, seconds: 0.1 }; }; + const rec = await s.compile(fake); + assert.equal(asked.level, 'O0'); + assert.equal(rec.diagnostics[0].origin, `the Mojo ${MOJO_VERSION} compiler`); + assert.equal(s.diagnostics('mojo')[0].id, 'compiler', 'the compiler\'s answer replaces Programming+\'s own finding'); + assert.equal(s.lastCompile().fresh, true); + s.setSource('mojo', 'def main():\n print(1)\n'); + assert.equal(s.lastCompile().fresh, false); + assert.deepEqual(s.diagnostics('mojo'), [], 'an answer for older source is not shown on the new lines'); + const failed = await s.compile(async () => ({ answer: null, error: 'Could not reach godbolt.org (offline).', seconds: 0 })); + assert.equal(failed.outcome.error, 'Could not reach godbolt.org (offline).'); +}); + +test('Compile & run goes through the compile backend, and the record names the service that answered', async () => { + const { compileBackend, setCompileBackend, explorerBackend, GODBOLT } = await import('../core/dist/services/compile-backend.js'); + assert.equal(compileBackend(), GODBOLT); + assert.equal(GODBOLT.host, 'godbolt.org'); + assert.equal(GODBOLT.compiler, GODBOLT_COMPILER); + const asked = []; + const fake = { id: 'fake', host: 'checker.example', compiler: GODBOLT_COMPILER, compile: async (source, opts) => { asked.push({ source, ...opts }); return { answer: null, error: 'checker.example did not answer in time.', seconds: 0 }; } }; + const prev = setCompileBackend(fake); + try { + const s = new Session(normalize({ v: 3, lang: 'mojo', sources: { mojo: 'def main():\n print(7)\n' } })); + const rec = await s.compile(); + assert.equal(asked.length, 1); + assert.equal(asked[0].source, 'def main():\n print(7)\n'); + assert.equal(asked[0].level, 'O0'); + assert.equal(rec.host, 'checker.example'); + } finally { + setCompileBackend(prev); + } + assert.equal(compileBackend(), GODBOLT); + // a Compiler Explorer at another address speaks the same API and names itself in its messages + const elsewhere = explorerBackend('local', { base: 'http://127.0.0.1:9', compiler: GODBOLT_COMPILER, host: 'the local checker' }); + const out = await elsewhere.compile('def main():\n pass\n', { timeoutMs: 2000 }); + assert.equal(out.answer, null); + assert.match(out.error, /the local checker/); +}); + +test('godbolt\'s answer outlives the session: a new one for the same source finds it without asking again', async () => { + const { forgetCompiles } = await import('../dist/core/compiles.js'); + forgetCompiles(); + const src = 'def main():\n print(42)\n'; + const answer = { compiled: true, buildStderr: '', executed: true, exitCode: 0, stdout: '42\n', stderr: '', timedOut: false, asm: [{ text: '"example::main()":' }, { text: ' retq' }] }; + let asks = 0; + const first = new Session(normalize({ v: 3, lang: 'mojo', sources: { mojo: src } })); + await first.compile(async () => { asks++; return { answer, error: null, seconds: 0.1 }; }); + // a change of problem, a reload: a new session for the same program + const again = new Session(normalize({ v: 3, lang: 'mojo', sources: { mojo: src } })); + const last = again.lastCompile(); + assert.ok(last, 'the answer is there before anyone presses Compile'); + assert.equal(last.fresh, true); + assert.equal(last.record.outcome.answer.stdout, '42\n'); + assert.equal(last.record.functions.length, 1, 'the listing is split into functions again'); + assert.equal(asks, 1); + // a different program does not see it, and comes back to it once the source is the same again + const other = new Session(normalize({ v: 3, lang: 'mojo', sources: { mojo: 'def main():\n print(7)\n' } })); + assert.equal(other.lastCompile(), null); + other.setSource('mojo', src); + assert.equal(other.lastCompile()?.fresh, true, 'editing back to a compiled source brings its answer back'); + // a failure to reach godbolt is not kept + forgetCompiles(); + const offline = new Session(normalize({ v: 3, lang: 'mojo', sources: { mojo: src } })); + await offline.compile(async () => ({ answer: null, error: 'offline', seconds: 0 })); + assert.equal(new Session(normalize({ v: 3, lang: 'mojo', sources: { mojo: src } })).lastCompile(), null); + forgetCompiles(); +}); + +test('Stage 6b: comparing builds does not replace the build the student chose', async () => { + const { Session } = await import('../dist/core/session.js'); + const { normalize } = await import('../dist/core/state.js'); + const s = new Session(normalize({ v: 3, sources: { mojo: 'def main():\n print(1)\n' }, lang: 'mojo' })); + const fake = (level) => async () => ({ ok: true, answer: { compiled: true, executed: true, exitCode: 0, stdout: level, stderr: '', buildStderr: '', asm: [] } }); + await s.compile(fake('O0')); + await s.compile(fake('default'), 'default'); + assert.equal(s.lastCompile().record.level, 'O0', 'the view keeps the chosen level'); + assert.ok(s.compileAt(s.source('mojo'), 'default'), 'the other build is there to compare with'); +}); + +test('a compile says how it was built: the arguments the request sent, from core\'s pin', async () => { + const { MOJO_BUILD_ARGS } = await import('../core/dist/mojo/generated/pin.js'); + const { BUILD_ARGS } = await import('../core/dist/services/godbolt.js'); + assert.match(MOJO_BUILD_ARGS, /--target-cpu \S+ --fp-mode contract=off/); + for (const level of ['O0', 'default']) assert.ok(BUILD_ARGS[level].startsWith(MOJO_BUILD_ARGS), `${level} is asked for with the pin's arguments first`); + // the summary line of a compile and the badge's tooltip show them, and neither names arguments of its own + const fs = await import('node:fs'); + for (const f of ['src/ui/views/compiler.ts', 'src/ui/provenance.ts']) { + const text = fs.readFileSync(f, 'utf8'); + assert.ok(text.includes('MOJO_BUILD_ARGS'), `${f} shows the pin's arguments`); + assert.doesNotMatch(text, /--target-cpu|--fp-mode/, `${f} writes build arguments of its own`); + } + // the two places the site's own tools run a Mojo file (a Quarto page's run, and the page checker) build it the same way + for (const f of ['quarto/_extensions/pplus/render.mjs', 'scripts/check-pages.mjs']) { + const text = fs.readFileSync(f, 'utf8'); + assert.ok(text.includes('mojoBuildArgs('), `${f} takes the pin's arguments`); + assert.doesNotMatch(text, /\['run', file\]/, `${f} runs mojo with no build arguments`); + assert.doesNotMatch(text, /--target-cpu|--fp-mode/, `${f} writes build arguments of its own`); + } +}); diff --git a/tests/narrow.test.mjs b/tests/narrow.test.mjs new file mode 100644 index 0000000..642ca42 --- /dev/null +++ b/tests/narrow.test.mjs @@ -0,0 +1,37 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// A phone-width screen shows one part of a workspace at a time (styles.css, src/ui/shell.ts setNarrow); a wider one +// must not see any of it: AGENTS.md rule 7 keeps the workspace's parts where they are on a normal screen. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; + +const css = readFileSync(new URL('../styles.css', import.meta.url), 'utf8').replace(/\/\*[\s\S]*?\*\//g, ''); + +/** The top-level blocks of a stylesheet: [prelude, body] pairs. */ +function blocks(text) { + const out = []; let depth = 0, start = 0, prelude = ''; + for (let i = 0; i < text.length; i++) { + if (text[i] === '{') { if (depth === 0) { prelude = text.slice(start, i).trim(); start = i + 1; } depth++; } + else if (text[i] === '}') { depth--; if (depth === 0) { out.push([prelude, text.slice(start, i)]); start = i + 1; } } + } + return out; +} + +test('every narrow-screen rule is inside the 700px media query, and the bar is hidden outside it', () => { + const top = blocks(css); + const outside = top.filter(([p]) => !p.startsWith('@media')).map(([p, b]) => `${p}{${b}}`); + assert.ok(outside.some((r) => /^\.narrow-bar\{\s*display: none;\s*\}$/.test(r.replace(/\s*\{\s*/, '{').trim())), '.narrow-bar is display: none on a normal screen'); + for (const r of outside) assert.doesNotMatch(r, /data-narrow/, `a rule outside the media query reads data-narrow: ${r.slice(0, 80)}`); + for (const [p, b] of top.filter(([p]) => p.startsWith('@media') && !/max-width: 700px/.test(p))) assert.doesNotMatch(b, /data-narrow|narrow-bar/, `${p} reads the narrow layout`); + const narrow = top.filter(([p]) => /^@media \(max-width: 700px\)$/.test(p)).map(([, b]) => b).join('\n'); + for (const part of ['code', 'side', 'dock']) assert.match(narrow, new RegExp(`data-narrow="${part}"`), part); +}); + +test('the shell offers the parts, and Run, Compile & run and a diagnostic\'s line show the part they open', () => { + const shell = readFileSync(new URL('../src/ui/shell.ts', import.meta.url), 'utf8'); + assert.match(shell, /\[\['code', 'Code'\], \['side', 'Board'\]\] : \[\['code', 'Code'\], \['side', 'Run and views'\], \['dock', 'Setup and output'\]\]/); + assert.match(shell, /this\.stepper\?\.goto\(this\.session\.trace\(\)\?\.count \?\? 0\); this\.setNarrow\('side'\);/, 'Run shows the Run view'); + assert.match(shell, /if \(open\) this\.setNarrow\('dock'\);/, 'opening the dock (Compile & run) shows it'); + assert.match(shell, /reveal: \(lang, line\) => \{\n\s*this\.setNarrow\('code'\);/, 'a line in the code shows the code'); +}); diff --git a/tests/practices-switch.test.mjs b/tests/practices-switch.test.mjs new file mode 100644 index 0000000..cf251a1 --- /dev/null +++ b/tests/practices-switch.test.mjs @@ -0,0 +1,85 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// Stage 13b: the best-practices switch. Off by default, one per area, remembered in the browser and nowhere else; +// while it is off the rules are never called (a spy proves it), and nothing about them reaches a diagnostic. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { Session } from '../dist/core/session.js'; +import { stateForProblem, problemById } from '../dist/core/catalog.js'; +import { practicesOn, setPracticesOn, forgetPractices, onPracticesChange } from '../dist/core/prefs.js'; +import { findPractices, PRACTICES_ORIGIN } from '../core/dist/mojo/practices.js'; +import { encodeState } from '../dist/core/state.js'; + +const store = new Map(); +globalThis.localStorage = { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, String(v)), removeItem: (k) => store.delete(k) }; +const spy = () => { const f = (...a) => { f.calls++; return findPractices(...a); }; f.calls = 0; return f; }; +const open = (id, area, practices) => new Session(stateForProblem(problemById(id)), { area, storageId: null, practices }); +const noted = (s) => s.allDiagnostics().filter((d) => d.origin === PRACTICES_ORIGIN); + +test('off by default in every area, and the rules are never called while off', () => { + forgetPractices(); + for (const area of ['bridge', 'dev', 'hw', null]) assert.equal(practicesOn(area), false, String(area)); + for (const area of ['bridge', 'dev', 'hw']) { + const f = spy(); + const s = open('count-base', area, f); + s.setLang('mojo'); + s.allDiagnostics(); s.diagnostics('mojo'); s.practices(); s.trace(); + assert.equal(f.calls, 0, `${area}: no rule ran`); + assert.deepEqual(s.practices(), []); + assert.deepEqual(noted(s), []); + } +}); + +test('the switch is per area, remembered under its own key, and a fresh read finds it', () => { + forgetPractices(); + setPracticesOn('dev', true); + assert.equal(store.get('pplus.practices.dev'), '1'); + assert.equal(practicesOn('dev'), true); + assert.equal(practicesOn('bridge'), false, 'the other area is unaffected'); + assert.equal(practicesOn('hw'), false, 'Hardware has no switch'); + setPracticesOn('hw', true); + assert.equal(practicesOn('hw'), false); + let told = 0; const off = onPracticesChange(() => told++); + setPracticesOn('bridge', true); setPracticesOn('bridge', false); + off(); setPracticesOn('bridge', true); + assert.equal(told, 2); + setPracticesOn('bridge', false); setPracticesOn('dev', false); + assert.ok(!store.has('pplus.practices.dev') && !store.has('pplus.practices.bridge'), 'off is stored as absent'); +}); + +test('on in the Developer area: findings are notes on the student\'s own lines; the Bridge, still off, stays quiet', () => { + forgetPractices(); + setPracticesOn('dev', true); + const f = spy(); + const dev = open('count-base', 'dev', f); + dev.setSource('mojo', 'def main():\n var n: Int\n n = 5\n n = n + 1\n print(n)\n'); + const notes = noted(dev); + assert.ok(f.calls >= 1); + assert.deepEqual(notes.map((d) => d.id).sort(), ['practice-augmented-assign', 'practice-declare-then-assign']); + assert.ok(notes.every((d) => d.severity === 'note' && d.fix && d.lang === 'mojo')); + const g = spy(); + const bridge = open('count-base', 'bridge', g); + bridge.allDiagnostics(); bridge.practices(); + assert.equal(g.calls, 0); + forgetPractices(); +}); + +test('on in the Bridge: the generated Mojo draws findings in the helper\'s list, not in Problems', () => { + forgetPractices(); + setPracticesOn('bridge', true); + const s = open('count-base', 'bridge'); + const rules = new Set(s.practices().map((x) => x.rule)); + for (const id of ['declare-then-assign', 'augmented-assign', 'codepoint-loop']) assert.ok(rules.has(id), id); + assert.deepEqual(noted(s), [], 'Problems stays about the pseudo and the translation'); + assert.equal(s.source('mojo'), s.derivedMojo().source, 'the Mojo is still the literal translation'); + forgetPractices(); +}); + +test('the switch is a browser preference: it is not in the state, so a link cannot turn it on', async () => { + forgetPractices(); + setPracticesOn('dev', true); + const st = stateForProblem(problemById('count-base')); + assert.ok(!/practices/i.test(JSON.stringify(st))); + assert.ok(!/practices/i.test(await encodeState(st))); + forgetPractices(); +}); diff --git a/tests/quarto-gallery.test.mjs b/tests/quarto-gallery.test.mjs new file mode 100644 index 0000000..cee3852 --- /dev/null +++ b/tests/quarto-gallery.test.mjs @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// The app's "With Quarto" page (#/quarto, src/ui/quarto.ts): its samples must show what a page gets from the +// extension, and every program in it must run as its header says. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { installDocument } from '../dist/quarto/dom.js'; +import { langOfFile } from '../dist/quarto/program.js'; + +installDocument(); +const { renderStatic } = await import('../dist/quarto/render.js'); +const { parseRoute, routeFor } = await import('../dist/core/state.js'); + +test('the gallery\'s samples render as a page would get them, and every run in it prints what its file says', async () => { + const { galleryFiles, SAMPLES } = await import('../dist/ui/quarto.js'); + const { SHORTCODES, requestFor, liveStateFor, shortcodeText } = await import('../dist/quarto/shortcodes.js'); + const files = galleryFiles(); + const named = new Set(SAMPLES.map((s) => s.name)); + // every shortcode has a card; the machine's one-view shortcodes share a card with a menu of them all + for (const d of SHORTCODES) assert.ok(named.has(d.name) || (d.kind === 'machine' && d.hw && SAMPLES.some((x) => x.explore)), `the gallery shows ${d.name}`); + for (const s of SAMPLES) { + for (const [k, v] of Object.entries(s.attrs)) if (['lingo', 'matho', 'pseudo', 'speco', 'mojo', 'asm', 'setup'].includes(k)) assert.ok(files[v] !== undefined, `${s.name} names ${v}`); + assert.match(shortcodeText(s.name, s.attrs), new RegExp(`^\\{\\{< ${s.name} .* >\\}\\}$`)); + const def = SHORTCODES.find((d) => d.name === s.name); + if (def.kind === 'live') { assert.ok(Object.keys(liveStateFor(s.attrs, files).sources).length, s.name); continue; } + if (def.kind !== 'rendered' && def.kind !== 'machine') continue; + const view = def.view ?? (s.attrs.view === 'dataflow' ? 'data' : s.attrs.view); + const req = requestFor(view, s.attrs, files); + if (def.hw) req.hw = [def.hw]; + const r = renderStatic(req); + assert.deepEqual(r.warnings, [], `${s.name} ${JSON.stringify(s.attrs)}`); + if (r.expect) assert.ok(r.expect.ok, `${s.name}: ${JSON.stringify(r.expect)}`); + } + // the files' own headers hold: each run prints its EXPECT lines, each stop is the one it names + for (const [name, text] of Object.entries(files)) { + const lang = langOfFile(name); + if (!lang || lang === 'speco' || lang === 'asm') continue; + const r = renderStatic({ view: 'run', files: { [lang]: text } }); + if (r.expect) assert.ok(r.expect.ok, `${name}: ${JSON.stringify(r.expect)}`); + } +}); + +test('#/quarto is the gallery, and its sections are links', () => { + assert.deepEqual(parseRoute('#/quarto'), { kind: 'quarto' }); + assert.deepEqual(parseRoute('#/quarto#pplus-steps'), { kind: 'quarto', anchor: 'pplus-steps' }); + assert.equal(routeFor({ kind: 'quarto', anchor: 'setup' }), '#/quarto#setup'); + assert.deepEqual(parseRoute('#/quarto/x'), { kind: 'home' }); +}); diff --git a/tests/quarto-render.test.mjs b/tests/quarto-render.test.mjs new file mode 100644 index 0000000..cff3d81 --- /dev/null +++ b/tests/quarto-render.test.mjs @@ -0,0 +1,222 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// The rendered views of the Quarto extension (src/quarto/): a program from the files beside a page, run by the app's +// engines and drawn by its views as HTML, under the small document of src/quarto/dom.ts; the CLI pplus.lua calls +// (quarto/_extensions/pplus/render.mjs). The gallery that shows them in the app is tests/quarto-gallery.test.mjs. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { spawnSync } from 'node:child_process'; +import zlib from 'node:zlib'; +import { installDocument, SDocument } from '../dist/quarto/dom.js'; +import { programHeader, listingText, langOfFile } from '../dist/quarto/program.js'; + +installDocument(); +const { renderStatic, STATIC_VIEWS, stepsPanel } = await import('../dist/quarto/render.js'); +const { problemById } = await import('../dist/core/catalog.js'); + +const ROOT = new URL('..', import.meta.url).pathname; +const CB = problemById('count-base'); +const head = (call, expect) => `// CALL: ${call}\n${expect ? `// EXPECT: ${expect}\n` : ''}`; +const PSEUDO = head(CB.call, 'COUNT_BASE returned 3') + CB.sources.pseudo; + +test('a program file: its pane, its header lines, and the text a page shows', () => { + assert.equal(langOfFile('x/count.pseudo'), 'pseudo'); + assert.equal(langOfFile('mean.tex'), 'matho'); + assert.equal(langOfFile('demo.mojo'), 'mojo'); + assert.equal(langOfFile('notes.txt'), null); + const h = programHeader('// CALL: F(1)\n// INPUT: 4\n// INPUT: 5\n// EXPECT: F returned 2\n// STOPS: index\nFUNCTION F...'); + assert.deepEqual(h, { call: 'F(1)', input: ['4', '5'], expect: ['F returned 2'], stops: 'index', questions: [] }); + assert.deepEqual(programHeader('% CALL: X(1)\n% EXPECT: X returned 1\n').expect, ['X returned 1']); + assert.deepEqual(programHeader('# expect-stdout: 3\n# expect-stdout: 4\ndef main():\n pass\n').expect, ['3', '4'], 'a Mojo file\'s corpus header counts as EXPECT'); + assert.equal(listingText('// CALL: F(1)\n\nFUNCTION F()\n', 'pseudo'), 'FUNCTION F()'); + assert.equal(listingText('# origin: x\n# expect-stdout: 1\n\ndef main():\n # note: mine\n print(1)\n', 'mojo'), 'def main():\n # note: mine\n print(1)'); +}); + +test('the small document builds, finds and writes what the views make', () => { + const doc = new SDocument(); + const div = doc.createElement('div'); + div.className = 'a b'; + div.classList.add('c'); div.classList.toggle('a'); + div.style.left = '10%'; div.style.setProperty('--x', '1'); + div.dataset.stepNo = '4'; + const svg = doc.createElementNS('http://www.w3.org/2000/svg', 'svg'); + svg.setAttribute('viewBox', '0 0 1 1'); + svg.appendChild(doc.createElementNS('http://www.w3.org/2000/svg', 'path')); + const p = doc.createElement('p'); p.textContent = 'x < y & "z"'; + const sel = doc.createElement('select'); + for (const v of ['one', 'two']) { const o = doc.createElement('option'); o.value = v; o.textContent = v; sel.appendChild(o); } + sel.value = 'two'; + const details = doc.createElement('details'); details.open = true; + div.append(svg, p, sel, details); + assert.equal(div.outerHTML, '<div class="b c" style="left: 10%; --x: 1" data-step-no="4"><svg viewBox="0 0 1 1"><path/></svg><p>x < y & "z"</p><select><option value="one" selected="">one</option><option value="two" selected>two</option></select><details open></details></div>'.replace(' selected=""', '')); + assert.equal(div.querySelectorAll('svg path').length, 1, 'the descendant combinator'); + assert.equal(div.querySelector('[data-step-no="4"]'), null, 'the root itself is not searched'); + assert.equal(div.querySelectorAll('.b, p').length, 1); + assert.equal(p.closest('.c'), div); + assert.throws(() => div.querySelector('div > p'), /only the descendant combinator/); + p.replaceWith(doc.createTextNode('gone')); + assert.equal(div.textContent.includes('gone'), true); +}); + +test('run: what the program prints, checked against its EXPECT lines, for each notation', () => { + const r = renderStatic({ view: 'run', files: { pseudo: PSEUDO } }); + assert.equal(r.lang, 'pseudo'); + assert.deepEqual(r.expect, { want: ['COUNT_BASE returned 3'], got: ['COUNT_BASE returned 3'], ok: true }); + assert.match(r.html, /prints the 1 line its EXPECT header says/); + assert.match(r.markdown, /```\nCOUNT_BASE returned 3\n```/); + const wrong = renderStatic({ view: 'run', files: { pseudo: PSEUDO.replace('returned 3', 'returned 9') } }); + assert.equal(wrong.expect.ok, false); + assert.match(wrong.warnings.join('\n'), /its EXPECT lines say \["COUNT_BASE returned 9"\]/); + const lingo = renderStatic({ view: 'run', files: { lingo: CB.sources.lingo }, call: 'COUNT_BASES(\'A\', "GATTACA")' }); + assert.deepEqual(lingo.expect, undefined); + assert.match(lingo.html, /COUNT_BASES returned 3/); + const mojo = renderStatic({ view: 'run', files: { mojo: '# EXPECT: 3\n' + CB.sources.mojo } }); + assert.equal(mojo.lang, 'mojo'); + assert.ok(mojo.expect.ok); + assert.match(mojo.html, /not the compiler/, 'the interpreter says it is not the compiler'); + const compiled = renderStatic({ view: 'run', files: { mojo: CB.sources.mojo }, compiled: { stdout: '3\n', stderr: '', status: 0, version: 'Mojo 9.9.9' } }); + // whatever version the rendering machine's compiler reports is what the view says + assert.match(compiled.html, /Mojo 9\.9\.9, on the machine that rendered this page/); + const broken = renderStatic({ view: 'run', files: { pseudo: 'FUNCTION F() RETURNS INTEGER\n RETURN Nope\nENDFUNCTION\n' } }); + assert.match(broken.html, /pplus-err/); + assert.ok(broken.warnings.length); +}); + +test('steps: one row per step of the run, the values after it, and the page drawn at the step asked for', () => { + const r = renderStatic({ view: 'steps', files: { pseudo: PSEUDO }, t: 5 }); + const json = /<script type="application\/json" class="pplus-steps-data">([^<]*)<\/script>/.exec(r.html)[1]; + const data = JSON.parse(json); + assert.equal(data.lang, 'pseudo'); + assert.equal(data.rows.length, data.count); + assert.equal(data.t, 5); + assert.deepEqual(data.cols.map((c) => c.label), ['B', 'T', 'N', 'Total', 'I']); + const at = stepsPanel(data, 5); + assert.match(r.html, new RegExp(`class="pplus-ln is-next" data-line="${at.next}"`)); + assert.equal(stepsPanel(data, data.count).out.join('\n'), 'COUNT_BASE returned 3'); + assert.equal(stepsPanel(data, 0).now, 'Before the first step.'); + const asm = renderStatic({ view: 'steps', files: { asm: problemById('asm-two-pointers').sources.asm }, setup: problemById('asm-two-pointers').setup, max: 20 }); + const ad = JSON.parse(/class="pplus-steps-data">([^<]*)</.exec(asm.html)[1]); + assert.equal(ad.lang, 'asm'); + assert.equal(ad.count, 20); + assert.ok(ad.truncated); + assert.ok(ad.cols.length && ad.cols.every((c) => /^r[a-z0-9]+$/.test(c.label)), 'a column per register the run writes'); + const follow = renderStatic({ view: 'steps', files: { pseudo: PSEUDO }, follow: ['total'] }); + assert.deepEqual(JSON.parse(/class="pplus-steps-data">([^<]*)</.exec(follow.html)[1]).cols.map((c) => c.label), ['Total']); +}); + +test('every rendered view draws for a program that has what it needs, with the app\'s controls taken out', () => { + const files = { pseudo: PSEUDO, speco: problemById('count-base-proved').sources.speco }; + for (const view of ['table', 'flow', 'data', 'proof', 'tests', 'check']) { + const r = renderStatic({ view, files }); + assert.match(r.html, new RegExp(`^<div class="[^"]*pplus-static pplus-v-${view}`), view); + assert.doesNotMatch(r.html, /<button|<input|<select/, `${view} keeps no control the page cannot use`); + assert.ok(r.markdown.length > 10, `${view} has a Markdown form`); + } + assert.match(renderStatic({ view: 'flow', files }).html, /<svg[^>]*class="flow-svg"/); + assert.match(renderStatic({ view: 'proof', files }).html, /4 proved/); + const check = renderStatic({ view: 'check', files: { pseudo: problemById('five-bugs').sources.pseudo } }); + assert.match(check.html, /problem-error/); + assert.match(check.markdown, /\*\*error\*\*, pseudo line \d+: /); + const tests = renderStatic({ view: 'tests', files: { pseudo: problemById('match-off-by-one').sources.pseudo } }); + assert.match(tests.html, /way of failing/); + const machine = renderStatic({ view: 'machine', files: { asm: problemById('asm-two-pointers').sources.asm }, setup: problemById('asm-two-pointers').setup }); + assert.match(machine.markdown, /\| instructions \| \d+ \|/); + const life = renderStatic({ view: 'life', files: { mojo: fs.readFileSync(ROOT + 'core/library/mojo/stress/lifecycle-moves.mojo', 'utf8') } }); + assert.ok((life.html.match(/life-row/g) ?? []).length >= 3); + assert.doesNotMatch(life.html, /Click a mark/, 'a page has no stepper to move'); + assert.equal(STATIC_VIEWS.length, 12); +}); + +test('translate: one file in, every notation out, Mojo labeled as generated', () => { + const r = renderStatic({ view: 'translate', files: { matho: '% CALL: X_BAR(3, [1.0, 2.0, 6.0])\n\\bar{x} = \\frac{1}{n} \\sum_{i=0}^{n-1} x_i\n' } }); + assert.deepEqual(r.panes.map((p) => [p.lang, p.authored, p.generated]), [['matho', true, false], ['lingo', false, true], ['pseudo', false, true], ['mojo', false, true]]); + assert.equal(r.panes.find((p) => p.lang === 'lingo').from, 'matho'); + assert.match(r.panes.find((p) => p.lang === 'mojo').text, /def x_bar/); + const only = renderStatic({ view: 'translate', files: { lingo: CB.sources.lingo }, to: ['pseudo', 'mojo'] }); + assert.deepEqual(only.panes.map((p) => p.lang), ['pseudo', 'mojo']); + const cannot = renderStatic({ view: 'translate', files: { pseudo: PSEUDO }, to: ['matho'] }); + assert.equal(cannot.panes[0].text, ''); + assert.ok(cannot.panes[0].note, 'a notation that cannot say it says why'); +}); + +test('render.mjs answers a request from pplus.lua, and keeps the answer in its cache', () => { + const cache = fs.mkdtempSync(path.join(os.tmpdir(), 'pplus-cache-')); + const ask = (req) => { + const r = spawnSync(process.execPath, [ROOT + 'quarto/_extensions/pplus/render.mjs', ROOT], { input: JSON.stringify(req), encoding: 'utf8', env: { ...process.env, PATH: '/nonexistent' } }); + assert.equal(r.status, 0, r.stderr); + return JSON.parse(r.stdout); + }; + const a = ask({ view: 'run', files: { pseudo: PSEUDO }, cache }); + assert.equal(a.expect.ok, true); + assert.equal(a.node, undefined, 'the element stays behind; its HTML goes'); + assert.equal(fs.readdirSync(cache).length, 1); + const b = ask({ view: 'run', files: { pseudo: PSEUDO }, cache }); + assert.deepEqual(b, a, 'the same answer, from the cache'); + assert.match(ask({ view: 'nonsense', files: { pseudo: PSEUDO } }).error, /unknown view "nonsense"/); + const big = ask({ view: 'tests', files: { pseudo: PSEUDO } }); + assert.ok(big.html.length > 65536 && big.html.endsWith('</div>'), `a large answer (${big.html.length} characters) arrives whole through the pipe`); + const none = spawnSync(process.execPath, [ROOT + 'quarto/_extensions/pplus/render.mjs', os.tmpdir()], { input: '{}', encoding: 'utf8' }); + assert.match(JSON.parse(none.stdout).error, /no built Programming\+/); + // a Mojo run asks for the compiler only when one is on the PATH; compiler="on" insists on it + const mojo = ask({ view: 'run', files: { mojo: CB.sources.mojo }, compiler: 'on' }); + assert.match(mojo.error, /no `mojo` on the PATH/); +}); + +test('the machine board: every card of the Hardware area, drawn at each step, the drawings shared between steps', async () => { + const { HW_NAMES, HW_PRESETS, hwView } = await import('../dist/quarto/machine.js'); + const p = problemById('asm-two-pointers'); + const files = { asm: p.sources.asm }; + const board = renderStatic({ view: 'hw', files, setup: p.setup, t: 9 }); + assert.deepEqual(board.warnings, []); + const data = JSON.parse(/class="pplus-hw-data">([^<]*)</.exec(board.html)[1]); + assert.equal(data.count, 97); + assert.equal(data.shown.length, 98, 'every step of a short run'); + assert.deepEqual(data.cards.map((c) => c.id), HW_PRESETS[0].views); + for (const c of data.cards) { + assert.equal(c.at.length, data.shown.length); + assert.ok(c.frames.length <= data.shown.length && c.at.every((i) => i < c.frames.length)); + } + assert.ok(data.cards.find((c) => c.id === 'stack').frames.length < 5, 'a card that does not change is drawn once'); + assert.equal(data.steps[9].x, 'mov r11, qword ptr [rdx + r9*8]'); + // every view of the machine draws on this run without failing, paging with virtual memory switched on + for (const name of Object.keys(HW_NAMES)) { + const r = renderStatic({ view: 'hw', files, setup: p.setup, hw: [name], max: 12 }); + assert.deepEqual(r.warnings, [], name); + assert.doesNotMatch(r.html, /has-failed|could not be built/, name); + const frames = JSON.parse(/class="pplus-hw-data">([^<]*)</.exec(r.html)[1]).cards.flatMap((c) => c.frames).join(''); + assert.doesNotMatch(frames, /<button|<input|<select/, `${name}: its drawings keep no control`); + } + assert.match(renderStatic({ view: 'hw', files, setup: p.setup, hw: ['paging'], max: 12 }).html, /with virtual memory/); + const sampled = renderStatic({ view: 'hw', files, setup: p.setup, hw: ['registers'], max: 20 }); + const sd = JSON.parse(/class="pplus-hw-data">([^<]*)</.exec(sampled.html)[1]); + assert.ok(sd.shown.length <= 21 && sd.shown.at(-1) === 97, 'a long run is sampled, and the last step is always there'); + assert.match(sampled.html, /every 5th is drawn/); + const one = renderStatic({ view: 'hw', files, setup: p.setup, hw: ['encoding'], t: 9, stepper: false, listing: false }); + assert.doesNotMatch(one.html, /pplus-steps-bar|pplus-hw-data|pplus-hw-listing/, 'stepper="0": one step, nothing to step'); + assert.match(one.markdown, /The machine at step 9 of 97, after `mov r11/); + assert.equal(hwView('alu'), 'bits'); + assert.equal(hwView('chip'), 'machine'); + assert.equal(hwView('run'), null, 'not a machine view'); + const none = renderStatic({ view: 'hw', files: { pseudo: PSEUDO } }); + assert.match(none.warnings.join(), /no x86-64 file/); +}); + +test('render.mjs compresses the machine\'s steps, and they come back whole', () => { + const p = problemById('asm-two-pointers'); + const r = spawnSync(process.execPath, [ROOT + 'quarto/_extensions/pplus/render.mjs', ROOT], { input: JSON.stringify({ view: 'hw', files: { asm: p.sources.asm }, setup: p.setup, hw: ['pipeline'] }), encoding: 'utf8' }); + const res = JSON.parse(r.stdout); + const b64 = /type="application\/x-pplus-deflate" class="pplus-hw-data">([^<]+)</.exec(res.html)[1]; + const data = JSON.parse(zlib.inflateRawSync(Buffer.from(b64, 'base64')).toString('utf8')); + assert.equal(data.cards[0].id, 'pipeline'); + assert.ok(b64.length < 60000, `the pipeline over 97 steps is ${b64.length} characters`); +}); + +test('a run that cannot start reports its EXPECT lines as not printed', () => { + const r = renderStatic({ view: 'run', files: { pseudo: '// EXPECT: 3\nPROCEDURE F(\n' } }); + assert.deepEqual(r.expect, { want: ['3'], got: [], ok: false }); + assert.match(r.warnings.join('\n'), /It does not run yet/); + assert.equal(renderStatic({ view: 'run', files: { pseudo: 'PROCEDURE F(\n' } }).expect, undefined, 'no EXPECT lines, nothing to hold it to'); +}); diff --git a/tests/quarto.test.mjs b/tests/quarto.test.mjs new file mode 100644 index 0000000..8ddb08a --- /dev/null +++ b/tests/quarto.test.mjs @@ -0,0 +1,302 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// The Quarto extension embeds what the playground shows: the whole playground or one view, arranged by the +// shortcode's options; the app reads those options from the embed's query (applyEmbedParams). +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { applyEmbedParams, emptyState, EMBED_VIEWS, parseRoute } from '../dist/core/state.js'; + +const ROOT = new URL('..', import.meta.url).pathname; +const EXT = ROOT + 'quarto/_extensions/pplus'; + +test('an embed query arranges the example the way the playground controls do', () => { + const base = { ...emptyState(), sources: { mojo: 'def main():\n pass', asm: 'ret' }, lang: 'pseudo' }; + const s = applyEmbedParams(base, new URLSearchParams('lang=mojo&panel=compiler&build=default&machine=Zen%204&dock=closed&docktab=output&editor=0.6&side=0.4&dockheight=0.75&t=3'), 'hw'); + assert.equal(s.lang, 'mojo'); + assert.equal(s.view, 'compiler'); + assert.equal(s.build, 'default'); + assert.equal(s.machine, 'Zen 4'); + assert.deepEqual(s.layout, { hw: { dockCollapsed: true, dockTab: 'output', split: 0.6, right: 0.4, dock: 0.75 } }, 'the arrangement is the area\'s'); + assert.equal(s.t, 3); + assert.equal(base.layout, undefined, 'the state it was given is not changed'); +}); + +test('a malformed embed query changes nothing', () => { + const base = emptyState(); + const s = applyEmbedParams(base, new URLSearchParams('panes=klingon&area=nowhere&panel=nope&build=O3&editor=2&t=-1&lang=cobol&dock=maybe')); + assert.equal(s.view, base.view); + assert.equal(s.lang, base.lang); + assert.equal(s.build, undefined); + assert.equal(s.t, undefined); + assert.deepEqual(s.layout, {}); +}); + +test('the playground and the Mojo views are embeddable routes', () => { + for (const v of ['playground', 'life', 'compiler']) assert.ok(EMBED_VIEWS.includes(v)); + const r = parseRoute('#/embed/playground/p/demo?panel=life'); + assert.equal(r.kind, 'embed'); + assert.equal(r.view, 'playground'); + assert.equal(r.problem, 'demo'); + assert.equal(r.params.get('panel'), 'life'); +}); + +test('check-pages knows every view the app embeds', () => { + const text = fs.readFileSync(ROOT + 'scripts/check-pages.mjs', 'utf8'); + const listed = new Set([...(/const EMBED_VIEWS = new Set\(\[([^\]]+)\]\)/.exec(text)?.[1] ?? '').matchAll(/'([^']+)'/g)].map((m) => m[1])); + assert.deepEqual([...listed].sort(), [...EMBED_VIEWS].sort()); +}); + +// the shortcode itself, run by pandoc's Lua with Quarto's few functions stubbed. Without pandoc 3 on the PATH these +// are skipped on a developer's machine. Under CI (the CI variable set, as Gitea and GitHub Actions set it) they are +// not skipped: they run and fail, because a skip in CI is how a gap hides (eleven of these were skipped in CI for +// weeks, until pixi brought pandoc to the runner). pixi run test brings pandoc. +const pandoc = spawnSync('pandoc', ['--version'], { encoding: 'utf8' }); +const lua = pandoc.status === 0 && /pandoc 3/.test(pandoc.stdout); +const NO_PANDOC = !lua && !process.env.CI && 'pandoc 3 is not on the PATH'; +const needPandoc = () => assert.ok(lua, 'pandoc 3 is not on the PATH, and CI must run the Quarto tests: run them as pixi run test, which brings the pinned pandoc'); + +function shortcode(calls, files) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pplus-qmd-')); + for (const [f, text] of Object.entries(files)) fs.writeFileSync(path.join(dir, f), text); + fs.writeFileSync(path.join(dir, 'calls.json'), JSON.stringify(calls)); + needPandoc(); + const r = spawnSync('pandoc', ['lua', ROOT + 'tests/quarto/harness.lua', EXT, dir, path.join(dir, 'calls.json')], { encoding: 'utf8' }); + assert.equal(r.status, 0, r.stderr); + return { out: r.stdout.trim().split('\n').map((l) => JSON.parse(l)), warnings: r.stderr }; +} +const stateOf = (src) => JSON.parse(Buffer.from(/\/~([\w-]+)/.exec(src)[1], 'base64url').toString('utf8')); + +const MOJO = '# origin: Programming+ demo\n# probe: a recursive function\n# mode: both\n# args: -O0 --debug-level=line-tables\n# expect: pass\n\ndef main():\n # note: this comment is the program\'s\n print(1)\n'; + +test('the shortcode embeds the whole playground from files, arranged as asked', { skip: NO_PANDOC }, () => { + const { out } = shortcode([{ mojo: 'demo.mojo', asm: 'demo.asm', setup: 'demo.setup', view: 'playground', area: 'hw', panel: 'compiler', build: 'default', dock: 'open', editor: '0.6', title: 'Demo' }], + { 'demo.mojo': MOJO, 'demo.asm': 'main:\n ret', 'demo.setup': '# main() takes no arguments' }); + const [o] = out; + assert.match(o.src, /^https:\/\/pplus\.scient\.ing\/#\/embed\/playground\/~/); + assert.equal(o.height, '720', 'the playground gets a taller frame by default'); + const st = stateOf(o.src); + assert.equal(st.sources.mojo, 'def main():\n # note: this comment is the program\'s\n print(1)', 'the corpus header is left out; a comment in the program is kept'); + assert.equal(st.sources.asm, 'main:\n ret'); + assert.equal(st.setup, '# main() takes no arguments'); + assert.equal(st.view, 'compiler'); + assert.equal(st.build, 'default'); + assert.deepEqual(st.layout, { hw: { dockCollapsed: false, split: 0.6 } }); + assert.equal(st.title, 'Demo'); + assert.match(o.src, /\?area=hw&panel=compiler&build=default&dock=open&editor=0\.6$/); +}); + +test('the shortcode writes a state the app reads back whole, and lists matho as LaTeX', { skip: NO_PANDOC }, async () => { + const { normalize } = await import('../dist/core/state.js'); + const { out } = shortcode([{ pseudo: 'x.pseudo' }, { matho: 'm.tex', show: 'listing', math: '0' }], { 'x.pseudo': 'OUTPUT 1\n', 'm.tex': 'y = x^2\n' }); + const st = stateOf(out[0].src); + assert.equal(st.v, normalize(st).v, 'the shortcode writes the current state format'); + assert.equal(normalize(st).sources.pseudo, 'OUTPUT 1'); + assert.deepEqual(out[1].codes, [{ lang: 'latex', text: 'y = x^2' }], 'pandoc highlights the listing as LaTeX'); +}); + +test('the shortcode arranges a catalog problem and a state from Share, and refuses an unknown view', { skip: NO_PANDOC }, () => { + const { out, warnings } = shortcode([ + { problem: 'demo', view: 'playground', panel: 'life', machine: 'Zen 4', theme: 'dark' }, + { state: 'https://pplus.scient.ing/#/bridge/s/~eyJ2IjoyfQ', view: 'life' }, + { mojo: 'demo.mojo', show: 'listing' }, + { mojo: 'demo.mojo', view: 'nonsense' }, + { mojo: 'demo.mojo', view: 'playground', height: 'auto' }, + ], { 'demo.mojo': MOJO }); + assert.equal(out[0].src, 'https://pplus.scient.ing/#/embed/playground/p/demo?panel=life&machine=Zen%204&theme=dark'); + assert.equal(out[1].src, 'https://pplus.scient.ing/#/embed/life/~eyJ2IjoyfQ', 'a whole share link is cut down to its state'); + assert.deepEqual(out[2].codes, [{ lang: 'mojo', text: 'def main():\n # note: this comment is the program\'s\n print(1)' }]); + assert.match(out[3].src, /#\/embed\/trace\//); + assert.match(warnings, /unknown view="nonsense"/); + assert.equal(out[4].height, '720'); + assert.match(warnings, /height="auto" does not apply/); +}); + +/* ---------- the family of shortcodes (quarto/_extensions/pplus/pplus.lua) ---------- */ + +const PSEUDO = '// CALL: COUNT_BASE(\'A\', "GATTACA")\n// EXPECT: COUNT_BASE returned 3\nFUNCTION COUNT_BASE(B : CHAR, T : STRING) RETURNS INTEGER\n DECLARE Total : INTEGER\n Total <- 0\n FOR I <- 0 TO LENGTH(T)\n IF T[I] == B THEN\n Total <- Total + 1\n ENDIF\n NEXT I\n RETURN Total\nENDFUNCTION\n'; +const sc = (name, kw, meta = { 'pplus-cache': 'false' }) => ({ sc: name, kw, meta }); + +test('pplus.lua offers every shortcode the gallery and check-pages know, and no other', { skip: NO_PANDOC }, async () => { + const { SHORTCODE_NAMES } = await import('../dist/quarto/shortcodes.js'); + needPandoc(); + const r = spawnSync('pandoc', ['lua', '-e', `quarto = { doc = { input_file = '' } }; local t = dofile('${EXT}/pplus.lua'); local n = {} for k in pairs(t) do n[#n + 1] = k end table.sort(n) print(table.concat(n, ' '))`], { encoding: 'utf8' }); + assert.equal(r.status, 0, r.stderr); + assert.deepEqual(r.stdout.trim().split(' '), [...SHORTCODE_NAMES].sort()); + const check = fs.readFileSync(ROOT + 'scripts/check-pages.mjs', 'utf8'); + const hwViews = [...(/const HW_VIEWS = \[([^\]]+)\]/.exec(check)?.[1] ?? '').matchAll(/'([^']+)'/g)].map((m) => m[1]); + const listed = [...(/const SHORTCODES = new Set\(\[([^\]]+)\]\)/.exec(check)?.[1] ?? '').matchAll(/'([^']+)'/g)].map((m) => m[1]).filter((n) => n.startsWith('pplus')); + assert.deepEqual([...listed, ...hwViews.map((v) => `pplus-hw-${v}`)].sort(), [...SHORTCODE_NAMES].sort(), 'scripts/check-pages.mjs knows every shortcode'); + const { HW_NAMES } = await import('../dist/quarto/machine.js'); + assert.deepEqual(hwViews, Object.keys(HW_NAMES), 'and every machine view, in the same order as pplus.lua'); + const luaHw = [...(/local HW_VIEWS = \{([^}]+)\}/.exec(fs.readFileSync(EXT + '/pplus.lua', 'utf8'))?.[1] ?? '').matchAll(/"([^"]+)"/g)].map((m) => m[1]); + assert.deepEqual(luaHw, Object.keys(HW_NAMES)); + const { STATIC_VIEWS } = await import('../dist/quarto/render.js'); + const views = new Set([...(/const STATIC_VIEWS = new Set\(\[([^\]]+)\]\)/.exec(check)?.[1] ?? '').matchAll(/'([^']+)'/g)].map((m) => m[1])); + for (const v of STATIC_VIEWS) assert.ok(views.has(v), `check-pages knows pplus-view's view="${v}"`); +}); + +test('a rendered shortcode runs the file while the page renders: no iframe, the view in the page', { skip: NO_PANDOC }, () => { + const { out, warnings } = shortcode([ + sc('pplus-run', { pseudo: 'count.pseudo', code: '1', title: 'Count' }), + sc('pplus-steps', { pseudo: 'count.pseudo', t: '3' }), + sc('pplus-flow', { pseudo: 'count.pseudo', live: 'click' }), + sc('pplus-view', { view: 'dataflow', pseudo: 'count.pseudo' }), + ], { 'count.pseudo': PSEUDO }); + const [run, steps, flow, data] = out; + assert.equal(run.src, undefined, 'no iframe'); + assert.ok(run.divs.includes('pplus-figure pplus-figure-run')); + assert.match(run.raw.join(''), /class="[^"]*pplus-static pplus-v-run[^"]*"/); + assert.match(run.raw.join(''), /COUNT_BASE returned 3/); + assert.match(run.raw.join(''), /pplus-figtitle">Count</); + assert.deepEqual(run.codes.map((c) => c.lang), ['pseudo'], 'code="1" puts the listing in the figure'); + assert.doesNotMatch(run.codes[0].text, /CALL:|EXPECT:/, 'without its header lines'); + assert.match(steps.raw.join(''), /<script type="application\/json" class="pplus-steps-data">/); + assert.match(steps.raw.join(''), /data-t="3"/); + assert.match(flow.raw.join(''), /<svg[^>]*class="flow-svg"/); + assert.match(flow.raw.join(''), /class="pplus-golive" data-src="https:\/\/pplus\.scient\.ing\/#\/embed\/flow\/~/, 'live="click" carries the live view to put in its place'); + assert.match(data.raw.join(''), /pplus-v-data/); + assert.doesNotMatch(warnings, /pplus-run|pplus-steps|pplus-flow/); +}); + +test('a rendered run that does not print its EXPECT lines is reported, and stops the render with pplus-strict', { skip: NO_PANDOC }, () => { + const wrong = PSEUDO.replace('returned 3', 'returned 4'); + const { warnings } = shortcode([sc('pplus-run', { pseudo: 'w.pseudo' })], { 'w.pseudo': wrong }); + assert.match(warnings, /pplus-run in index\.qmd: run: printed \["COUNT_BASE returned 3"\], its EXPECT lines say \["COUNT_BASE returned 4"\]/); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pplus-qmd-')); + fs.writeFileSync(path.join(dir, 'w.pseudo'), wrong); + fs.writeFileSync(path.join(dir, 'calls.json'), JSON.stringify([sc('pplus-run', { pseudo: 'w.pseudo' }, { 'pplus-strict': 'true', 'pplus-cache': 'false' })])); + needPandoc(); + const r = spawnSync('pandoc', ['lua', ROOT + 'tests/quarto/harness.lua', EXT, dir, path.join(dir, 'calls.json')], { encoding: 'utf8' }); + assert.notEqual(r.status, 0, 'the render stops'); + assert.match(r.stderr, /does not print its EXPECT lines \(pplus-strict is on\)/); +}); + +test('check-pages reads a machine shortcode too: pplus-hw-<view> with a missing file, and a view that does not exist', () => { + // the name pattern once stopped at the first hyphenated part, so every pplus-hw-<view> shortcode was skipped + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pplus-pages-')); + fs.writeFileSync(path.join(dir, 'two.asm'), 'main:\n ret\n'); + const run = (text) => { + fs.writeFileSync(path.join(dir, 'index.qmd'), text); + return spawnSync(process.execPath, [ROOT + 'scripts/check-pages.mjs', dir], { encoding: 'utf8', cwd: ROOT, env: { ...process.env, CHECK_FILES_ONLY: '1' } }); + }; + const ok = run('{{< pplus-hw-pipeline asm="two.asm" >}}\n'); + assert.equal(ok.status, 0, ok.stdout + ok.stderr); + const missing = run('{{< pplus-hw-pipeline asm="missing.asm" >}}\n'); + assert.equal(missing.status, 1); + assert.match(missing.stdout, /pplus-hw-pipeline >}} names missing\.asm, which does not exist/); + const unknown = run('{{< pplus-hw-nosuch asm="two.asm" >}}\n'); + assert.equal(unknown.status, 1); + assert.match(unknown.stdout, /pplus-hw-nosuch >}} is not a shortcode of the extension/); +}); + +test('a program with EXPECT lines that does not run stops the render with pplus-strict', { skip: NO_PANDOC }, () => { + const broken = '// EXPECT: 3\nPROCEDURE F(\n'; + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pplus-qmd-')); + fs.writeFileSync(path.join(dir, 'b.pseudo'), broken); + fs.writeFileSync(path.join(dir, 'calls.json'), JSON.stringify([sc('pplus-run', { pseudo: 'b.pseudo' }, { 'pplus-strict': 'true', 'pplus-cache': 'false' })])); + needPandoc(); + const r = spawnSync('pandoc', ['lua', ROOT + 'tests/quarto/harness.lua', EXT, dir, path.join(dir, 'calls.json')], { encoding: 'utf8' }); + assert.notEqual(r.status, 0, 'the render stops'); + assert.match(r.stderr, /does not print its EXPECT lines \(pplus-strict is on\)/); +}); + +test('without an engine a rendered view falls back to the listing and the live view', { skip: NO_PANDOC }, () => { + const { out, warnings } = shortcode([sc('pplus-table', { pseudo: 'count.pseudo' }, { 'pplus-engine': 'none' })], { 'count.pseudo': PSEUDO }); + assert.deepEqual(out[0].codes.map((c) => c.lang), ['pseudo']); + assert.match(out[0].src, /#\/embed\/table\/~/); + assert.match(warnings, /showing the live view instead/); +}); + +test('translate writes a tabset of code blocks; listing, tabs and link need no engine', { skip: NO_PANDOC }, () => { + const { out } = shortcode([ + sc('pplus-translate', { matho: 'mean.tex' }), + sc('pplus-listing', { pseudo: 'count.pseudo', numbers: '1' }), + sc('pplus-tabs', { pseudo: 'count.pseudo', matho: 'mean.tex' }), + sc('pplus-link', { pseudo: 'count.pseudo', text: 'Open it' }), + sc('pplus-playground', { pseudo: 'count.pseudo', panel: 'flow' }), + sc('pplus-embed', { pseudo: 'count.pseudo', view: 'life' }), + ], { 'count.pseudo': PSEUDO, 'mean.tex': '% CALL: X_BAR(3, [1.0, 2.0, 6.0])\n\\bar{x} = \\frac{1}{n} \\sum_{i=0}^{n-1} x_i\n' }); + const [tr, listing, tabs, link, playground, embed] = out; + assert.ok(tr.divs.some((d) => d.includes('panel-tabset')), 'a tabset (Quarto turns it into tabs)'); + assert.deepEqual(tr.codes.map((c) => c.lang), ['latex', 'lingo', 'pseudo', 'mojo'], 'the file the page gave first, then what was made from it'); + assert.match(tr.codes.find((c) => c.lang === 'pseudo').text, /FUNCTION X_BAR/); + assert.equal(tr.maths.length, 1, 'the equation typeset too'); + assert.match(tr.raw.join(''), /pplus-tag-generated/); + assert.deepEqual(listing.codes, [{ lang: 'pseudo', text: PSEUDO.split('\n').slice(2).join('\n').trim() }]); + assert.ok(tabs.divs.some((d) => d.includes('panel-tabset'))); + assert.match(link.links[0], /^https:\/\/pplus\.scient\.ing\/#\/bridge\/s\/~/); + assert.match(playground.src, /#\/embed\/playground\/~.*\?panel=flow$/); + assert.equal(playground.height, '720'); + assert.match(embed.src, /#\/embed\/life\/~/); +}); + +test('in a format other than HTML a rendered view is Markdown', { skip: NO_PANDOC }, () => { + process.env.PPLUS_FORMAT = 'latex'; + try { + const { out } = shortcode([sc('pplus-run', { pseudo: 'count.pseudo' }), sc('pplus-flow', { pseudo: 'count.pseudo' })], { 'count.pseudo': PSEUDO }); + assert.equal(Object.keys(out[0].raw).length, 0, 'no HTML'); // (an empty Lua table is {} in JSON) + assert.deepEqual(out[0].codes.map((c) => c.text), ['COUNT_BASE returned 3']); + assert.ok(out[0].links.length, 'and a link to the app'); + assert.equal(Object.keys(out[1].raw).length, 0); + } finally { delete process.env.PPLUS_FORMAT; } +}); + +test('the Lua listing and the renderer\'s leave out the same header lines', { skip: NO_PANDOC }, async () => { + const { listingText } = await import('../dist/quarto/program.js'); + const files = { 'a.pseudo': PSEUDO, 'b.mojo': MOJO, 'c.tex': '% CALL: F(1)\n% EXPECT: F returned 1\ny = x\n', 'd.lingo': '// CALL: F(1)\nTo f x:\n The answer is x.\n' }; + const { out } = shortcode([sc('pplus-listing', { pseudo: 'a.pseudo', mojo: 'b.mojo', matho: 'c.tex', lingo: 'd.lingo', math: '0' })], files); + const byLang = Object.fromEntries(out[0].codes.map((c) => [c.lang, c.text])); + assert.equal(byLang.pseudo, listingText(PSEUDO, 'pseudo')); + assert.equal(byLang.mojo, listingText(MOJO, 'mojo')); + assert.equal(byLang.latex, listingText(files['c.tex'], 'matho')); + assert.equal(byLang.lingo, listingText(files['d.lingo'], 'lingo')); +}); + +test('pplus-views.css is what `pixi run quarto-css` writes from styles.css', () => { + const r = spawnSync(process.execPath, [ROOT + 'scripts/quarto-css.mjs', '--check'], { encoding: 'utf8' }); + assert.equal(r.status, 0, r.stderr || r.stdout); +}); + +test('the example site\'s programs run as their headers say, and its shortcodes name files that exist', () => { + const r = spawnSync(process.execPath, [ROOT + 'scripts/check-pages.mjs', ROOT + 'quarto/example'], { encoding: 'utf8', cwd: ROOT }); + assert.equal(r.status, 0, r.stdout + r.stderr); + assert.match(r.stdout, /0 problems/); + const page = fs.readFileSync(ROOT + 'quarto/example/index.qmd', 'utf8') + fs.readFileSync(ROOT + 'quarto/example/live.qmd', 'utf8'); + const used = new Set([...page.matchAll(/(?<!\{)\{\{<\s*(pplus(?:-[a-z]+)?)/g)].map((m) => m[1])); + const page2 = page + fs.readFileSync(ROOT + 'quarto/example/machine.qmd', 'utf8'); + for (const m of page2.matchAll(/(?<!\{)\{\{<\s*(pplus(?:-[a-z]+)*)/g)) used.add(m[1]); + for (const name of ['pplus-run', 'pplus-steps', 'pplus-table', 'pplus-flow', 'pplus-dataflow', 'pplus-lifetimes', 'pplus-proof', 'pplus-tests', 'pplus-check', 'pplus-translate', 'pplus-machine', 'pplus-view', 'pplus-hw', 'pplus-hw-pipeline', 'pplus-hw-chip', 'pplus-hw-paging', 'pplus-hw-encoding', 'pplus-hw-counters', 'pplus-playground', 'pplus-embed', 'pplus-listing', 'pplus-tabs', 'pplus-link']) + assert.ok(used.has(name), `the example site uses ${name}`); +}); + +test('the machine: pplus-hw draws the board over an x86-64 run, and pplus-hw-<view> one card', { skip: NO_PANDOC }, async () => { + const { problemById } = await import('../dist/core/catalog.js'); + const p = problemById('asm-two-pointers'); + const files = { 'two.asm': p.sources.asm, 'two.setup': p.setup }; + const { out, warnings } = shortcode([ + sc('pplus-hw', { asm: 'two.asm', setup: 'two.setup', t: '9' }), + sc('pplus-hw-cache', { asm: 'two.asm', setup: 'two.setup', listing: '0' }), + sc('pplus-hw', { asm: 'two.asm', setup: 'two.setup', views: 'registers,nonsense', column: 'body' }), + sc('pplus-hw-registers', { pseudo: 'count.pseudo' }), + ], { ...files, 'count.pseudo': PSEUDO }); + const [board, cache, named, noAsm] = out; + const html = board.raw.join(''); + assert.ok(board.divs.includes('pplus-figure pplus-figure-hw column-page'), 'the board is page-wide'); + for (const card of ['registers', 'flags', 'address', 'memory', 'stack']) assert.match(html, new RegExp(`data-hw="${card}"`), `the first preset has ${card}`); + assert.match(html, /pplus-hw-now">Step 9: mov r11, qword ptr/); + assert.match(html, /<div class="a86 board-a86" data-hw-frame="">\s*<section class="a86-panel/, 'the opening step\'s drawing is in the markup'); + assert.match(html, /<script type="application\/x-pplus-deflate" class="pplus-hw-data">[A-Za-z0-9+/=]+<\/script>/, 'every step, compressed'); + assert.match(html, /href="https:\/\/pplus\.scient\.ing\/#\/hw\/s\/~/, 'open in the playground goes to Hardware'); + const cacheHtml = cache.raw.join(''); + assert.ok(cache.divs.includes('pplus-figure pplus-figure-hw'), 'one card is as wide as the text'); + assert.match(cacheHtml, /data-hw="cache"/); + assert.doesNotMatch(cacheHtml, /pplus-hw-listing/); + assert.ok(!named.divs.some((d) => d.includes('column-'))); + assert.match(warnings, /pplus-hw in index\.qmd: hw: no machine view "nonsense"/); + assert.match(noAsm.raw.join(''), /run an x86-64 file/); + assert.match(warnings, /pplus-hw-registers in index\.qmd: hw: no x86-64 file/); +}); diff --git a/tests/quarto/harness.lua b/tests/quarto/harness.lua new file mode 100644 index 0000000..c02ba5c --- /dev/null +++ b/tests/quarto/harness.lua @@ -0,0 +1,36 @@ +-- Runs the extension's shortcodes outside Quarto, with the few `quarto` functions they use stubbed, and prints one +-- JSON line per call for tests/quarto.test.mjs. Usage: pandoc lua harness.lua <ext> <page dir> <calls.json> +-- +-- A call is either the options of {{< pplus >}} ({ pseudo = "x.pseudo", ... }), or { sc = "pplus-run", kw = {...}, +-- meta = {...} } for any shortcode. The line holds what the blocks came to: the iframe's src and height, the code +-- blocks (language and text), the links, the raw HTML, the classes of every Div, and the tab titles. +local ext, dir, calls_file = arg[1], arg[2], arg[3] +local b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +local function b64(data) + return ((data:gsub('.', function(x) local r, b = '', x:byte() for i = 8, 1, -1 do r = r .. (b % 2 ^ i - b % 2 ^ (i - 1) > 0 and '1' or '0') end return r end) .. '0000'):gsub('%d%d%d?%d?%d?%d?', function(x) + if #x < 6 then return '' end local c = 0 for i = 1, 6 do c = c + (x:sub(i, i) == '1' and 2 ^ (6 - i) or 0) end return b64chars:sub(c + 1, c + 1) end) .. ({ '', '==', '=' })[#data % 3 + 1]) +end +local format = os.getenv('PPLUS_FORMAT') or 'html' +quarto = { doc = { input_file = dir .. '/index.qmd', is_format = function(f) return f == format end, add_html_dependency = function() end }, + base64 = { encode = b64 }, json = { encode = pandoc.json.encode } } +local shortcodes = dofile(ext .. '/pplus.lua') +local f = io.open(calls_file); local calls = pandoc.json.decode(f:read('a'), false); f:close() +local function str_table(t) local out = {} for k, v in pairs(t or {}) do out[k] = pandoc.Str(tostring(v)) end return out end +for _, call in ipairs(calls) do + local name, kw, meta = 'pplus', call, {} + if call.sc then name, kw, meta = call.sc, call.kw or {}, call.meta or {} end + local out = { codes = {}, links = {}, raw = {}, divs = {}, maths = {} } + local blocks = shortcodes[name]({}, kw, str_table(meta)) + pandoc.Div(blocks):walk({ + RawBlock = function(blk) + out.raw[#out.raw + 1] = blk.text + local src = blk.text:match('<iframe[^>]-src="([^"]+)"') + if src then out.src = src:gsub('&', '&'); out.height = blk.text:match('<iframe[^>]-height="(%d+)"') end + end, + CodeBlock = function(blk) out.codes[#out.codes + 1] = { lang = blk.classes[1], text = blk.text } end, + Link = function(l) out.links[#out.links + 1] = l.target end, + Div = function(d) if #d.classes > 0 then out.divs[#out.divs + 1] = table.concat(d.classes, ' ') end end, + Math = function(m) out.maths[#out.maths + 1] = m.text end, + }) + print(pandoc.json.encode(out)) +end diff --git a/tests/services.test.mjs b/tests/services.test.mjs new file mode 100644 index 0000000..c72d052 --- /dev/null +++ b/tests/services.test.mjs @@ -0,0 +1,26 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// Runs against the compiled output: `npm test` builds first. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { PROBLEMS, stateForProblem } from '../dist/core/catalog.js'; +import { Session } from '../dist/core/session.js'; +import { encodeState, decodeState, parseRoute, routeFor } from '../dist/core/state.js'; +import { toAscii, toMath, parseSpec, weave, extractSpec } from '../core/dist/services/speco.js'; +import { studyOf, runPseudo, provePseudo } from '../core/dist/services/pseudo.js'; +import { readLingo, runLingo } from '../core/dist/services/lingo.js'; +import { parseAsm, runAsmProgram, parseSetup } from '../core/dist/services/asm.js'; + +globalThis.localStorage = { getItem() { return null; }, setItem() { }, removeItem() { } }; + +test('state survives a URL round trip and routes parse', async () => { + const st = stateForProblem(PROBLEMS[0]); st.t = 7; st.call = 'COUNT_BASE(\'G\', "GGG")'; + const back = await decodeState(await encodeState(st)); + assert.deepEqual(back.sources, st.sources); + assert.equal(back.t, 7); assert.equal(back.call, st.call); assert.equal(back.problem, st.problem); + assert.deepEqual(parseRoute('#/bridge/p/count-base'), { kind: 'problem', area: 'bridge', id: 'count-base' }); + const r = parseRoute('#/embed/trace/p/match?t=12'); + assert.equal(r.kind, 'embed'); assert.equal(r.view, 'trace'); assert.equal(r.problem, 'match'); assert.equal(r.params.get('t'), '12'); + assert.equal(routeFor({ kind: 'problem', area: 'dev', id: 'match' }), '#/dev/p/match'); +}); + diff --git a/tests/site-data.test.mjs b/tests/site-data.test.mjs new file mode 100644 index 0000000..a8b563d --- /dev/null +++ b/tests/site-data.test.mjs @@ -0,0 +1,124 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// "What this site stores and sends" (SITE_DATA in src/core/site.ts, in the footer) is held to the code here: what the +// shipped files ask for, which other sites they name, what they keep in the browser, and the footer's legal lines. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { GODBOLT_BASE } from '../core/dist/mojo/generated/pin.js'; +import { SITE_DATA, SOURCE_URL, LICENSE_FILES, DISCLAIMER, DESCRIPTION, siteVersion } from '../dist/core/site.js'; + +const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url))); +const read = (p) => fs.readFileSync(path.join(ROOT, p), 'utf8'); +const walk = (dir, keep) => fs.readdirSync(path.join(ROOT, dir), { withFileTypes: true }).flatMap((e) => { + const p = path.join(dir, e.name); + return e.isDirectory() ? walk(p, keep) : keep(p) ? [p] : []; +}); + +/** What scripts/assemble.sh ships: the page, the styles and fonts, dist/, core's dist/ (without the lesson corpus), and the Quarto extension. */ +const shipped = () => { + const code = (p) => /\.(m?js|css|html|lua)$/.test(p) && !p.endsWith('.d.ts') && !p.endsWith('.map'); + return [ + 'index.html', 'styles.css', + ...walk('styles', code), ...walk('fonts', code), ...walk('dist', code), + ...walk('core/dist', code).filter((p) => !p.startsWith('core/dist/curriculum/')), + ...walk('quarto/_extensions/pplus', code).filter((p) => !p.includes('/engine/')), + ]; +}; + +test('the only request the shipped code makes to another site is Compile & run\'s, to godbolt.org', () => { + const files = shipped(); + assert.ok(files.length > 100, `${files.length} files`); + const api = /\bfetch\s*\(|XMLHttpRequest|sendBeacon|new\s+WebSocket|new\s+EventSource|\.importScripts\s*\(/; + const callers = files.filter((f) => api.test(read(f))); + assert.deepEqual(callers, ['core/dist/services/godbolt.js'], 'a new network call must be added to the note on what the site sends'); + assert.equal(new URL(GODBOLT_BASE).hostname, 'godbolt.org'); +}); + +test('every other site the shipped files name is a link a reader follows, or not a place at all', () => { + // a new origin fails here until it is listed with what it is; none of them is asked for anything (the CSP's + // connect-src, font-src and script-src allow this site and godbolt.org only: tests/csp.test.mjs) + const allowed = new Map([ + ['https://godbolt.org', 'Compile & run (the one request, after asking)'], + ['https://mojolang.org', 'links to the Mojo manual and release notes'], + ['https://quest.mojolang.org', 'a link to Mojo Quest'], + ['https://doi.org', 'links to where a library routine\'s method comes from'], + ['https://dlmf.nist.gov', 'the same: the NIST Digital Library of Mathematical Functions'], + ['https://www.itl.nist.gov', 'the same: the NIST/SEMATECH e-Handbook of Statistical Methods'], + ['https://archive.org', 'the same: a scanned handbook'], + ['https://biopython.org', 'the same: the documentation of the function a routine is held against'], + ['https://biosc1540.scient.ing', 'the "guide" link beside a diagnostic'], + ['https://pplus.scient.ing', 'the Quarto extension\'s default address of the app, for its live views'], + ['http://www.w3.org', 'the SVG namespace, not a request'], + ['https://pplus.invalid', 'the address the small document of src/quarto/dom.ts pretends to have'], + ]); + if (SOURCE_URL) allowed.set(new URL(SOURCE_URL).origin, 'the footer\'s link to the source'); + const seen = new Map(); + for (const f of shipped()) for (const m of read(f).matchAll(/\bhttps?:\/\/[a-z0-9.-]+\.[a-z]{2,}(?::\d+)?/gi)) { + const o = new URL(m[0]).origin; + if (!seen.has(o)) seen.set(o, f); + } + const unknown = [...seen].filter(([o]) => !allowed.has(o)).map(([o, f]) => `${o} (${f})`); + assert.deepEqual(unknown, [], 'say what each is in this test, and in SITE_DATA if the site asks it for anything'); + assert.ok(seen.has(new URL(GODBOLT_BASE).origin)); +}); + +test('the site keeps nothing but localStorage and one sessionStorage mark, under names that start with pplus', () => { + const src = walk('src', (p) => p.endsWith('.ts') && !p.includes('/vendor/')).map(read).join('\n'); + for (const api of ['document.cookie', 'indexedDB', 'caches.open', 'serviceWorker', 'openDatabase']) assert.ok(!src.includes(api), `src uses ${api}`); + const shippedCode = shipped().filter((f) => f.endsWith('.js')).map(read).join('\n'); + assert.ok(!/document\.cookie|indexedDB\.open|navigator\.serviceWorker/.test(shippedCode), 'nor do the shipped modules'); + // every key a storage call names starts with pplus. (keys built by a function are checked where they are built) + const literal = [...src.matchAll(/(?:local|session)Storage\.(?:getItem|setItem|removeItem)\(\s*(['"`])([^'"`$]*)/g)].map((m) => m[2]); + assert.ok(literal.length > 3); + for (const k of literal) assert.ok(/^pplus[.:]/.test(k) || k.startsWith('progo.'), `storage key ${k}`); + // the keys built from an id (a problem's save, its versions, a preference per area) are template strings + const built = [...src.matchAll(/`(pplus[.:][^`$]*)\$\{/g)].map((m) => m[1]); + assert.ok(built.length >= 4, built.join(' ')); + for (const k of built) assert.ok(/^pplus[.:]/.test(k), `storage key ${k}…`); + assert.match(read('src/core/guard.ts'), /sessionStorage/, 'the one sessionStorage mark (SITE_DATA says so)'); + assert.match(SITE_DATA.join(' '), /localStorage/); + assert.match(SITE_DATA.join(' '), /sessionStorage/); + assert.match(SITE_DATA.join(' '), /under names that start with "pplus"/); +}); + +test('the note says what Compile & run sends, that it asks first, and that a shared link never saves over your work', () => { + const text = SITE_DATA.join(' '); + assert.match(text, /No accounts, no cookies, no analytics/); + assert.match(text, /Compile & run sends the Mojo pane's text, the input box's lines and the build flags to godbolt\.org/); + assert.match(text, /The first time, it says so and asks; nothing is sent until you agree/); + assert.match(text, /never saves over your own work/); + // what the request carries is mojoRequestBody's: the source, the input and the flags (core's src/services/godbolt.ts) + const body = read('core/src/services/godbolt.ts'); + assert.match(body, /export function mojoRequestBody\(source: string, stdin = '', args = ''\)/); + // held elsewhere: tests/hardening.test.mjs "the first Compile & run asks before anything is sent" and + // "a shared link never saves over the reader's own work on the problem it names" + const hardening = read('tests/hardening.test.mjs'); + assert.match(hardening, /the first Compile & run asks before anything is sent/); + assert.match(hardening, /a shared link never saves over the reader\\'s own work/); +}); + +test('the footer links the license and notices the site ships, and repeats NOTICE.md\'s disclaimer', () => { + const assemble = read('scripts/assemble.sh'); + for (const f of LICENSE_FILES) { + const file = f.href.replace('./', ''); + assert.ok(fs.existsSync(path.join(ROOT, file)), file); + assert.match(assemble, new RegExp(`\\b${file.replace('.', '\\.')}\\b`), `assemble.sh copies ${file}`); + } + assert.match(read('LICENSE.md'), /Apache License/); + const notice = read('NOTICE.md').replace(/\s+/g, ' '); + assert.ok(notice.includes('Programming+ is not affiliated with, sponsored by, or endorsed by Modular Inc.')); + assert.match(DISCLAIMER, /^Programming\+ is not affiliated with, sponsored by, or endorsed by Modular Inc\./); + assert.equal(typeof SOURCE_URL, 'string', 'the source address: one constant, empty until the owner sets it'); + assert.ok(DESCRIPTION.length < 120); +}); + +test('the build\'s version is shown only when the assembled page names a commit', () => { + assert.equal(siteVersion('0123456789abcdef0123456789abcdef01234567'), '0123456789ab'); + assert.equal(siteVersion('dev'), null); + assert.equal(siteVersion(''), null); + assert.equal(siteVersion(null), null); + assert.equal(siteVersion('<script>'), null); +}); diff --git a/tests/spdx.test.mjs b/tests/spdx.test.mjs new file mode 100644 index 0000000..9ee1b5a --- /dev/null +++ b/tests/spdx.test.mjs @@ -0,0 +1,38 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// Every source file written here says who holds its copyright and under which license, in two SPDX lines at its +// top, so a file copied out of the repository still says where it came from. Left without them, on purpose: +// the vendored editor's type declarations (src/vendor/), which are other people's files with their own +// notices (THIRD_PARTY.md). A new file fails here until +// it has the lines; this test goes with them if the owner drops the headers. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; + +const ROOT = new URL('..', import.meta.url).pathname; +const LEFT_OUT = [/^src\/vendor\//]; +const HOLDER = 'SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC'; +const LICENSE = 'SPDX-License-Identifier: Apache-2.0'; + +test('every hand-written source, script and test starts with its SPDX lines', () => { + const files = []; + const walk = (dir) => { + for (const e of fs.readdirSync(path.join(ROOT, dir), { withFileTypes: true })) { + const f = `${dir}/${e.name}`; + if (e.isDirectory()) { if (!['node_modules', '__pycache__'].includes(e.name)) walk(f); } + else if (/\.(ts|js|mjs|py|sh)$/.test(e.name) && !LEFT_OUT.some((r) => r.test(f))) files.push(f); + } + }; + for (const d of ['src', 'scripts', 'tests']) walk(d); + assert.ok(files.length > 85, `${files.length} files read`); + const missing = []; + for (const f of files) { + const lines = fs.readFileSync(path.join(ROOT, f), 'utf8').split('\n'); + const at = lines[0].startsWith('#!') ? 1 : 0; + const mark = /\.(py|sh)$/.test(f) ? '# ' : '// '; + if (lines[at] !== mark + HOLDER || lines[at + 1] !== mark + LICENSE) missing.push(f); + } + assert.deepEqual(missing, []); + assert.match(fs.readFileSync(path.join(ROOT, 'LICENSE.md'), 'utf8'), /Apache License/); +}); diff --git a/tests/state.test.mjs b/tests/state.test.mjs new file mode 100644 index 0000000..1ffcd21 --- /dev/null +++ b/tests/state.test.mjs @@ -0,0 +1,95 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// Programming+ is a new product: a state from any other version normalizes to empty, not migrated. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { normalize, emptyState, DEFAULT_PANES } from '../dist/core/state.js'; + +test('the state format is 3: no code pane, and mojo is the pane of Mojo the student writes', () => { + assert.equal(emptyState().v, 3); + assert.ok(!DEFAULT_PANES.includes('code')); + assert.ok(DEFAULT_PANES.includes('mojo')); +}); + +test('format-3 Mojo state round-trips, with its build level', () => { + const s = normalize({ v: 3, lang: 'mojo', panes: ['pseudo', 'mojo'], sources: { mojo: 'def main():\n print(1)' }, view: 'compiler', build: 'default' }); + assert.equal(s.lang, 'mojo'); assert.equal(s.view, 'compiler'); assert.equal(s.build, 'default'); + assert.equal(s.sources.mojo, 'def main():\n print(1)'); + assert.equal(normalize({ v: 3, build: 'O3' }).build, undefined); +}); + +test('a state from any other version normalizes to empty, not migrated', () => { + assert.deepEqual(normalize({ v: 2, lang: 'mojo', panes: ['pseudo', 'mojo'], sources: { pseudo: 'OUTPUT 1' } }), emptyState()); + assert.deepEqual(normalize({ v: 1, lang: 'code', panes: ['pseudo', 'code', 'asm'], sources: { pseudo: 'OUTPUT 1', code: 'print(1)' }, target: 'rust', codeView: 'manual' }), emptyState()); + // the oldest links, with no v at all, and whose generated pane was called mojo: also empty, not migrated + assert.deepEqual(normalize({ lang: 'mojo', panes: ['lingo', 'mojo'] }), emptyState()); +}); + +test('format-3 state round-trips', () => { + const s = normalize({ v: 3, lang: 'asm', sources: { asm: 'ret' }, view: 'asm' }); + assert.equal(s.lang, 'asm'); assert.equal(s.panes, undefined, 'the area, not the state, decides which panes show'); assert.equal(s.sources.asm, 'ret'); +}); + +test('an embed keeps its own save, never the app\'s save for the problem', async () => { + const { embedStorageId } = await import('../dist/core/state.js'); + const { Session } = await import('../dist/core/session.js'); + assert.equal(embedStorageId('mojo', 'count-base'), 'embed.mojo.p.count-base'); + assert.equal(embedStorageId('trace', undefined, 'abc'), embedStorageId('trace', undefined, 'abc')); + assert.notEqual(embedStorageId('trace', undefined, 'abc'), embedStorageId('trace', undefined, 'abd')); + assert.match(embedStorageId('trace', undefined, 'x'.repeat(5000)), /^embed\.trace\.b\.[0-9a-f]{8}$/); + const store = new Map(); + globalThis.localStorage = { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, String(v)), removeItem: (k) => store.delete(k) }; + try { + const embed = new Session(normalize({ v: 3, problem: 'count-base', sources: { pseudo: 'OUTPUT 1' } }), { storageId: 'embed.pseudo.p.count-base' }); + embed.setSource('pseudo', 'OUTPUT 2'); + assert.deepEqual([...store.keys()], ['pplus.embed.pseudo.p.count-base']); + const app = new Session(normalize({ v: 3, problem: 'count-base', sources: { pseudo: 'OUTPUT 1' } })); + app.setSource('pseudo', 'OUTPUT 3'); + assert.ok(store.has('pplus.count-base')); + assert.match(store.get('pplus.embed.pseudo.p.count-base'), /OUTPUT 2/); + // an embed keeps a save only while it holds edits: editing back to the original removes it + const { editedFrom } = await import('../dist/core/state.js'); + const original = normalize({ v: 3, problem: 'count-base', sources: { pseudo: 'OUTPUT 1' } }); + const kept = new Session(structuredClone(original), { storageId: 'embed.x', keep: (st) => editedFrom(st, original) }); + kept.setSource('pseudo', 'OUTPUT 9'); assert.ok(store.has('pplus.embed.x')); + kept.setSource('pseudo', 'OUTPUT 1'); assert.ok(!store.has('pplus.embed.x'), 'back to the original: no save'); + kept.setView('proof'); assert.ok(!store.has('pplus.embed.x'), 'where the reader looks is not an edit'); + const readOnly = new Session(normalize({ v: 3, problem: 'count-base' }), { storageId: null }); + store.clear(); readOnly.setSource('pseudo', 'OUTPUT 4'); + assert.equal(store.size, 0, 'a read-only embed saves nothing'); + } finally { delete globalThis.localStorage; } +}); + +test('a save made against an older version of a problem is dropped unless it holds edits', async () => { + const { normalize, editsFingerprint, resolveSaved } = await import('../dist/core/state.js'); + const original = normalize({ v: 3, problem: 'p', sources: { pseudo: 'OUTPUT 2' } }); + const older = normalize({ v: 3, problem: 'p', sources: { pseudo: 'OUTPUT 1' } }); + assert.deepEqual(resolveSaved(original, null), { state: original, stale: false }); + // made against the current version: kept as is + const current = { ...structuredClone(original), base: editsFingerprint(original), edited: false, t: 3 }; + assert.equal(resolveSaved(original, current).state.t, 3); + // made against an older version, no edits: the author's current version wins + const untouched = { ...structuredClone(older), base: editsFingerprint(older), edited: false }; + assert.deepEqual(resolveSaved(original, untouched), { state: original, stale: false }); + // made against an older version, with edits: kept, and marked stale + const edited = { ...structuredClone(older), sources: { pseudo: 'OUTPUT 9' }, base: editsFingerprint(older), edited: true }; + const r = resolveSaved(original, edited); + assert.equal(r.stale, true); assert.equal(r.state.sources.pseudo, 'OUTPUT 9'); + // a save from before fingerprints existed is kept + assert.equal(resolveSaved(original, normalize({ v: 3, sources: { pseudo: 'OUTPUT 7' } })).state.sources.pseudo, 'OUTPUT 7'); + // fingerprints ignore where the reader is looking + assert.equal(editsFingerprint(original), editsFingerprint({ ...original, t: 9, view: 'proof' })); +}); + +test('a save from another state format is discarded, so the problem opens as written', async () => { + const { loadLocal, resolveSaved } = await import('../dist/core/state.js'); + const { problemById, stateForProblem } = await import('../dist/core/catalog.js'); + const store = new Map([['pplus.count-base', JSON.stringify({ v: 2, problem: 'count-base', sources: { pseudo: 'OUTPUT 9' } })]]); + globalThis.localStorage = { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, String(v)), removeItem: (k) => store.delete(k) }; + try { + assert.equal(loadLocal('count-base'), null); + assert.ok(!store.has('pplus.count-base'), 'the old save is removed'); + const original = stateForProblem(problemById('count-base')); + assert.deepEqual(resolveSaved(original, loadLocal('count-base')).state, original); + } finally { delete globalThis.localStorage; } +}); diff --git a/tests/sync-hub.test.mjs b/tests/sync-hub.test.mjs new file mode 100644 index 0000000..bb5e92b --- /dev/null +++ b/tests/sync-hub.test.mjs @@ -0,0 +1,96 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// Stage 8: the sync hub (restructure plan, section 2.3), without any UI. Pseudo is the hub; the pane that is +// edited is the authority and is never rewritten; an authority with errors changes nothing; a language that +// cannot say the program goes stale rather than blank; contracts ride along; opening rewrites nothing; and the +// whole cascade is fast enough that typing stays instant. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { SyncHub, LINKED, namesFromMatho } from '../core/dist/sync/hub.js'; +import { pseudoToLingo } from '../core/dist/sync/pseudo-to-lingo.js'; +import { Session } from '../dist/core/session.js'; +import { PROBLEMS, stateForProblem, problemById } from '../dist/core/catalog.js'; +import { encodeState, decodeState, emptyState } from '../dist/core/state.js'; +import { checkMojo } from '../core/dist/mojo/check.js'; +import { studyOf } from '../core/dist/services/pseudo.js'; +import { EQUATIONS, FIXTURES } from '../core/tests/helpers/sync-programs.mjs'; + +globalThis.localStorage = { getItem() { return null; }, setItem() { }, removeItem() { } }; + +const sync = (r) => ({ authority: r.authority, stale: r.stale, names: r.names }); +const next = (r, lang, text) => new SyncHub(r.sources, sync(r)).edit(lang, text); + +const COUNT = `FUNCTION COUNT_BASE(B : CHAR, T : STRING) RETURNS INTEGER + DECLARE Total : INTEGER + Total <- 0 + FOR EACH C IN T + IF C == B THEN + Total <- Total + 1 + ENDIF + NEXT C + RETURN Total +ENDFUNCTION`; +const SIMPLE = `FUNCTION SUMMED(N : INTEGER, X : LIST OF FLOAT) RETURNS FLOAT + DECLARE S : FLOAT + S <- 0.0 + FOR I <- 0 TO N + S <- S + X[I] + NEXT I + RETURN S +ENDFUNCTION`; +const WHILE_PSEUDO = FIXTURES['fixture:div-mod'][0]; + +test('the first edit makes the pane the authority and writes the shown panes into the state', () => { + const p = problemById('count-base'); + const s = new Session(stateForProblem(p)); + let events = 0; s.onChange(() => events++); + const lingo = s.source('lingo').replace('Start with Count at 0.', 'Start with Count at 5.'); + assert.notEqual(lingo, s.source('lingo')); + s.setSource('lingo', lingo); + assert.equal(events, 1, 'one change event for the whole cascade'); + assert.equal(s.state.sync.authority, 'lingo'); + assert.equal(s.state.sources.lingo, lingo); + assert.match(s.source('pseudo'), /Count <- 5/); + assert.match(s.derivedMojo().source, /count = 5/); + assert.equal(s.linkState('lingo').kind, 'authority'); + assert.equal(s.linkState('pseudo').kind, 'sync'); + // an unchanged text is not an edit + s.setSource('lingo', lingo); + assert.equal(events, 1); + // Mojo and x86-64 are not linked + s.setSource('mojo', 'def main():\n pass\n'); + assert.equal(s.state.sync.authority, 'lingo'); +}); + +test('a share link round-trips sync, and a stale pane stays stale', async () => { + const p = problemById('count-base'); + const s = new Session(stateForProblem(p)); + s.setSource('pseudo', 'FUNCTION BROKEN(\nRETURN'); + assert.equal(s.linkState('lingo').kind, 'stale'); + const blob = await encodeState(s.state); + const back = await decodeState(blob); + assert.deepEqual(back.sync, s.state.sync); + const s2 = new Session(back); + assert.match(s2.linkState('lingo').reason, /pseudo line/); + assert.equal(s2.source('pseudo'), 'FUNCTION BROKEN(\nRETURN', 'a state that has been edited is not filled again'); + // a malformed sync field is dropped, not trusted + const { normalize } = await import('../dist/core/state.js'); + assert.equal(normalize({ v: 3, sync: { authority: 'mojo' } }).sync, undefined); +}); + +test('derivedMojo is the literal translation, is memoized by the pseudo and the call, and passes the checker', () => { + const s = new Session(stateForProblem(problemById('count-base'))); + const a = s.derivedMojo(); + assert.match(a.source, /^# Generated by Programming\+ from pseudo\./); + assert.equal(s.derivedMojo(), a, 'the same object while the pseudo and the call are unchanged'); + const diags = checkMojo(a.source).diagnostics.filter((d) => d.severity === 'error'); + assert.deepEqual(diags, []); + s.setSource('pseudo', s.source('pseudo').replace('Total <- 0', 'Total <- 1')); + assert.notEqual(s.derivedMojo(), a); + assert.match(s.derivedMojo().source, /total = 1/); + s.setCall('COUNT_BASE("C", "CCC")'); + assert.match(s.derivedMojo().source, /count_base\("C", "CCC"\)/); + // no pseudo, no Mojo + assert.equal(new Session(emptyState()).derivedMojo().source, ''); +}); + diff --git a/tests/tasks.test.mjs b/tests/tasks.test.mjs new file mode 100644 index 0000000..0544f71 --- /dev/null +++ b/tests/tasks.test.mjs @@ -0,0 +1,108 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// The commands people run live in pixi.toml; the README's table lists them. core/ is pplus-core, a project of its +// own with its own pixi.toml and this same test. These tests keep the +// two in step, and keep every `pixi run <task>` mentioned anywhere pointing at a task that exists. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; + +const ROOT = new URL('..', import.meta.url).pathname; +const read = (p) => fs.readFileSync(path.join(ROOT, p), 'utf8'); + +/** Task names in pixi.toml's [tasks] table: `name = {` at the start of a line, until the next table. */ +function pixiTasks() { + const text = read('pixi.toml'); + const body = text.slice(text.indexOf('\n[tasks]') + 1).split(/\n\[(?!tasks\])/)[0]; + return [...body.matchAll(/^([a-z][a-z0-9-]*)\s*=\s*\{/gm)].map((m) => m[1]); +} + +/** Task names in the README's Commands table: the first cell, a backticked name with optional arguments. */ +function readmeTasks() { + const readme = read('README.md'); + const section = readme.slice(readme.indexOf('## Commands'), readme.indexOf('\n## ', readme.indexOf('## Commands') + 1)); + return [...section.matchAll(/^\| `([a-z][a-z0-9-]*)(?: [^`]*)?` \|/gm)].map((m) => m[1]); +} + +test('the README lists every pixi task, once, and nothing else', () => { + const tasks = pixiTasks(); + assert.ok(tasks.length > 15, `only ${tasks.length} tasks read from pixi.toml`); + const listed = readmeTasks(); + assert.deepEqual([...listed].sort(), [...tasks].sort()); + assert.equal(new Set(listed).size, listed.length, 'a task is listed twice'); +}); + +test('every pixi task has a description', () => { + const text = read('pixi.toml'); + for (const t of pixiTasks()) { + const line = text.split('\n').find((l) => l.startsWith(`${t} = {`)); + assert.match(line, /description = "[^"]+"/, `${t} has no description`); + } +}); + +test('every `pixi run <task>` in the docs, scripts and sources names a real task', () => { + const tasks = new Set(pixiTasks()); + const files = []; + const walk = (dir) => { + for (const e of fs.readdirSync(path.join(ROOT, dir), { withFileTypes: true })) { + const p = path.join(dir, e.name); + if (e.isDirectory()) { if (!['node_modules', 'dist', 'site', '.git', '.pixi', 'corpus', 'golden', 'vendor', 'scratch', '_site', '.quarto'].includes(e.name) && p !== 'core') walk(p); } + else if (/\.(md|mjs|ts|py|lua|yml|toml)$/.test(e.name)) files.push(p); + } + }; + walk('.'); + const unknown = []; + for (const f of files) { + for (const m of read(f).matchAll(/pixi run ([a-z][a-z0-9-]*)/g)) if (!tasks.has(m[1])) unknown.push(`${f}: pixi run ${m[1]}`); + } + assert.deepEqual(unknown, []); +}); + +test('package.json keeps only what CI and a machine without pixi need', () => { + const pkg = JSON.parse(read('package.json')); + assert.deepEqual(Object.keys(pkg.scripts).sort(), ['build', 'check', 'dev', 'test', 'watch']); + // the README and AGENTS.md say TypeScript is the only npm dependency and the site has no npm runtime dependency + assert.equal(pkg.dependencies, undefined, 'no npm runtime dependency (CodeMirror is vendored in src/vendor/)'); + assert.deepEqual(Object.keys(pkg.devDependencies ?? {}), ['typescript']); +}); + +test('every document the README points to exists', () => { + const readme = read('README.md'); + for (const m of readme.matchAll(/\]\(((?:docs|quarto|styles)\/[^)#]+)\)/g)) assert.ok(fs.existsSync(path.join(ROOT, m[1])), `${m[1]} is linked from the README but missing`); + for (const m of read('docs/app.md').matchAll(/`(docs\/[\w.-]+\.md)`/g)) assert.ok(fs.existsSync(path.join(ROOT, m[1])), `${m[1]} is named in docs/app.md but missing`); +}); + +test('the site names the Mojo version core is pinned to, in its documents and in pixi.toml', async () => { + // core decides the pin (core/library/mojo/pin.json); these are the site's sentences that have to move with it + const { MOJO_VERSION, GODBOLT_COMPILER } = await import('../core/dist/mojo/generated/pin.js'); + const wrong = []; + for (const d of ['README.md', 'AGENTS.md', 'docs/app.md', 'docs/deploy.md', 'quarto/README.md']) { + fs.readFileSync(path.join(ROOT, d), 'utf8').split('\n').forEach((line, i) => { + for (const m of line.matchAll(/(?:pinned to (?:\*\*)?(?:Mojo )?|verified on Mojo )(\d+\.\d+\.\d+)/g)) if (m[1] !== MOJO_VERSION) wrong.push(`${d}:${i + 1} says ${m[1]}`); + for (const m of line.matchAll(/\bmojo_\d+_\d+_\d+\b/g)) if (m[0] !== GODBOLT_COMPILER) wrong.push(`${d}:${i + 1} says ${m[0]}`); + }); + } + assert.deepEqual(wrong, [], `core is pinned to Mojo ${MOJO_VERSION}`); + assert.match(fs.readFileSync(path.join(ROOT, 'pixi.toml'), 'utf8'), new RegExp(`^mojo = "==${MOJO_VERSION.replace(/\./g, '\\.')}"`, 'm'), 'pixi.toml installs the compiler core is pinned to'); +}); + +test('package.json and pixi.toml agree, and the site pins the same Node and Python as core', () => { + // package.json is what a machine without pixi reads; core/pixi.toml is the pin core is tested with + const pkg = JSON.parse(read('package.json')); + const toml = read('pixi.toml'); + const core = read('core/pixi.toml'); + assert.equal(/^version = "([^"]+)"/m.exec(toml)?.[1], pkg.version, 'the version in pixi.toml [workspace] and in package.json'); + for (const dep of ['nodejs', 'python']) { + const pin = (text) => new RegExp(`^${dep} = "([^"]+)"`, 'm').exec(text)?.[1]; + assert.equal(pin(toml), pin(core), `${dep}: the site pins ${pin(toml)}, core ${pin(core)}`); + } + const parts = (s) => s.split('.').map(Number).concat([0, 0]).slice(0, 3); + const atLeast = (a, b) => { for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i]; return true; }; + const floor = /^>=\s*(\d+(?:\.\d+){0,2})$/.exec(pkg.engines?.node ?? ''); + assert.ok(floor, `engines.node is "${pkg.engines?.node}"; this test reads ">=X.Y.Z"`); + const pinned = /^nodejs = ">=(\d+\.\d+\.\d+)/m.exec(toml); + assert.ok(pinned && atLeast(parts(pinned[1]), parts(floor[1])), `pixi installs Node ${pinned?.[1]}, below engines.node ${pkg.engines.node}`); + assert.equal(pkg.engines.node, JSON.parse(read('core/package.json')).engines?.node, 'the site and core name the same oldest Node'); + assert.ok(atLeast(parts(process.versions.node), parts(floor[1])), `this Node is ${process.versions.node}, below engines.node ${pkg.engines.node}`); +}); diff --git a/tests/third-party.test.mjs b/tests/third-party.test.mjs new file mode 100644 index 0000000..e29eed9 --- /dev/null +++ b/tests/third-party.test.mjs @@ -0,0 +1,72 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// THIRD_PARTY.md is written by hand; these tests hold it to the files that say what is bundled, copied, loaded +// and installed, so a rebuilt CodeMirror, a new copied stylesheet, a self-hosted font or a moved tool fails here +// until the inventory says so. They read files only: no build and no core/ needed. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; + +const ROOT = new URL('..', import.meta.url).pathname; +const read = (p) => fs.readFileSync(path.join(ROOT, p), 'utf8'); +const doc = read('THIRD_PARTY.md'); +const row = (name) => doc.split('\n').find((l) => l.startsWith(`| ${name} `)) ?? ''; + +test('every package bundled into codemirror.js has a row with its version and a copyright notice', () => { + const banner = read('src/vendor/codemirror.js').split('\n').slice(0, 3).join('\n'); + const pkgs = [...banner.matchAll(/(@?[a-z0-9-]+(?:\/[a-z0-9-]+)?)@(\d+\.\d+\.\d+)/g)].map((m) => [m[1], m[2]]); + assert.ok(pkgs.length >= 10, `only ${pkgs.length} packages read from the banner`); + for (const [name, version] of pkgs) { + const r = row(name); + assert.ok(r.includes(`| ${version} |`), `${name}@${version} has no row with that version`); + assert.match(r, /\| Copyright \(C\) \d{4}(-\d{4})? by .+ \|$/, `${name} has no copyright notice`); + } + const rows = doc.split('\n').filter((l) => /^\| (@[a-z0-9-]+\/)?[a-z0-9-]+ \| \d+\.\d+\.\d+ \| /.test(l)); + assert.equal(rows.length, pkgs.length, 'a row for a package the bundle does not hold'); + // the permission notice is the one the vendored license file carries + const permission = read('src/vendor/CODEMIRROR-LICENSE').split('\n').slice(4).join('\n').trim(); + assert.ok(doc.includes(permission), 'the MIT permission notice differs from src/vendor/CODEMIRROR-LICENSE'); +}); + +test('every copied course stylesheet and syntax definition is named', () => { + for (const dir of ['styles/course', 'quarto/_extensions/pplus/course', 'quarto/_extensions/pplus/syntax']) { + for (const f of fs.readdirSync(path.join(ROOT, dir))) if (/\.(css|xml)$/.test(f)) assert.ok(doc.includes(`\`${f}\``), `${dir}/${f} is not named`); + } +}); + +test('the fonts the page loads are named, and a font file in the repository has its license beside it', () => { + const html = read('index.html'); + for (const m of html.matchAll(/family=([A-Za-z+]+)/g)) assert.ok(doc.includes(m[1].replace(/\+/g, ' ')), `${m[1]} is not named`); + const fonts = []; + const walk = (d) => { + for (const e of fs.readdirSync(path.join(ROOT, d), { withFileTypes: true })) { + const p = path.join(d, e.name); + if (e.isDirectory()) { if (!['node_modules', 'dist', 'core', '.git', '.pixi', 'site', 'scratch', '_site', '.quarto'].includes(e.name)) walk(p); } // _site and .quarto: what `pixi run quarto-example` leaves, with Quarto's own fonts + else if (/\.(woff2?|ttf|otf)$/i.test(e.name)) fonts.push(p); + } + }; + walk('.'); + for (const f of fonts) { + const dir = path.dirname(f); + assert.ok(fs.readdirSync(path.join(ROOT, dir)).some((n) => /^(OFL|LICENSE)/i.test(n)), `${f} has no OFL or LICENSE file beside it`); + } + if (fonts.length) assert.ok(/IBM Plex/.test(doc), 'font files are served but THIRD_PARTY.md names no font'); +}); + +test('the tools in pixi.lock and package-lock.json have their versions and licenses', () => { + const lock = read('pixi.lock'); + const conda = (pkg) => { + const m = lock.match(new RegExp(`\\n- conda: \\S*/${pkg}-(\\d[^-/]*)-[^/\\s]*\\.conda\\n(?: .*\\n)*? license: (.+)`)); + assert.ok(m, `${pkg} is not in pixi.lock`); + return { version: m[1], license: m[2].trim() }; + }; + for (const [name, pkg] of [['Mojo', 'mojo'], ['Node.js', 'nodejs'], ['Python', 'python'], ['pandoc', 'pandoc']]) { + const c = conda(pkg); + assert.ok(row(name).includes(`| ${c.version} |`) && row(name).includes(c.license), `${name} ${c.version}, ${c.license}`); + } + const pkgs = JSON.parse(read('package-lock.json')).packages; + assert.deepEqual(Object.keys(pkgs).filter((k) => k), ['node_modules/typescript'], 'a new npm package needs a row here (and AGENTS.md allows none)'); + const ts = pkgs['node_modules/typescript']; + assert.ok(row('TypeScript').includes(`| ${ts.version} |`) && row('TypeScript').includes(`| ${ts.license} |`), `TypeScript ${ts.version}, ${ts.license}`); +}); diff --git a/tests/trust.test.mjs b/tests/trust.test.mjs new file mode 100644 index 0000000..71342b9 --- /dev/null +++ b/tests/trust.test.mjs @@ -0,0 +1,73 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// Every badge and chip the site shows makes a claim, and core's docs/trust.md is where each claim says what earned +// it, what it means and what it does not mean. This test holds the two together: the words a badge can show are +// listed here with the row of trust.md that covers them, the words must still be in the source that draws them, the +// row must still be in trust.md, and a badge drawn in a new place fails the count until it is listed. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; + +const trust = fs.readFileSync('core/docs/trust.md', 'utf8'); +/** The first cell ("Shown") of every row of every table in trust.md. */ +const shown = trust.split('\n').filter((l) => l.startsWith('| ') && !/^\| (Shown|---)/.test(l)).map((l) => l.slice(2).split(' | ')[0]); +const read = (f) => fs.readFileSync(f, 'utf8'); +const walk = (dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(dir, e.name)) : e.name.endsWith('.ts') ? [path.join(dir, e.name)] : [])); + +/** [the words on the badge, the file that draws it, the words of trust.md's "Shown" cell that cover it] */ +const BADGES = [ + ['Generated from pseudo', 'src/ui/provenance.ts', '**Generated from pseudo**'], + ['best-practice rewrite', 'src/ui/provenance.ts', '**Generated from pseudo, with N best-practice rewrites**'], + ['Started from generated Mojo', 'src/ui/provenance.ts', '**Started from generated Mojo**'], + ['Compiled on godbolt', 'src/ui/provenance.ts', '**Compiled on godbolt**'], + ['Edited since compile', 'src/ui/provenance.ts', '**Edited since compile**'], + ...['compiling', 'ran, exit 0', 'exited with', 'compiled, did not run', 'did not compile', 'timed out', 'no answer'] + .map((w) => [w, 'src/ui/views/compiler.ts', `**${w}`]), + ['verified on Mojo', 'src/ui/shell.ts', '**verified on Mojo'], + ['not verified', 'src/ui/shell.ts', '**not verified**'], + ['your edits', 'src/ui/shell.ts', '**your edits**'], + ['`Mojo ${MOJO_VERSION}`', 'src/ui/shell.ts', '(no other word)'], + ["'verified'", 'src/ui/home.ts', 'The home page\'s **verified** chip'], + ['your edits saved', 'src/ui/home.ts', '**your edits saved** chip'], + ['proved', 'src/ui/views/panels.ts', '**Proved**'], + ['broken by a run', 'src/ui/views/panels.ts', '**Broken**'], + ['open', 'src/ui/views/panels.ts', '**Open**'], + ['partial: not every path was examined', 'src/ui/views/panels.ts', '**partial: not every path was examined**'], + ['no failures', 'src/ui/views/tests.ts', '**no failures**'], + ['of failing', 'src/ui/views/tests.ts', '**N ways of failing**'], + ['not tested', 'src/ui/views/tests.ts', '**not tested**'], + // the home page's sample cards show the same three kinds of answer on a fixed example + ['no failures', 'src/ui/home.ts', '**no failures**'], + ['to fail', 'src/ui/home.ts', '**N ways of failing**'], + ['proved', 'src/ui/home.ts', '**Proved**'], + ['ran, exit 0', 'src/ui/home.ts', '**ran, exit 0**'], +]; +/** The library page's chips are a check's name and one of five words; trust.md has a row for each kind of check. */ +const LIBRARY_ROWS = ['**Cases pass**', '**Prover: pass**', '**Prover: open**', '**A reference agrees**', '**Mojo: unverified**', '**Proof: pass**']; + +test('every badge the site can show is drawn where this test says, and has a row in core\'s docs/trust.md', () => { + assert.ok(shown.length >= 30, `${shown.length} rows read from core/docs/trust.md`); + for (const [words, file, row] of BADGES) { + assert.ok(read(file).includes(words), `${file} no longer shows "${words}": take it off this list, or say what replaced it`); + assert.ok(shown.some((c) => c.includes(row)), `core/docs/trust.md has no row for ${row} (shown by ${file} as "${words}")`); + } + for (const row of LIBRARY_ROWS) assert.ok(shown.some((c) => c.includes(row)), `core/docs/trust.md has no row for ${row}`); +}); + +test('a badge drawn in a new place is listed here, with its row in trust.md, before it ships', () => { + const sites = new Map(); + for (const f of walk('src')) { + const n = (read(f).match(/class: [`'](?:badge[ `'$]|chip chip-verified|chip chip-saved|lib-chip[ `'$])/g) || []).length; + if (n) sites.set(f, n); + } + assert.deepEqual(Object.fromEntries(sites), { + 'src/ui/home.ts': 9, + 'src/ui/library.ts': 2, + 'src/ui/provenance.ts': 3, + 'src/ui/shell.ts': 3, + 'src/ui/views/compiler.ts': 2, + 'src/ui/views/panels.ts': 5, + 'src/ui/views/tests.ts': 3, + }, 'a badge was added or removed: update BADGES above and core\'s docs/trust.md, then this count'); +}); diff --git a/tests/versions.test.mjs b/tests/versions.test.mjs new file mode 100644 index 0000000..80f5e50 --- /dev/null +++ b/tests/versions.test.mjs @@ -0,0 +1,231 @@ +// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC +// SPDX-License-Identifier: Apache-2.0 +// Stage 14: saved versions. A version holds what the student edits (sources, link bookkeeping, where the Mojo came +// from, call, input, setup, machine, build) and not where they are looking (layout, step, open tab). Switching and +// Reset save unsaved work first, so neither loses anything; the cap holds; a link carries no versions, a file may. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { Session } from '../dist/core/session.js'; +import { stateForProblem, problemById } from '../dist/core/catalog.js'; +import { resolveSaved, editsFingerprint, normalize, encodeState, decodeState, saveLocal } from '../dist/core/state.js'; +import { + listVersions, saveVersion, renameVersion, deleteVersion, restoreVersion, editsOf, hasUnsavedEdits, versionKey, currentVersion, + exportVersions, importVersions, cleanVersion, storagePressure, MAX_VERSIONS, PRESSURE_CHARS, newWorkspaceId, +} from '../dist/core/versions.js'; + +function fakeStorage() { + const m = new Map(); + return { + getItem: (k) => m.get(k) ?? null, setItem: (k, v) => m.set(k, String(v)), removeItem: (k) => m.delete(k), + key: (i) => [...m.keys()][i] ?? null, get length() { return m.size; }, _m: m, + }; +} +let store; +test.beforeEach(() => { store = fakeStorage(); globalThis.localStorage = store; }); + +const problem = (id = 'count-base') => stateForProblem(problemById(id)); +const open = (state, area = 'bridge', opts = {}) => new Session(state, { area, storageId: null, original: opts.original, stale: opts.stale }); +const withLingo = (st, text) => { const s = structuredClone(st); s.sources.lingo = text; return s; }; + +test('save, list, rename, delete and restore round-trip', () => { + const st = problem(); + const key = versionKey(st); + assert.equal(key, 'pplus.versions.count-base'); + assert.deepEqual(listVersions(key), []); + const a = saveVersion(key, 'first', st, 'bridge', { now: 1000 }); + const edited = withLingo(st, 'Start with Total at 0.'); + const b = saveVersion(key, 'second', edited, 'dev', { now: 2000 }); + assert.ok(a.ok && b.ok); + assert.deepEqual(listVersions(key).map((v) => [v.name, v.area]), [['second', 'dev'], ['first', 'bridge']], 'newest first, with the area it was saved in'); + assert.equal(renameVersion(key, a.version.id, 'original'), true); + assert.equal(listVersions(key)[1].name, 'original'); + const back = restoreVersion(key, b.version.id, st); + assert.equal(back.sources.lingo, 'Start with Total at 0.'); + assert.equal(restoreVersion(key, 'nope', st), null); + assert.equal(deleteVersion(key, b.version.id), true); + assert.equal(listVersions(key).length, 1); + assert.equal(deleteVersion(key, 'nope'), false); + deleteVersion(key, a.version.id); + assert.equal(store.getItem(key), null, 'an empty list leaves nothing behind'); +}); + +test('a version holds the edited fields, sync, mojoOrigin and machine, and not the layout, step or tab', () => { + const st = problem(); + Object.assign(st, { input: '3\n', call: 'COUNT_BASE("A", "AA")', setup: 'x', machine: 'm', build: 'default', mojoOrigin: 'generated', sync: { authority: 'lingo', stale: {}, names: {} }, layout: { bridge: { split: 0.3 } }, t: 7, lang: 'matho', view: 'flow', title: 'T' }); + const e = editsOf(st); + assert.deepEqual(Object.keys(e).sort(), ['build', 'call', 'input', 'machine', 'mojoOrigin', 'setup', 'sources', 'sync']); + for (const k of ['layout', 't', 'lang', 'view', 'title', 'problem', 'base', 'edited']) assert.ok(!(k in e), k); +}); + +test('restoring changes the edits but not the layout, the step or the open tab; a field the version lacks does not linger', () => { + const key = 'pplus.versions.count-base'; + const plain = problem(); + const v = saveVersion(key, 'plain', plain, 'bridge').version; + const now = withLingo(plain, 'something else'); + Object.assign(now, { call: 'X()', mojoOrigin: 'generated-edited', sync: { authority: 'lingo', stale: {}, names: {} }, layout: { bridge: { split: 0.7 } }, t: 9, lang: 'lingo', view: 'flow' }); + const r = restoreVersion(key, v.id, now); + assert.equal(r.sources.lingo, plain.sources.lingo); + assert.equal(r.call, plain.call); + assert.ok(!('mojoOrigin' in r) && !('sync' in r)); + assert.deepEqual([r.layout, r.t, r.lang, r.view], [now.layout, 9, 'lingo', 'flow']); +}); + +test('switching with unsaved edits saves "Before switching" first; switching without edits does not', () => { + const st = problem(); + const s = open(structuredClone(st), 'bridge', { original: st }); + const keep = s.saveVersion('plain'); assert.ok(keep.ok); + assert.equal(s.hasUnsavedEdits(), false, 'the problem as written has nothing to lose'); + s.setSource('lingo', 'Start with Total at 5.'); + assert.equal(s.hasUnsavedEdits(), true); + const was = s.state.sources.lingo; + assert.ok(s.restoreVersion(keep.version.id)); + const names = s.versions().map((v) => v.name); + assert.equal(names.length, 2); + assert.ok(names.some((n) => /^Before switching \(/.test(n)), names.join('|')); + assert.ok(s.versions().find((v) => v.auto).edits.sources.lingo === was, 'the automatic version holds the work that was replaced'); + assert.equal(s.state.sources.lingo, st.sources.lingo); + // now the work is exactly a saved version: switching again adds nothing + assert.equal(s.hasUnsavedEdits(), false); + const before = s.versions().length; + const other = s.versions().find((v) => v.auto); + assert.ok(s.restoreVersion(other.id)); + assert.equal(s.versions().length, before); +}); + +test('Reset saves the work first as "Before reset", and does nothing extra when there is nothing to lose', () => { + const st = problem(); + const s = open(structuredClone(st), 'dev', { original: st }); + assert.ok(s.reset(problem())); + assert.deepEqual(s.versions(), []); + s.setSource('mojo', s.source('mojo') + '\n# mine'); + assert.ok(s.reset(problem())); + const [v] = s.versions(); + assert.match(v.name, /^Before reset \(/); + assert.ok(v.auto && v.edits.sources.mojo.endsWith('# mine')); + assert.ok(!s.source('mojo').includes('# mine')); +}); + +test('the cap holds: automatic versions make room, and named ones are never dropped to do it', () => { + const key = 'pplus.versions.count-base', st = problem(); + for (let i = 0; i < MAX_VERSIONS; i++) assert.ok(saveVersion(key, `v${i}`, st, 'bridge', { now: 1000 + i, auto: i < 3 }).ok); + assert.equal(listVersions(key).length, MAX_VERSIONS); + const r = saveVersion(key, 'more', st, 'bridge', { now: 9999 }); + assert.ok(r.ok); + assert.equal(r.dropped.length, 1); + assert.equal(r.dropped[0].name, 'v0', 'the oldest automatic one went'); + assert.equal(listVersions(key).length, MAX_VERSIONS); + for (let i = 0; i < 2; i++) saveVersion(key, `x${i}`, st, 'bridge', { now: 10000 + i }); + assert.equal(listVersions(key).length, MAX_VERSIONS); + const full = saveVersion(key, 'no room', st, 'bridge', { now: 20000 }); + assert.deepEqual(full, { ok: false, reason: 'cap' }); + assert.equal(listVersions(key).length, MAX_VERSIONS); +}); + +test('a refused save stops the switch: nothing changes and nothing is lost', () => { + const st = problem(); + const s = open(structuredClone(st), 'bridge', { original: st }); + const keep = s.saveVersion('plain'); + for (let i = 0; i < MAX_VERSIONS - 1; i++) saveVersion(s.versionKey(), `n${i}`, st, 'bridge', { now: 5 + i }); + s.setSource('lingo', 'Start with Total at 6.'); + assert.equal(s.restoreVersion(keep.version.id), false); + assert.equal(s.state.sources.lingo, 'Start with Total at 6.'); +}); + +test('a stale problem: "See the new version" keeps the edits as a version and opens the problem as it is now', () => { + const original = problem(); + const saved = withLingo(original, 'My own start.'); + saved.base = 'deadbeef'; saved.edited = true; // made against another version of the problem + const { state, stale } = resolveSaved(original, saved); + assert.equal(stale, true); + const s = open(state, 'bridge', { original, stale }); + assert.equal(s.stale, true); + assert.ok(s.seeNewVersion()); + assert.equal(s.stale, false); + assert.equal(s.state.sources.lingo, original.sources.lingo, 'the problem as it is now'); + const [v] = s.versions(); + assert.equal(v.name, 'My edits, before the problem changed'); + assert.ok(!v.auto); + assert.equal(v.edits.sources.lingo, 'My own start.'); + assert.equal(editsFingerprint(s.state), editsFingerprint(original)); +}); + +test('work from a share link has no problem: it gets a workspace id when first saved, and the list is found again by it', async () => { + const shared = normalize({ ...problem(), v: 3 }); shared.problem = undefined; shared.title = 'From a link'; + const blob = await encodeState(shared); + const s = open(await decodeState(blob), 'bridge'); + assert.equal(s.versionKey(), null); + assert.deepEqual(s.versions(), []); + assert.equal(s.hasUnsavedEdits(), true, 'work with no original has something to save once it has text'); + const r = s.saveVersion('mine'); + assert.ok(r.ok); + assert.match(s.state.workspace, /^w[0-9a-f]{16}$/); + assert.equal(s.versionKey(), `pplus.versions.ws.${s.state.workspace}`); + const again = open(await decodeState(await encodeState(s.state)), 'dev'); + assert.deepEqual(again.versions().map((v) => v.name), ['mine'], 'the same work in another area finds the same versions'); +}); + +test('the same work in each area shares one list', () => { + const st = problem(); + const a = open(structuredClone(st), 'bridge', { original: st }), b = open(structuredClone(st), 'dev', { original: st }), c = open(structuredClone(st), 'hw', { original: st }); + a.saveVersion('from the Bridge'); + assert.deepEqual(b.versions().map((v) => [v.name, v.area]), [['from the Bridge', 'bridge']]); + assert.equal(c.versions().length, 1); +}); + +test('a file with versions restores them in a fresh storage, never over a version with the same id', () => { + const key = 'pplus.versions.ws.wabc12345678', st = problem(); + saveVersion(key, 'one', st, 'bridge', { now: 1 }); saveVersion(key, 'two', withLingo(st, 'x'), 'dev', { now: 2 }); + const file = JSON.parse(JSON.stringify(exportVersions(key))); + const fresh = fakeStorage(); + assert.deepEqual(importVersions(key, file, fresh), { added: 2, skipped: 0 }); + assert.deepEqual(listVersions(key, fresh).map((v) => v.name), ['two', 'one']); + // renamed in the fresh browser; importing the file again must not undo that + renameVersion(key, file[0].id, 'renamed here', fresh); + assert.deepEqual(importVersions(key, file, fresh), { added: 0, skipped: 2 }); + assert.equal(listVersions(key, fresh).find((v) => v.id === file[0].id).name, 'renamed here'); +}); + +test('a damaged or hostile version in a file is dropped or cleaned, never trusted', () => { + assert.equal(cleanVersion(null), null); + assert.equal(cleanVersion({ id: '../x', name: 'n', at: 1, area: 'bridge', edits: {} }), null); + assert.equal(cleanVersion({ id: 'ok', name: 'n', at: 1, area: 'nowhere', edits: {} }), null); + const v = cleanVersion({ id: 'ok', name: 'n'.repeat(500), at: 1, area: 'bridge', edits: { sources: { pseudo: 'x', evil: 'y' }, layout: { bridge: { split: 0.1 } }, t: 4, mojoOrigin: 'hand-written' } }); + assert.equal(v.name.length, 120); + assert.deepEqual(Object.keys(v.edits), ['sources']); + assert.deepEqual(v.edits.sources, { pseudo: 'x' }); + const key = 'pplus.versions.count-base'; + assert.deepEqual(importVersions(key, 'nonsense'), { added: 0, skipped: 0 }); + assert.deepEqual(importVersions(key, [{ id: 1 }]), { added: 0, skipped: 1 }); +}); + +test('the drop-down warns when storage is nearly full', () => { + assert.equal(storagePressure(store).nearlyFull, false); + store.setItem('big', 'x'.repeat(PRESSURE_CHARS)); + assert.equal(storagePressure(store).nearlyFull, true); +}); + +test('a browser that refuses storage still keeps versions for the tab, and a full one says so instead of losing them', () => { + const key = 'pplus.versions.count-base', st = problem(); + assert.ok(saveVersion(key, 'tab only', st, 'bridge', { store: null }).ok); + assert.deepEqual(listVersions(key, null).map((v) => v.name), ['tab only']); + const full = { getItem: () => null, setItem() { throw new Error('quota'); }, removeItem() { } }; + assert.deepEqual(saveVersion(key, 'x', st, 'bridge', { store: full }), { ok: false, reason: 'storage' }); +}); + +test('a version is not in the state, a link or the problem\'s own save', async () => { + const s = open(problem(), 'bridge'); + s.saveVersion('v'); + assert.ok(!/versions?/i.test(JSON.stringify(s.state).replace(/"version"/g, ''))); + assert.ok(!/"edits"/.test(await encodeState(s.state))); + assert.equal(newWorkspaceId().length, 17); + assert.equal(currentVersion(s.versionKey(), s.state)?.name, 'v', 'the work is exactly the version just saved'); +}); + +test('a session keeps its own copy of the problem: editing the work never edits "the problem as written"', () => { + const st = problem(); + const s = open(st, 'bridge', { original: st }); // the very same object, as when a problem opens with no save + s.setSource('lingo', 'Start with Total at 5.'); + assert.notEqual(st.sources.lingo, 'Start with Total at 5.' === st.sources.lingo ? '' : 'x'); + assert.equal(s.hasUnsavedEdits(), true, 'the edit shows against the problem as written'); + assert.equal(s.state.sources.lingo, 'Start with Total at 5.'); +}); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..3511f79 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": [ + "ES2022", + "DOM", + "DOM.Iterable" + ], + "rootDir": "src", + "outDir": "dist", + "allowJs": true, + "checkJs": false, + "strict": true, + "noImplicitAny": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "allowUnreachableCode": false, + "allowUnusedLabels": false, + "noUncheckedSideEffectImports": true, + "skipLibCheck": true, + "sourceMap": true, + "types": [] + }, + "include": [ + "src/**/*.ts", + "src/vendor/*.js" + ] +}