diff --git a/CHANGELOG.md b/CHANGELOG.md index 4465128d..c5c5e304 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ The format is loosely inspired by Keep a Changelog. ### Changed +- **Web 0.14.31, web app links point to visucode.de:** the website now lives on one subdomain per world (visustruct.visucode.de, visubot.visucode.de, visuobject.visucode.de, published from the GitLab repo visucode/website). The app's home, imprint and privacy links go to the start page of the current world there (relative on its own subdomain, e.g. `../de/index.html`, otherwise absolute); before, in VisuBot they pointed to `../de/visubot.html`, which no longer exists. On visubot.visucode.de and visuobject.visucode.de the app starts in that world when no world was chosen yet. The about link (web and Swift app) and the Messprotokoll links in lesson 22 use the new addresses (`web/src/ui/site.ts`, test `site.test.ts`). - **Web 0.14.30, VisuBot concentrates on robotics:** the VisuBot world now shows only the robot lessons and robot tasks (23 lessons in four parts: Losfahren, Sensoren und Entscheidungen, Licht/Ton/Bildschirm, Motoren und Methoden) instead of all 40 VisuStruct lessons with the robot lessons in between; plain Java (console, Scanner, files, windows) stays in VisuStruct (Holger 2026-11-03). The five „Jetzt ohne Roboter“ steps became robot steps: L3 „Ergebnis auf dem Bildschirm“ (`mbot.showText`, data types with robot examples), L9 „Startsignal“ (switch in a for loop), L17 „Messreihe“ (five distance measurements in an array, average), L19 „Laufschrift“ (`charAt` backwards on the screen), L22 „Methode mit Rückgabe“ (`int zentimeter(int umdrehungen)`). New lesson 8 „Und, oder, nicht“ (`&&`, `||`, `!` with distance, line and buttons, truth tables, Java exercise „Sicher fahren“ in four worlds); it is inserted after the line lesson without renaming files, robot lessons are numbered in file order. Links „📘 Mehr dazu ohne Roboter“ (`[…](?visustruct&lektion=…)`) open the matching VisuStruct lesson in a new window (`?lektion=` opens a lesson). The robot lesson file `09-fallauswahl.md` is now `09-fallauswahl-mbot2.md`, because an old progress rename for VisuStruct deleted its progress on every load. Robot Java exercises are now also checked by typing them as Java (de/en). - **Web 0.14.29, VisuBot commands grouped by colour:** in the palette every mBot2 box gets a 4 px stripe on the left and every group heading a dot in the colour of its group: driving and wheels orange, light (LEDs) yellow-green, sound magenta, screen and emotions indigo, waiting and stopwatch grey, all sensors turquoise. The boxes themselves stay yellow (statement), and the structure chart and the code are unchanged. The former group „Licht, Ton und Bildschirm“ is split into „Licht“, „Ton“ and „Bildschirm“ in the palette and in the VisuBot Nachschlagen (de/en), whose `###` headings show the same dots. New lesson syntax `### Überschrift {.klasse}`. With „Blöcke farbig“ off, stripes and dots disappear. Every sub-group also gets a symbol in the palette (all languages) and in the Nachschlagen headings: 🚗 driving, ⚙️ wheels, 💡 LEDs, 🔊 sound, 🖥️ screen, 😊 emotions, ⏱️ waiting, 📏 distance, ➖ line, 🎨 colours, 🕹️ buttons/joystick, 🔆 light/loudness, 📐 tilt, 🔋 stopwatch/battery. - **Web 0.14.27, VisuBot: `forward`/`backward` overloaded with a unit:** besides `mbot.forward()` (10 cm) and `mbot.forward(30)` there is now `mbot.forward(2, "Umdrehungen")` and `mbot.forward(30, "cm")` (en `"rotations"`, pt `"rotações"`), same for `backward`. One wheel rotation is π · 6.5 cm ≈ 20.4 cm; the action stores the distance in cm, so simulation, exercise check and the real robot (`mbot2.straight`) work unchanged, and the console shows e.g. „2 Umdrehungen vorwärts (40.84 cm)“. An unknown unit is an error naming the allowed units. The CyberPi program export gets the same overload. VisuBot lesson 22 gets a step „Gleicher Name, andere Parameter: Überladung“ with the three headers, a Ludwig Angeberwissen asking pupils to measure their own robot with a printable test record (PDF, de/en, `website/visubot/messprotokoll-radumdrehung.pdf` / `test-record-wheel-rotation.pdf`: wheel diameter, five test cases expected vs. actual, evaluation, causes, feedback for the teacher, box „So testet man Softwaresysteme“), the exercise „Quadrat mit Umdrehungen“ and a quiz; Nachschlagen, glossary („Überladung“) and code completion list the new variants (de/en). diff --git a/VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/About/AboutVisuStructView.swift b/VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/About/AboutVisuStructView.swift index 42aacade..4202f2f8 100644 --- a/VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/About/AboutVisuStructView.swift +++ b/VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/About/AboutVisuStructView.swift @@ -16,8 +16,8 @@ struct AboutVisuStructView: View { // Öffentliches Java-Repo: maßgebliche Quelle & Releases (aktueller als dieses SwiftUI-Repo). private let projectDisplay = "code4teaching/VisuStruct" private let projectURL = URL(string: "https://github.com/code4teaching/VisuStruct") - private let webDisplay = "www.visustruct.org" - private let webURL = URL(string: "https://www.visustruct.org") + private let webDisplay = "visustruct.visucode.de" + private let webURL = URL(string: "https://visustruct.visucode.de") private let developerDisplay = "www.sebastiao.org" private let developerURL = URL(string: "https://www.sebastiao.org") // Java-Referenzrepo (aktuell gepflegt): code4teaching/VisuStruct diff --git a/web/lessons/README.md b/web/lessons/README.md index ca833e93..f5a539b8 100644 --- a/web/lessons/README.md +++ b/web/lessons/README.md @@ -165,7 +165,7 @@ Der Text darf Markdown und Links enthalten: ``` ::: angeberwissen -Ben Shneiderman hatte die Idee 1972. [Mehr dazu](https://visustruct.org/de/angeberwissen.html) +Ben Shneiderman hatte die Idee 1972. [Mehr dazu](https://visustruct.visucode.de/de/angeberwissen.html) ::: ``` diff --git a/web/lessons/de/visubot/22-eigene-methoden.md b/web/lessons/de/visubot/22-eigene-methoden.md index 9b1dbad2..0cef18f5 100644 --- a/web/lessons/de/visubot/22-eigene-methoden.md +++ b/web/lessons/de/visubot/22-eigene-methoden.md @@ -97,7 +97,7 @@ void forward(int wert, String einheit) Überladung kennst du schon: `System.out.println` gibt es für `int`, für `double`, für `String` und noch mehr. Deshalb kannst du jeden dieser Werte einfach in die Klammern schreiben. ::: angeberwissen -Stimmen die 20,4 cm bei **deinem** mBot2 wirklich? Profis glauben keiner Zahl, die sie nicht nachgemessen haben. Miss den Raddurchmesser und lass `mbot.forward(5, "Umdrehungen")` fahren: Soll sind 102,1 cm. So testet man Softwaresysteme: Jeder **Testfall** hat ein erwartetes Ergebnis (**Soll**) und ein gemessenes (**Ist**). Man testet mehrmals und schreibt alles in ein **Protokoll**. Hier ist dein [Messprotokoll zum Ausdrucken (PDF)](https://visustruct.org/visubot/messprotokoll-radumdrehung.pdf). Gib es deiner Lehrkraft, dann sieht sie, ob alle Roboter gleich weit fahren. +Stimmen die 20,4 cm bei **deinem** mBot2 wirklich? Profis glauben keiner Zahl, die sie nicht nachgemessen haben. Miss den Raddurchmesser und lass `mbot.forward(5, "Umdrehungen")` fahren: Soll sind 102,1 cm. So testet man Softwaresysteme: Jeder **Testfall** hat ein erwartetes Ergebnis (**Soll**) und ein gemessenes (**Ist**). Man testet mehrmals und schreibt alles in ein **Protokoll**. Hier ist dein [Messprotokoll zum Ausdrucken (PDF)](https://visubot.visucode.de/messprotokoll-radumdrehung.pdf). Gib es deiner Lehrkraft, dann sieht sie, ob alle Roboter gleich weit fahren. ::: ::: übung vb-ueberladung-umdrehung diff --git a/web/lessons/en/visubot/22-eigene-methoden.md b/web/lessons/en/visubot/22-eigene-methoden.md index a64cd016..fc475c8c 100644 --- a/web/lessons/en/visubot/22-eigene-methoden.md +++ b/web/lessons/en/visubot/22-eigene-methoden.md @@ -97,7 +97,7 @@ void forward(int value, String unit) You already know overloading: `System.out.println` exists for `int`, for `double`, for `String` and more. That is why you can simply put any of these values in the brackets. ::: angeberwissen -Are the 20.4 cm really true for **your** mBot2? Professionals don't trust a number they haven't measured. Measure the wheel diameter and run `mbot.forward(5, "rotations")`: the expected distance is 102.1 cm. This is how software systems are tested: every **test case** has an expected result and an actual (measured) result. You test several times and write everything into a **test record**. Here is your [test record to print (PDF)](https://visustruct.org/visubot/test-record-wheel-rotation.pdf). Give it to your teacher, so they can see whether all robots drive the same distance. +Are the 20.4 cm really true for **your** mBot2? Professionals don't trust a number they haven't measured. Measure the wheel diameter and run `mbot.forward(5, "rotations")`: the expected distance is 102.1 cm. This is how software systems are tested: every **test case** has an expected result and an actual (measured) result. You test several times and write everything into a **test record**. Here is your [test record to print (PDF)](https://visubot.visucode.de/test-record-wheel-rotation.pdf). Give it to your teacher, so they can see whether all robots drive the same distance. ::: ::: übung vb-ueberladung-umdrehung diff --git a/web/package-lock.json b/web/package-lock.json index 1442dae4..323f4a35 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -1,12 +1,12 @@ { "name": "visustruct-web", - "version": "0.14.30", + "version": "0.14.31", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "visustruct-web", - "version": "0.14.29", + "version": "0.14.31", "dependencies": { "@codemirror/autocomplete": "^6.20.4", "@codemirror/commands": "^6.11.1", diff --git a/web/package.json b/web/package.json index 4441fcf0..762b6758 100644 --- a/web/package.json +++ b/web/package.json @@ -1,7 +1,7 @@ { "name": "visustruct-web", "private": true, - "version": "0.14.30", + "version": "0.14.31", "type": "module", "scripts": { "dev": "vite", diff --git a/web/src/main.ts b/web/src/main.ts index a411145f..21ecdbb3 100644 --- a/web/src/main.ts +++ b/web/src/main.ts @@ -2,7 +2,8 @@ import './ui/styles.css' import { App, applyCanvasStubTexts } from './ui/app' import { installTooltips } from './ui/tooltip' import { preferredLanguage, setCodeKeywords, setLanguage, storedCodeKeywords } from './ui/i18n' -import { setVisuFlowWorld, setVisuObjectWorld, visuFlowWorld, visuObjectWorld } from './ui/visubotView' +import { setVisuBotMode, setVisuFlowWorld, setVisuObjectWorld, visuFlowWorld, visuObjectWorld, worldChosen } from './ui/visubotView' +import { hostWorld } from './ui/site' // Nach einem Update kann eine noch offene oder zwischengespeicherte Seite Dateien der alten Version // nachladen wollen, die es nicht mehr gibt. Dann einmal neu laden statt leer zu bleiben. @@ -53,6 +54,13 @@ Promise.all([setLanguage(language, false), setCodeKeywords(storedCodeKeywords(), installTooltips() // Welten VisuObject (…/app/?visuobject) und VisuFlow (?visuflow) haben eine eigene Oberfläche; ?visustruct und ?visubot wählt die App selbst. const query = new URLSearchParams(location.search) + // Erster Besuch auf visubot.visucode.de oder visuobject.visucode.de ohne Welt in der Adresse: gleich die Welt der Seite + const anyWorld = ['visustruct', 'visubot', 'visuobject', 'visuflow'].some((k) => query.has(k)) + if (!anyWorld && !worldChosen()) { + const site = hostWorld() + if (site === 'visubot') setVisuBotMode('on') + else if (site === 'visuobject') setVisuObjectWorld() + } if (query.has('visuobject')) setVisuObjectWorld() if (query.has('visuflow')) setVisuFlowWorld() const root = document.getElementById('app')! diff --git a/web/src/ui/app.ts b/web/src/ui/app.ts index 63e70413..07463827 100644 --- a/web/src/ui/app.ts +++ b/web/src/ui/app.ts @@ -1,4 +1,5 @@ import { canvasTextLines, setCanvasStubTexts } from '../core/diagramText' +import { worldHomeURL } from './site' import { appendCaseToFallauswahl, canDeleteElement, @@ -199,12 +200,7 @@ const isMac = /Mac|iPhone|iPad/.test(navigator.platform) /** Tastenkürzel im Tooltip, z. B. „Strg+S“ bzw. „⌘S“. */ /** Startseite (oder ein Abschnitt ihrer Fußzeile) in der passenden Sprache der Webseite; im VisuBot-Modus die VisuBot-Startseite. */ function siteURL(section?: 'contact' | 'privacy'): string { - const code = currentLanguage() - const lang = code === 'pt-PT' ? 'pt' : code === 'de' ? 'de' : 'en' - // Auf visustruct.org liegt die Web-App unter /app/, sonst (Vorschau, Einzeldatei) zur echten Seite - const base = /\/app\/(index\.html)?$/.test(location.pathname) ? '../' : 'https://visustruct.org/' - const page = visuBotEnabled() ? 'visubot' : 'index' - return `${base}${lang}/${page}.html${section ? `#${section}` : ''}` + return worldHomeURL(visuBotEnabled() ? 'visubot' : 'visustruct', currentLanguage(), section) } /** Symbolknopf; der Name (mit Tastenkürzel) erscheint als Tooltip. */ @@ -1162,7 +1158,7 @@ export class App {
${e(t('web_about_version_fmt').replace('%@', __APP_VERSION__))}
- ${link('about_web_label', 'https://www.visustruct.org', 'www.visustruct.org')} + ${link('about_web_label', 'https://visustruct.visucode.de', 'visustruct.visucode.de')} ${link('about_developer_label', 'https://www.sebastiao.org', 'www.sebastiao.org')} ${link('about_project_github_label', 'https://github.com/code4teaching/VisuStruct', 'code4teaching/VisuStruct')} diff --git a/web/src/ui/flowApp.ts b/web/src/ui/flowApp.ts index c00937e0..998cd79f 100644 --- a/web/src/ui/flowApp.ts +++ b/web/src/ui/flowApp.ts @@ -29,6 +29,7 @@ import { import { gearIcon } from './app' import { buildDiagramPDF, canvasRGB, canvasToPNG, exportFilenameSlug, rasterize, svgMarkup, type ExportImage } from './exporter' import { currentLanguage, t } from './i18n' +import { worldHomeURL } from './site' import { icons } from './icons' import { setVisuBotMode, setVisuObjectWorld, worldChooserHTML, type WorldChoice } from './visubotView' @@ -65,10 +66,7 @@ function store(key: string, value: string) { } function siteURL(): string { - const code = currentLanguage() - const lang = code === 'pt-PT' ? 'pt' : code === 'de' ? 'de' : 'en' - const base = /\/app\/(index\.html)?$/.test(location.pathname) ? '../' : 'https://visustruct.org/' - return `${base}${lang}/index.html` + return worldHomeURL('visustruct', currentLanguage()) } function download(name: string, data: BlobPart, type: string) { diff --git a/web/src/ui/i18n.ts b/web/src/ui/i18n.ts index 005b4e5d..ae913265 100644 --- a/web/src/ui/i18n.ts +++ b/web/src/ui/i18n.ts @@ -140,7 +140,7 @@ export function codeKeywords(): boolean { /** Wie `AppLanguage.deviceDefault`: erste Browsersprache, die VisuStruct anbietet, sonst Englisch. */ export function preferredLanguage(): LanguageCode { if (migrateJavaLanguage()) return 'en' - // Link von der Webseite, z. B. visustruct.org/app/?lang=de + // Link von der Webseite, z. B. visustruct.visucode.de/app/?lang=de const fromURL = new URLSearchParams(location.search).get('lang') if (fromURL && isOffered(fromURL)) return fromURL try { diff --git a/web/src/ui/objectApp.ts b/web/src/ui/objectApp.ts index 392bc4a8..2f6deb7c 100644 --- a/web/src/ui/objectApp.ts +++ b/web/src/ui/objectApp.ts @@ -75,6 +75,7 @@ import { } from '../core/umlRelations' import { gearIcon } from './app' import { currentLanguage, t } from './i18n' +import { worldHomeURL } from './site' import { icons } from './icons' import { codeScopes, JavaEditor, setCodeScopes } from './javaEditor' import { closeWindows, compileAndRunProject, prepareJava } from './javaRuntime' @@ -144,10 +145,7 @@ function store(key: string, value: string) { } function siteURL(): string { - const code = currentLanguage() - const lang = code === 'pt-PT' ? 'pt' : code === 'de' ? 'de' : 'en' - const base = /\/app\/(index\.html)?$/.test(location.pathname) ? '../' : 'https://visustruct.org/' - return `${base}${lang}/visuobject.html` + return worldHomeURL('visuobject', currentLanguage()) } function download(name: string, data: BlobPart, type: string) { diff --git a/web/src/ui/site.ts b/web/src/ui/site.ts new file mode 100644 index 00000000..91589885 --- /dev/null +++ b/web/src/ui/site.ts @@ -0,0 +1,34 @@ +/** + * Webseiten der Welten auf visucode.de: visustruct.visucode.de, visubot.visucode.de, visuobject.visucode.de. + * Jede Subdomain hat ihre eigene Startseite (/de/, /en/, /pt/ …) und eine eigene Kopie der Web-App unter /app/. + */ +export type SiteWorld = 'visustruct' | 'visubot' | 'visuobject' + +export const SITE_DOMAIN = 'visucode.de' + +/** Welt der Subdomain, auf der die App gerade läuft (z. B. `visubot` auf visubot.visucode.de), sonst `undefined`. */ +export function hostWorld(host: string = location.hostname): SiteWorld | undefined { + const m = /^(visustruct|visubot|visuobject)\.visucode\.de$/.exec(host.toLowerCase()) + return m ? (m[1] as SiteWorld) : undefined +} + +/** Sprachordner der Webseite zur App-Sprache (die Seiten gibt es auf Deutsch, Englisch und Portugiesisch). */ +export function siteLanguage(code: string): 'de' | 'en' | 'pt' { + return code === 'pt-PT' ? 'pt' : code === 'de' ? 'de' : 'en' +} + +/** + * Startseite einer Welt, auf Wunsch mit Abschnitt (#contact, #privacy). + * Läuft die App unter /app/ auf der Subdomain dieser Welt, relativ (`../de/index.html`), sonst absolut. + */ +export function worldHomeURL( + world: SiteWorld, + languageCode: string, + section?: string, + where: { hostname: string; pathname: string } = location, +): string { + const lang = siteLanguage(languageCode) + const hash = section ? `#${section}` : '' + const local = hostWorld(where.hostname) === world && /\/app\/(index\.html)?$/.test(where.pathname) + return local ? `../${lang}/index.html${hash}` : `https://${world}.${SITE_DOMAIN}/${lang}/${hash}` +} diff --git a/web/test/site.test.ts b/web/test/site.test.ts new file mode 100644 index 00000000..955875e9 --- /dev/null +++ b/web/test/site.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest' +import { hostWorld, siteLanguage, worldHomeURL } from '../src/ui/site' + +describe('Webseiten auf visucode.de', () => { + it('erkennt die Welt an der Subdomain', () => { + expect(hostWorld('visubot.visucode.de')).toBe('visubot') + expect(hostWorld('VisuStruct.visucode.de')).toBe('visustruct') + expect(hostWorld('visuobject.visucode.de')).toBe('visuobject') + expect(hostWorld('visucode.de')).toBeUndefined() + expect(hostWorld('localhost')).toBeUndefined() + expect(hostWorld('visubot.visucode.de.example.com')).toBeUndefined() + }) + + it('nimmt de, en oder pt als Sprachordner', () => { + expect(siteLanguage('de')).toBe('de') + expect(siteLanguage('pt-PT')).toBe('pt') + expect(siteLanguage('fr')).toBe('en') + }) + + it('verlinkt die Startseite relativ nur auf der eigenen Subdomain', () => { + const bot = { hostname: 'visubot.visucode.de', pathname: '/app/index.html' } + expect(worldHomeURL('visubot', 'de', undefined, bot)).toBe('../de/index.html') + expect(worldHomeURL('visubot', 'pt-PT', 'privacy', bot)).toBe('../pt/index.html#privacy') + expect(worldHomeURL('visustruct', 'de', 'contact', bot)).toBe('https://visustruct.visucode.de/de/#contact') + const preview = { hostname: 'localhost', pathname: '/' } + expect(worldHomeURL('visuobject', 'en', undefined, preview)).toBe('https://visuobject.visucode.de/en/') + }) +}) diff --git a/website/app/assets/flowApp-C5bsta4X.js b/website/app/assets/flowApp-Dp3QSP_8.js similarity index 54% rename from website/app/assets/flowApp-C5bsta4X.js rename to website/app/assets/flowApp-Dp3QSP_8.js index b36f264b..28deecaa 100644 --- a/website/app/assets/flowApp-C5bsta4X.js +++ b/website/app/assets/flowApp-Dp3QSP_8.js @@ -1,7 +1,7 @@ -var dt=Object.defineProperty;var lt=(n,t,e)=>t in n?dt(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var y=(n,t,e)=>lt(n,typeof t!="symbol"?t+"":t,e);import{t as h,g as ct,i as I,w as ht,n as ut,f as ft,o as G,q as pt,u as gt,v as wt,x as vt,y as mt,l as xt}from"./index-ByOt241d.js";const et=["start","anweisung","ein","verzweigung","unterprogramm","ende"],m=20,st={start:"#d1f2d9",ende:"#d1f2d9",anweisung:"#e5f0ff",ein:"#f2e6ff",verzweigung:"#fff4d6",unterprogramm:"#e5f0ff"},H=16,yt=170;function bt(n,t,e){const i=[];for(const s of n.split(` -`)){let o="";for(const r of s.split(/\s+/).filter(Boolean)){const a=o?`${o} ${r}`:r;o&&e(a)>t?(i.push(o),o=r):o=a}i.push(o)}return i.length?i:[""]}const q=n=>Math.round(n/m)*m;function C(n,t){const e=bt(n.text,yt,t),i=Math.max(0,...e.map(t)),s=e.length*H;let o,r;if(n.shape==="verzweigung")o=Math.max(140,i*1.7+30),r=Math.max(80,s*1.8+24);else{const a=n.shape==="ein"?44:n.shape==="unterprogramm"?40:n.shape==="anweisung"?24:36;o=Math.max(n.shape==="start"||n.shape==="ende"?100:120,i+a),r=Math.max(40,s+18)}return{x:n.x,y:n.y,w:Math.ceil(o/m)*m,h:Math.ceil(r/m)*m,lines:e}}function V(n){return n==="ende"?[]:n==="verzweigung"?["ja","nein"]:["out"]}const D=n=>n!=="start";function P(n,t,e){var s;if(e==="out")return"bottom";const i=((s=n.yesRight)==null?void 0:s.includes(t.id))??!1;return e==="ja"===i?"right":"bottom"}function F(n,t){return t==="bottom"?[n.x,n.y+n.h/2]:[n.x+n.w/2,n.y]}const _t=n=>[n.x,n.y-n.h/2];function $t(n,t,e,i=0){const[s,o]=F(n,t),[r,a]=_t(e),d=m,u=Math.max(n.x+n.w/2,e.x+e.w/2)+d*(1.5+i);if(t==="bottom"){if(a>=o+d){if(s===r)return[[s,o],[r,a]];const l=o+d;return[[s,o],[s,l],[r,l],[r,a]]}return[[s,o],[s,o+d],[u,o+d],[u,a-d],[r,a-d],[r,a]]}const p=e.x-e.w/2;if(p>=s+d&&Math.abs(e.y-o)${Ne(p("codegen_generated_hint"))}
- `;const e=a=>this.element.querySelector(a);this.codeView=e(".code-view"),this.javaModeRow=e(".java-mode"),this.runButton=e("[data-act=run]"),this.saveButton=e("[data-act=save]"),this.copyButton=e("[data-act=copy]"),this.runner=e(".runner"),this.runOutput=e(".runner-out"),this.runInput=e(".runner-input"),this.pseudocodeBox=e("[data-opt=pseudocode]"),this.pseudocodeHint=e(".pseudocode-hint"),this.pseudocodeBox.addEventListener("change",()=>this.setPseudocode(this.pseudocodeBox.checked)),e(".code-close").addEventListener("click",()=>this.onClose());for(const a of this.element.querySelectorAll("[data-target]"))a.addEventListener("click",()=>{this.target=a.dataset.target,ma(yn.target,this.target),this.refresh()});for(const a of this.element.querySelectorAll("[data-java-mode]"))a.addEventListener("click",()=>{this.javaMode=a.dataset.javaMode,ma(yn.javaMode,this.javaMode),this.refresh()});const t=e("[data-opt=comments]");t.checked=this.comments,t.addEventListener("change",()=>{this.comments=t.checked,ma(yn.comments,String(this.comments)),this.refresh()});const n=e("[data-opt=emptyElse]");n.checked=this.emptyElse,n.addEventListener("change",()=>{this.emptyElse=n.checked,ma(yn.emptyElse,String(this.emptyElse)),this.refresh()}),this.copyButton.addEventListener("click",()=>this.copy()),this.saveButton.addEventListener("click",()=>{const a=rr(this.classStem()),s=Fu(this.currentDocument(),this.classStem(),this.options());this.saveFile(`${a}.java`,s)}),this.runButton.addEventListener("click",()=>this.run()),e("[data-act=stop]").addEventListener("click",()=>this.stopRun(!1)),e("[data-act=cancel]").addEventListener("click",()=>this.answer(null)),this.runInput.addEventListener("submit",a=>{a.preventDefault(),this.answer(this.runInput.querySelector("input").value)})}async copy(){var t;let e=!1;try{await navigator.clipboard.writeText(this.code),e=!0}catch{const n=document.createRange();n.selectNodeContents(this.codeView);const a=getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(n),e=((t=document.execCommand)==null?void 0:t.call(document,"copy"))??!1}this.copyButton.textContent=p(e?"web_copied_check":"web_copy_manual"),setTimeout(()=>this.copyButton.textContent=p("codegen_copy"),2e3)}run(){this.stopRun(!0),this.runner.hidden=!1,this.runOutput.textContent="",this.outputLines=[],this.droppedLines=0,this.runOutput.classList.remove("error");const e=rx(this.code),t=n=>this.onRunnerMessage(n);try{const n=URL.createObjectURL(new Blob([ox],{type:"text/javascript"})),a=new Worker(n);URL.revokeObjectURL(n),a.onmessage=s=>t(s.data),a.onerror=s=>{s.preventDefault(),t({type:"error",text:s.message||p("web_run_error")})},a.postMessage({type:"run",code:e}),this.worker=a}catch{this.runInPage(e,t)}this.setRunning(!0)}runInPage(e,t){const n={log:(...r)=>t({type:"log",lines:[r.map(o=>typeof o=="string"?o:JSON.stringify(o)).join(" ")]})},a=r=>new Promise((o,l)=>{this.pendingAnswer=u=>u===null?l(new Error(sg())):o(u),t({type:"prompt",text:r})}),s=(async()=>{}).constructor;new s("__visuStructPrompt","console",e)(a,n).then(()=>t({type:"done"})).catch(r=>t({type:"error",text:String(r)}))}onRunnerMessage(e){switch(e.type){case"log":this.appendOutput(e.lines??[]);break;case"prompt":{this.runInput.hidden=!1,this.runInput.querySelector("label").textContent=e.text??"";const t=this.runInput.querySelector("input");t.value="",t.focus();break}case"error":this.appendOutput([e.text??""]),this.runOutput.classList.add("error"),this.stopRun(!1);break;case"done":this.stopRun(!1);break}}appendOutput(e){this.outputLines.push(...e),this.outputLines.length>Pr&&(this.droppedLines+=this.outputLines.length-Pr,this.outputLines.splice(0,this.outputLines.length-Pr)),this.outputFrame===void 0&&(this.outputFrame=requestAnimationFrame(()=>{this.outputFrame=void 0;const t=this.droppedLines>0?p("web_run_dropped_fmt",this.droppedLines)+` + `;const e=a=>this.element.querySelector(a);this.codeView=e(".code-view"),this.javaModeRow=e(".java-mode"),this.runButton=e("[data-act=run]"),this.saveButton=e("[data-act=save]"),this.copyButton=e("[data-act=copy]"),this.runner=e(".runner"),this.runOutput=e(".runner-out"),this.runInput=e(".runner-input"),this.pseudocodeBox=e("[data-opt=pseudocode]"),this.pseudocodeHint=e(".pseudocode-hint"),this.pseudocodeBox.addEventListener("change",()=>this.setPseudocode(this.pseudocodeBox.checked)),e(".code-close").addEventListener("click",()=>this.onClose());for(const a of this.element.querySelectorAll("[data-target]"))a.addEventListener("click",()=>{this.target=a.dataset.target,ma(yn.target,this.target),this.refresh()});for(const a of this.element.querySelectorAll("[data-java-mode]"))a.addEventListener("click",()=>{this.javaMode=a.dataset.javaMode,ma(yn.javaMode,this.javaMode),this.refresh()});const t=e("[data-opt=comments]");t.checked=this.comments,t.addEventListener("change",()=>{this.comments=t.checked,ma(yn.comments,String(this.comments)),this.refresh()});const n=e("[data-opt=emptyElse]");n.checked=this.emptyElse,n.addEventListener("change",()=>{this.emptyElse=n.checked,ma(yn.emptyElse,String(this.emptyElse)),this.refresh()}),this.copyButton.addEventListener("click",()=>this.copy()),this.saveButton.addEventListener("click",()=>{const a=or(this.classStem()),s=Ru(this.currentDocument(),this.classStem(),this.options());this.saveFile(`${a}.java`,s)}),this.runButton.addEventListener("click",()=>this.run()),e("[data-act=stop]").addEventListener("click",()=>this.stopRun(!1)),e("[data-act=cancel]").addEventListener("click",()=>this.answer(null)),this.runInput.addEventListener("submit",a=>{a.preventDefault(),this.answer(this.runInput.querySelector("input").value)})}async copy(){var t;let e=!1;try{await navigator.clipboard.writeText(this.code),e=!0}catch{const n=document.createRange();n.selectNodeContents(this.codeView);const a=getSelection();a==null||a.removeAllRanges(),a==null||a.addRange(n),e=((t=document.execCommand)==null?void 0:t.call(document,"copy"))??!1}this.copyButton.textContent=p(e?"web_copied_check":"web_copy_manual"),setTimeout(()=>this.copyButton.textContent=p("codegen_copy"),2e3)}run(){this.stopRun(!0),this.runner.hidden=!1,this.runOutput.textContent="",this.outputLines=[],this.droppedLines=0,this.runOutput.classList.remove("error");const e=cx(this.code),t=n=>this.onRunnerMessage(n);try{const n=URL.createObjectURL(new Blob([dx],{type:"text/javascript"})),a=new Worker(n);URL.revokeObjectURL(n),a.onmessage=s=>t(s.data),a.onerror=s=>{s.preventDefault(),t({type:"error",text:s.message||p("web_run_error")})},a.postMessage({type:"run",code:e}),this.worker=a}catch{this.runInPage(e,t)}this.setRunning(!0)}runInPage(e,t){const n={log:(...r)=>t({type:"log",lines:[r.map(o=>typeof o=="string"?o:JSON.stringify(o)).join(" ")]})},a=r=>new Promise((o,l)=>{this.pendingAnswer=u=>u===null?l(new Error(og())):o(u),t({type:"prompt",text:r})}),s=(async()=>{}).constructor;new s("__visuStructPrompt","console",e)(a,n).then(()=>t({type:"done"})).catch(r=>t({type:"error",text:String(r)}))}onRunnerMessage(e){switch(e.type){case"log":this.appendOutput(e.lines??[]);break;case"prompt":{this.runInput.hidden=!1,this.runInput.querySelector("label").textContent=e.text??"";const t=this.runInput.querySelector("input");t.value="",t.focus();break}case"error":this.appendOutput([e.text??""]),this.runOutput.classList.add("error"),this.stopRun(!1);break;case"done":this.stopRun(!1);break}}appendOutput(e){this.outputLines.push(...e),this.outputLines.length>Or&&(this.droppedLines+=this.outputLines.length-Or,this.outputLines.splice(0,this.outputLines.length-Or)),this.outputFrame===void 0&&(this.outputFrame=requestAnimationFrame(()=>{this.outputFrame=void 0;const t=this.droppedLines>0?p("web_run_dropped_fmt",this.droppedLines)+` `:"";this.runOutput.textContent=t+this.outputLines.join(` `)+(this.outputLines.length?` -`:""),this.runOutput.scrollTop=this.runOutput.scrollHeight}))}answer(e){var t;this.runInput.hidden=!0,this.worker?this.worker.postMessage({type:"answer",value:e}):(t=this.pendingAnswer)==null||t.call(this,e),this.pendingAnswer=void 0}stopRun(e){var t;(t=this.worker)==null||t.terminate(),this.worker=void 0,this.pendingAnswer=void 0,this.runInput&&(this.runInput.hidden=!0),e&&this.runner&&(this.runner.hidden=!0),this.setRunning(!1)}setRunning(e){const t=this.element.querySelector("[data-act=stop]");t&&(t.disabled=!e)}}const Me=(i,e=!1)=>``,oe={newFile:Me('${e[Number(a)]}`)}function jn(i){const e=[],t=i.replace(/\r\n/g,`
+${l}`)}Xa=$B(((o=e.find(([l])=>l==="begriffe.md"))==null?void 0:o[1])??"")}function ZL(i){const e=i.map(([a])=>a).filter(a=>/^\d+/.test(a)).sort((a,s)=>Number(/^\d+/.exec(a)[0])-Number(/^\d+/.exec(s)[0])||a.localeCompare(s)),t=new Map,n=new Map;return e.forEach((a,s)=>{t.set(a.replace(/\.md$/,""),s+1);const r=Number(/^\d+/.exec(a)[0]);n.has(r)||n.set(r,s+1)}),{number:t,renumber:n}}function cm(i,e){return e?i.replace(/\b(Lektion(?:en)?|Lessons?|Li[cç](?:ão|ões))(\s+\d+(?:\s*(?:,|bis|und|and|to|a|e|–|-)\s*\d+)*)/gi,(t,n,a)=>n+a.replace(/\d+/g,s=>String(e.get(Number(s))??s))):i}Cs("en");function kg(i,e){return _1==="de"?i.get(e)??i.get(`en/${e}`):(_1==="en"?void 0:i.get(`${_1}/${e}`))??i.get(`en/${e}`)??i.get(e)}const Sg=(i,e)=>i.slice(i.indexOf(e)+e.length),BL=new Map(Object.entries(OL).map(([i,e])=>[Sg(i,"/diagramme/"),e]));function ui(i){const e=kg(BL,i);return e===void 0?void 0:Kl(e)}const LL=new Map(Object.entries(DL).map(([i,e])=>[Sg(i,"/bilder/"),e]));function pa(i){return kg(LL,i)}const WL=new Map(Object.entries(ML).map(([i,e])=>[Ig(i).replace(/\.txt$/,""),e])),dm=new Map;function Ka(i){const e=WL.get(i);if(e===void 0)return;let t=dm.get(i);return t||dm.set(i,t=Ix(e)),t}const Tg=i=>i.replace(/&/g,"&").replace(//g,">").replace(/"/g,""");function _e(i){const e=[];let t=Tg(i).replace(/`([^`]+)`/g,(n,a)=>(e.push(a),`\0${e.length-1}\0`));return t=t.replace(/\*\*(.+?)\*\*/g,"$1").replace(/(^|[^*])\*([^*\s][^*]*?)\*/g,"$1$2").replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(n,a,s)=>{const r=/^\?(visustruct|visubot)(&lektion=[\w-]+)?$/.test(s),o=r||/^(https?:|mailto:|#|\.{0,2}\/)/.test(s)?s:"#",l=r||/^https?:/.test(o)?' target="_blank" rel="noopener noreferrer"':"";return`${a}`}).replace(/\[([^\]]+)\]\{\.(blau|orange|gruen|gelb|rosa)\}/g,'$1').replace(/\[([^\]]+)\]\{(?:teil|part)=([\w,]+)\}/g,'$1'),t.replace(/\u0000(\d+)\u0000/g,(n,a)=>`${e[Number(a)]}`)}function jn(i){const e=[],t=i.replace(/\r\n/g,`
`).split(`
-`);let n=0;for(;n${kg(c.join(`
+`);let n=0;for(;n${Tg(c.join(`
`))}`);continue}const s=/^(#{2,4})\s+(.*)$/.exec(a);if(s){const o=s[1].length,l=/\s*\{\.([a-z][a-z-]*)\}$/.exec(s[2]),u=l?s[2].slice(0,l.index):s[2];e.push(`${_e(u)} `),n++;continue}if(/^\s*([-*]|\d+\.)\s+/.test(a)){const o=/^\s*\d+\./.test(a),l=[];for(;n${_e(u)}`)}e.push(o?`${l.join("")}
`:`${l.join("")}
`);continue}if(a.startsWith("|")&&/^\|?[\s:|-]*-{3,}[\s:|-]*$/.test(t[n+1]??"")){const o=m=>m.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(c=>_e(c.trim())),l=o(a);n+=2;const u=[];for(;n${l.map(m=>`${m} `).join("")} ${u.map(m=>`${m.map(c=>`${c} `).join("")} `).join("")}
`);continue}if(a.startsWith(">")){const o=[];for(;n");)o.push(t[n++].replace(/^>\s?/,""));e.push(``);continue}const r=[];for(;n|\||\s*([-*]|\d+\.)\s+)/.test(t[n]);)r.push(t[n++].trim());e.push(`${_e(r.join(" "))}
`)}return e.join(`
-`)}const fa=""+new URL("ludwig-Cus1i402.webp",import.meta.url).href,qo="f4ecc8e489ae7865308288c7d0fa313333cf2be3ff529b23bc214bee010310e0",v0="visustruct.learn.teacher";let y0=!1;function dm(){if(y0)return!0;try{return localStorage.getItem(v0)===qo}catch{return!1}}async function DL(i){const e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(i));return[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function ZL(i){let e=!1;try{e=await DL(i.trim())===qo}catch{return!1}if(e){y0=!0;try{localStorage.setItem(v0,qo)}catch{}}return e}function BL(){y0=!1;try{localStorage.removeItem(v0)}catch{}}function Sg(i,e,t=!1){const n=document.createElement("figure");n.className=t?"learn-file written":"learn-file";const a=document.createElement("figcaption"),s=document.createElement("span");s.className="learn-file-icon",s.setAttribute("aria-hidden","true"),s.textContent="📄",a.append(s,t?p("web_sim_written_file_fmt",i):i);const r=document.createElement("pre");return r.className="learn-file-text",r.dir="ltr",e.replace(/\n$/,"").split(`
+`)}const fa=""+new URL("ludwig-Cus1i402.webp",import.meta.url).href,qo="f4ecc8e489ae7865308288c7d0fa313333cf2be3ff529b23bc214bee010310e0",y0="visustruct.learn.teacher";let w0=!1;function hm(){if(w0)return!0;try{return localStorage.getItem(y0)===qo}catch{return!1}}async function EL(i){const e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(i));return[...new Uint8Array(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function NL(i){let e=!1;try{e=await EL(i.trim())===qo}catch{return!1}if(e){w0=!0;try{localStorage.setItem(y0,qo)}catch{}}return e}function JL(){w0=!1;try{localStorage.removeItem(y0)}catch{}}function jg(i,e,t=!1){const n=document.createElement("figure");n.className=t?"learn-file written":"learn-file";const a=document.createElement("figcaption"),s=document.createElement("span");s.className="learn-file-icon",s.setAttribute("aria-hidden","true"),s.textContent="📄",a.append(s,t?p("web_sim_written_file_fmt",i):i);const r=document.createElement("pre");return r.className="learn-file-text",r.dir="ltr",e.replace(/\n$/,"").split(`
`).forEach((l,u)=>{const m=document.createElement("span");m.className="ln",m.textContent=String(u+1),r.append(m,l+`
-`)}),n.append(a,r),n}function Tg(i){return[...i].map(([e,t])=>Sg(e,t,!0))}function n1(i){switch(i.kind){case"finished":return p("sim_notice_finished");case"infiniteLoopWithoutBody":return p("sim_notice_infinite_loop_empty");case"unsupportedStatement":return p("sim_notice_unsupported_statement_fmt",i.text);case"invalidExpression":return p("sim_notice_invalid_expression_fmt",i.text);case"unknownVariable":return i.similar?p("web_sim_unknown_variable_case_fmt",i.text,i.similar):p("sim_notice_unknown_variable_fmt",i.text);case"divisionByZero":return p("sim_notice_division_by_zero");case"wholeNumberExpected":return p("sim_notice_whole_number_expected");case"numberExpected":return p("sim_notice_number_expected");case"booleanExpected":return p("sim_notice_boolean_expected");case"subprogramNotFound":return p("sim_notice_subprogram_not_found_fmt",i.text);case"callTooDeep":return p("sim_notice_call_too_deep");case"callArguments":return p("web_sim_call_arguments_fmt",i.text);case"missingReturn":return p("web_sim_missing_return_fmt",i.text);case"fileNotFound":return p("web_sim_file_not_found_fmt",i.text);case"endOfFile":return p("web_sim_end_of_file_fmt",i.text);case"nullValue":return p("web_sim_null_value_fmt",i.text);case"other":return i.text}}const De=i=>i.replace(/&/g,"&").replace(//g,">").replace(/"/g,"""),hm=["0.2","0.5","1.0","1.5","2.0"],LL=i=>Number(i).toLocaleString(r1()==="java"?"en":r1(),{minimumFractionDigits:1}),Mr="visustruct.simulation.stepDelay",gm="visustruct.simulation.highlightMode";function Dr(i){try{return localStorage.getItem(i)}catch{return null}}function pm(i,e){try{localStorage.setItem(i,e)}catch{}}class WL{constructor(e,t,n=()=>{},a=()=>{},s=()=>{}){y(this,"element");y(this,"engine");y(this,"isPlaying",!1);y(this,"playTimer");y(this,"wasPlayingBeforeInput",!1);y(this,"delay",hm.includes(Dr(Mr)??"")?Dr(Mr):"0.5");y(this,"highlightMode",Dr(gm)==="nextToExecute"?"nextToExecute":"lastExecuted");y(this,"buttons");y(this,"inputSection");y(this,"trace");y(this,"variables");y(this,"output");y(this,"transcript",[]);y(this,"printed",0);y(this,"notice");y(this,"editButton");y(this,"robot");y(this,"liveBusy",!1);this.currentDocument=e,this.onHighlight=t,this.findSubprogram=n,this.onEdit=a,this.onTranscript=s,this.engine=new Ai(e(),n),this.element=document.createElement("aside"),this.element.className="simpanel",this.build()}setRobot(e){var t;this.robot!==e&&((t=this.robot)==null||t.element.remove(),this.robot=e,e&&(this.element.querySelector("section").after(e.element),e.onWorldChange=()=>this.restartEngine(),e.reset()))}showRobot(){var e;(e=this.robot)==null||e.show()}begin(){this.pause(),this.restartEngine(),this.showRobot()}end(){this.pause()}step(){var n,a,s;if((n=this.robot)!=null&&n.live){this.stepLive();return}if(!this.engine.canStep){this.pause();return}const e=this.isPlaying,t=this.engine.currentStepPath;(a=this.robot)==null||a.prepare(this.engine),this.engine.step(),(s=this.robot)==null||s.follow(this.engine.state.robotActions,e?Number(this.delay)*850:450),this.afterStep(e,t)}async stepLive(){if(this.liveBusy)return;if(!this.engine.canStep){this.pause();return}this.liveBusy=!0;const e=this.robot,t=this.isPlaying,n=this.engine.currentStepPath;try{await e.prepareLive(this.engine,H3(JSON.stringify(this.currentDocument()))),this.engine.step(),e.follow(this.engine.state.robotActions,450),await e.drive(this.engine.state.robotActions)}catch(a){e.liveFailed(a),this.isPlaying=!1}finally{this.liveBusy=!1}this.afterStep(t,n)}afterStep(e,t){this.collectOutput(),this.highlightMode==="nextToExecute"&&this.engine.canStep?this.onHighlight(this.engine.currentStepPath):this.onHighlight(t??this.engine.currentStepPath),this.engine.state.inputRequest&&e&&(this.wasPlayingBeforeInput=!0),this.engine.canStep||this.pause(),this.update()}reset(){this.pause(),this.restartEngine()}play(){if(this.isPlaying||!this.engine.canStep)return;this.isPlaying=!0;const e=async()=>{var t;this.playTimer=void 0,this.isPlaying&&((t=this.robot)!=null&&t.live?await this.stepLive():this.step(),this.isPlaying&&this.engine.canStep?this.playTimer=window.setTimeout(()=>void e(),Number(this.delay)*1e3):(this.isPlaying=!1,this.update()))};e()}pause(){this.playTimer!==void 0&&window.clearTimeout(this.playTimer),this.playTimer=void 0,this.isPlaying=!1,this.update()}submitInput(e){var s,r;const t=this.isPlaying||this.wasPlayingBeforeInput;this.pause();const n=((s=this.engine.state.inputRequest)==null?void 0:s.prompt)??"",a=(r=this.engine.state.inputRequest)==null?void 0:r.continuesLine;if(this.engine.provideInput(e.value),!this.engine.state.inputRequest){const o=this.transcript[this.transcript.length-1];a&&o&&o.typed===void 0?o.typed=e.value:this.transcript.push({text:n?`${n} `:"",typed:e.value}),e.value=""}this.onHighlight(this.engine.currentStepPath),t&&this.engine.canStep&&(this.wasPlayingBeforeInput=!1,this.play()),this.update()}restartEngine(){var e;this.engine=new Ai(this.currentDocument(),this.findSubprogram),this.transcript=[],this.printed=0,this.wasPlayingBeforeInput=!1,(e=this.robot)==null||e.reset(),this.onHighlight(this.engine.currentStepPath),this.update()}build(){this.element.innerHTML=`
+`)}),n.append(a,r),n}function _g(i){return[...i].map(([e,t])=>jg(e,t,!0))}function n1(i){switch(i.kind){case"finished":return p("sim_notice_finished");case"infiniteLoopWithoutBody":return p("sim_notice_infinite_loop_empty");case"unsupportedStatement":return p("sim_notice_unsupported_statement_fmt",i.text);case"invalidExpression":return p("sim_notice_invalid_expression_fmt",i.text);case"unknownVariable":return i.similar?p("web_sim_unknown_variable_case_fmt",i.text,i.similar):p("sim_notice_unknown_variable_fmt",i.text);case"divisionByZero":return p("sim_notice_division_by_zero");case"wholeNumberExpected":return p("sim_notice_whole_number_expected");case"numberExpected":return p("sim_notice_number_expected");case"booleanExpected":return p("sim_notice_boolean_expected");case"subprogramNotFound":return p("sim_notice_subprogram_not_found_fmt",i.text);case"callTooDeep":return p("sim_notice_call_too_deep");case"callArguments":return p("web_sim_call_arguments_fmt",i.text);case"missingReturn":return p("web_sim_missing_return_fmt",i.text);case"fileNotFound":return p("web_sim_file_not_found_fmt",i.text);case"endOfFile":return p("web_sim_end_of_file_fmt",i.text);case"nullValue":return p("web_sim_null_value_fmt",i.text);case"other":return i.text}}const De=i=>i.replace(/&/g,"&").replace(//g,">").replace(/"/g,"""),gm=["0.2","0.5","1.0","1.5","2.0"],FL=i=>Number(i).toLocaleString(r1()==="java"?"en":r1(),{minimumFractionDigits:1}),Dr="visustruct.simulation.stepDelay",pm="visustruct.simulation.highlightMode";function Zr(i){try{return localStorage.getItem(i)}catch{return null}}function fm(i,e){try{localStorage.setItem(i,e)}catch{}}class RL{constructor(e,t,n=()=>{},a=()=>{},s=()=>{}){y(this,"element");y(this,"engine");y(this,"isPlaying",!1);y(this,"playTimer");y(this,"wasPlayingBeforeInput",!1);y(this,"delay",gm.includes(Zr(Dr)??"")?Zr(Dr):"0.5");y(this,"highlightMode",Zr(pm)==="nextToExecute"?"nextToExecute":"lastExecuted");y(this,"buttons");y(this,"inputSection");y(this,"trace");y(this,"variables");y(this,"output");y(this,"transcript",[]);y(this,"printed",0);y(this,"notice");y(this,"editButton");y(this,"robot");y(this,"liveBusy",!1);this.currentDocument=e,this.onHighlight=t,this.findSubprogram=n,this.onEdit=a,this.onTranscript=s,this.engine=new Ai(e(),n),this.element=document.createElement("aside"),this.element.className="simpanel",this.build()}setRobot(e){var t;this.robot!==e&&((t=this.robot)==null||t.element.remove(),this.robot=e,e&&(this.element.querySelector("section").after(e.element),e.onWorldChange=()=>this.restartEngine(),e.reset()))}showRobot(){var e;(e=this.robot)==null||e.show()}begin(){this.pause(),this.restartEngine(),this.showRobot()}end(){this.pause()}step(){var n,a,s;if((n=this.robot)!=null&&n.live){this.stepLive();return}if(!this.engine.canStep){this.pause();return}const e=this.isPlaying,t=this.engine.currentStepPath;(a=this.robot)==null||a.prepare(this.engine),this.engine.step(),(s=this.robot)==null||s.follow(this.engine.state.robotActions,e?Number(this.delay)*850:450),this.afterStep(e,t)}async stepLive(){if(this.liveBusy)return;if(!this.engine.canStep){this.pause();return}this.liveBusy=!0;const e=this.robot,t=this.isPlaying,n=this.engine.currentStepPath;try{await e.prepareLive(this.engine,Y3(JSON.stringify(this.currentDocument()))),this.engine.step(),e.follow(this.engine.state.robotActions,450),await e.drive(this.engine.state.robotActions)}catch(a){e.liveFailed(a),this.isPlaying=!1}finally{this.liveBusy=!1}this.afterStep(t,n)}afterStep(e,t){this.collectOutput(),this.highlightMode==="nextToExecute"&&this.engine.canStep?this.onHighlight(this.engine.currentStepPath):this.onHighlight(t??this.engine.currentStepPath),this.engine.state.inputRequest&&e&&(this.wasPlayingBeforeInput=!0),this.engine.canStep||this.pause(),this.update()}reset(){this.pause(),this.restartEngine()}play(){if(this.isPlaying||!this.engine.canStep)return;this.isPlaying=!0;const e=async()=>{var t;this.playTimer=void 0,this.isPlaying&&((t=this.robot)!=null&&t.live?await this.stepLive():this.step(),this.isPlaying&&this.engine.canStep?this.playTimer=window.setTimeout(()=>void e(),Number(this.delay)*1e3):(this.isPlaying=!1,this.update()))};e()}pause(){this.playTimer!==void 0&&window.clearTimeout(this.playTimer),this.playTimer=void 0,this.isPlaying=!1,this.update()}submitInput(e){var s,r;const t=this.isPlaying||this.wasPlayingBeforeInput;this.pause();const n=((s=this.engine.state.inputRequest)==null?void 0:s.prompt)??"",a=(r=this.engine.state.inputRequest)==null?void 0:r.continuesLine;if(this.engine.provideInput(e.value),!this.engine.state.inputRequest){const o=this.transcript[this.transcript.length-1];a&&o&&o.typed===void 0?o.typed=e.value:this.transcript.push({text:n?`${n} `:"",typed:e.value}),e.value=""}this.onHighlight(this.engine.currentStepPath),t&&this.engine.canStep&&(this.wasPlayingBeforeInput=!1,this.play()),this.update()}restartEngine(){var e;this.engine=new Ai(this.currentDocument(),this.findSubprogram),this.transcript=[],this.printed=0,this.wasPlayingBeforeInput=!1,(e=this.robot)==null||e.reset(),this.onHighlight(this.engine.currentStepPath),this.update()}build(){this.element.innerHTML=`
${De(p("simulation_controls"))}