diff --git a/CHANGELOG.md b/CHANGELOG.md index 84499116..70c09f69 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ The format is loosely inspired by Keep a Changelog. ### Added +- **Web 0.12.3, `System.out.print` in VisuStruct:** `System.out.print(…)` (without a new line) works in the simulation, in Programmieren and in the code export (JavaScript `process.stdout.write`, Python `print(…, end="")`); an input right after an output no longer shows the extra question `name:`, after `System.out.print` it stays on the same line (#187). - **Web 0.12.2, code colours like Eclipse:** string literals are blue instead of red (red only marks errors), keywords purple bold including `int`, `boolean`, `true`, `false`, `null`, comments green, numbers ochre, class names black. Applies to Programmieren and VisuObject. - **Web 0.12.1, missing Scanner/import is an error:** in Programmieren, `eingabe.next()` without `Scanner eingabe = new Scanner(System.in);` is marked red and ▶ does not start (like javac); the VisuObject debugger now reports a missing `import java.util.…` for Scanner, ArrayList, HashMap, Arrays etc. (#188) - **Web 0.12.0, VisuObject sequence diagram:** a third tab next to class and object diagram draws a sequence diagram live from the debugger run: a lifeline per object (`s1 : Spieler`) or class (static), call arrows with arguments, dashed return arrows with the value, «create» arrows to boxes that start where the object is created, activation bars, the latest arrow in yellow while paused; clicking an arrow shows the line in the code. diff --git a/web/package-lock.json b/web/package-lock.json index 85d0b3bf..757e6e5e 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -1,12 +1,12 @@ { "name": "visustruct-web", - "version": "0.12.2", + "version": "0.12.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "visustruct-web", - "version": "0.12.2", + "version": "0.12.3", "dependencies": { "@codemirror/autocomplete": "^6.20.4", "@codemirror/commands": "^6.11.1", diff --git a/web/package.json b/web/package.json index c4fc57b7..813c3935 100644 --- a/web/package.json +++ b/web/package.json @@ -1,7 +1,7 @@ { "name": "visustruct-web", "private": true, - "version": "0.12.2", + "version": "0.12.3", "type": "module", "scripts": { "dev": "vite", diff --git a/web/src/core/codeGenerator.ts b/web/src/core/codeGenerator.ts index 4afedc2d..38b60594 100644 --- a/web/src/core/codeGenerator.ts +++ b/web/src/core/codeGenerator.ts @@ -558,6 +558,16 @@ function emitPrintLineIfNeeded( intVariables: Set, stringVariables: Set, ): string | undefined { + // `System.out.print(…)`: Ausgabe ohne neue Zeile. + const print = /^System\s*\.\s*out\s*\.\s*print\s*\(([\s\S]*)\)$/.exec(stripTrailingSemicolon(raw).trim()) + if (print) { + const value = print[1].trim() + switch (target) { + case 'java': return sp(indent) + 'System.out.print(' + value + ');\n' + case 'javascript': return sp(indent) + 'process.stdout.write(String(' + value + '));\n' + case 'python': return sp(indent) + 'print(' + (value === '' ? '' : pythonConcatenation(value, intVariables, stringVariables) + ', ') + 'end="")\n' + } + } const expr = expressionAfterOutputDiagramPrefix(raw) if (expr === undefined) { // Leere Ausgabe (`output:` ohne Text): eine Leerzeile. diff --git a/web/src/core/simulation.ts b/web/src/core/simulation.ts index 4965d15e..7e747d3b 100644 --- a/web/src/core/simulation.ts +++ b/web/src/core/simulation.ts @@ -63,6 +63,8 @@ export interface InputRequest { variableName: string valueType: SimValueType prompt: string + /** Wie in Java hinter `System.out.print("Note: ")`: Die Eingabe steht in derselben Zeile wie diese Ausgabe. */ + continuesLine?: boolean } /** Meldungen der Simulation, unabhängig von der Sprache. */ @@ -94,6 +96,8 @@ export interface SimState { stepIndex: number variables: Map outputLines: string[] + /** Die letzte Ausgabe war `System.out.print(…)`: Die nächste Ausgabe schreibt in derselben Zeile weiter. */ + outputLineOpen?: boolean inputRequest?: InputRequest /** Fehler zur letzten Eingabe (z. B. keine Zahl). */ inputErrorNotice?: SimNotice @@ -977,6 +981,7 @@ export class SimulationEngine { reset(document?: VSDocument): void { if (document) this.steps = buildSteps(document.elements) this.state = freshState() + this.afterOutput = false this.nextFrame = 1 this.callDepth = 0 this.frames.clear() @@ -1300,21 +1305,34 @@ export class SimulationEngine { // MARK: Anweisungen + /** Die letzte Anweisung war eine Ausgabe (für die Frage einer folgenden Eingabe). */ + private afterOutput = false + private executeStatement(rawText: string): void { const state = this.state const text = rawText.trim() const lower = text.toLowerCase() + const afterOutput = this.afterOutput + this.afterOutput = false if (lower.startsWith('input:')) { - state.inputRequest = this.parseInputRequest(text) + state.inputRequest = this.parseInputRequest(text, afterOutput) + // Mit Enter endet die Zeile. + state.outputLineOpen = false state.inputErrorNotice = undefined return } - if (lower.startsWith('output:') || lower.startsWith('print:')) { - const expression = text.slice(lower.startsWith('output:') ? 'output:'.length : 'print:'.length) + // `System.out.print(…)` schreibt ohne neue Zeile, `System.out.println(…)` wie `output:`. + const javaOut = /^System\s*\.\s*out\s*\.\s*(println|print)\s*\(([\s\S]*)\)\s*;?$/u.exec(text) + if (lower.startsWith('output:') || lower.startsWith('print:') || javaOut) { + const expression = javaOut ? javaOut[2] : text.slice(lower.startsWith('output:') ? 'output:'.length : 'print:'.length) const rendered = this.peek(() => this.renderOutputExpression(expression)) - const output = this.evaluateOutputExpression(expression) - state.outputLines.push(output) + // `println()` ohne Text: nur eine neue Zeile. + const output = expression.trim() === '' ? '' : this.evaluateOutputExpression(expression) + if (state.outputLineOpen && state.outputLines.length) state.outputLines[state.outputLines.length - 1] += output + else state.outputLines.push(output) + state.outputLineOpen = javaOut?.[1] === 'print' + this.afterOutput = true state.lastTrace = `${rendered} -> ${output}` return } @@ -1554,7 +1572,12 @@ export class SimulationEngine { return { variableName: name, valueType } } - private parseInputRequest(text: string): InputRequest { + /** + * Ohne eigene Frage steht `name:` vor der Eingabe. Kommt direkt davor eine Ausgabe, fragt diese schon (wie in Java, + * z. B. `System.out.println("Note für Fach " + fach[i])`): Dann steht nichts davor, nach `System.out.print(…)` steht + * die Eingabe in derselben Zeile. + */ + private parseInputRequest(text: string, afterOutput = false): InputRequest { const afterColon = text.slice('input:'.length).trim() // Wie Swift `split(maxSplits: 2)`: zwei Wörter, dann der Rest. const match = /^(\S+)(?:\s+(\S+))?(?:\s+([\s\S]*))?$/u.exec(afterColon) @@ -1575,6 +1598,9 @@ export class SimulationEngine { } if (!isAssignableTarget(target)) throw unsupported(text) const prompt = unquotedString(promptRaw) ?? promptRaw + if (prompt === '' && afterOutput) { + return this.state.outputLineOpen ? { variableName: target, valueType, prompt: '', continuesLine: true } : { variableName: target, valueType, prompt: '' } + } return { variableName: target, valueType, prompt: prompt === '' ? `${target}:` : prompt } } diff --git a/web/src/ui/codePanel.ts b/web/src/ui/codePanel.ts index 648bade1..3a9a6d16 100644 --- a/web/src/ui/codePanel.ts +++ b/web/src/ui/codePanel.ts @@ -50,20 +50,33 @@ export function javaScriptRunnerCode(js: string): string { const workerSource = ` let answer let lines = [] -const flush = () => { +// Text von \`process.stdout.write\` ohne neue Zeile (wie \`System.out.print\`). +let partial = '' +const flush = (all) => { + if (all && partial) { + lines.push(partial) + partial = '' + } if (lines.length) postMessage({ type: 'log', lines }) lines = [] } const send = (type, text) => { - flush() + flush(true) postMessage({ type, text }) } const fmt = (a) => (typeof a === 'string' ? a : JSON.stringify(a)) // Ausgaben gesammelt senden, sonst bremsen viele kleine Nachrichten (z. B. in Endlosschleifen) die Seite aus. console.log = (...args) => { - lines.push(args.map(fmt).join(' ')) + lines.push(partial + args.map(fmt).join(' ')) + partial = '' if (lines.length >= 500) flush() } +const process = { stdout: { write: (text) => { + const parts = (partial + String(text)).split('\\n') + partial = parts.pop() + lines.push(...parts) + if (lines.length >= 500) flush() +} } } setInterval(flush, 50) const __visuStructPrompt = (label) => new Promise((resolve, reject) => { answer = (value) => (value === null ? reject(new Error(${JSON.stringify(cancelMessage())})) : resolve(value)) diff --git a/web/src/ui/liveCodePanel.ts b/web/src/ui/liveCodePanel.ts index 9619f08f..e98d1c73 100644 --- a/web/src/ui/liveCodePanel.ts +++ b/web/src/ui/liveCodePanel.ts @@ -625,13 +625,15 @@ export class LiveCodePanel { } /** `typed`: Eingabezeile mit Frage und der getippten Antwort (farbig). */ - private printNewLines(typed?: { prompt: string; value: string }) { + private printNewLines(typed?: { prompt: string; value: string; continuesLine?: boolean }) { const run = this.run if (!run) return const lines = run.engine.state.outputLines for (; run.printed < lines.length; run.printed++) this.consoleLine(lines[run.printed]) if (typed) { - const div = this.consoleLine(typed.prompt ? `${typed.prompt} ` : '') + // Nach `System.out.print("Note: ")` steht die Eingabe in derselben Zeile. + const last = this.consoleLines.lastElementChild + const div = typed.continuesLine && last instanceof HTMLElement ? last : this.consoleLine(typed.prompt ? `${typed.prompt} ` : '') const value = document.createElement('span') value.className = 'typed' value.textContent = typed.value @@ -671,10 +673,10 @@ export class LiveCodePanel { const run = this.run if (!run?.engine.state.inputRequest) return const field = this.consoleForm.querySelector('input')! - const prompt = run.engine.state.inputRequest.prompt + const { prompt, continuesLine } = run.engine.state.inputRequest run.engine.provideInput(field.value) if (run.engine.state.inputRequest) return this.askInput() - this.printNewLines({ prompt, value: field.value }) + this.printNewLines({ prompt, value: field.value, continuesLine }) field.value = '' this.consoleForm.hidden = true if (!run.stepping) return this.continueRun(false) diff --git a/web/src/ui/simulationPanel.ts b/web/src/ui/simulationPanel.ts index ee3541c8..eb754c26 100644 --- a/web/src/ui/simulationPanel.ts +++ b/web/src/ui/simulationPanel.ts @@ -225,9 +225,12 @@ export class SimulationPanel { const shouldResume = this.isPlaying || this.wasPlayingBeforeInput this.pause() const prompt = this.engine.state.inputRequest?.prompt ?? '' + const continuesLine = this.engine.state.inputRequest?.continuesLine this.engine.provideInput(field.value) if (!this.engine.state.inputRequest) { - this.transcript.push({ text: prompt ? `${prompt} ` : '', typed: field.value }) + const last = this.transcript[this.transcript.length - 1] + if (continuesLine && last && last.typed === undefined) last.typed = field.value + else this.transcript.push({ text: prompt ? `${prompt} ` : '', typed: field.value }) field.value = '' } this.onHighlight(this.engine.currentStepPath) @@ -321,7 +324,7 @@ export class SimulationPanel { const { state, canStep } = this.engine this.onTranscript({ lines: this.transcript, - pending: state.inputRequest?.prompt, + pending: state.inputRequest?.continuesLine ? undefined : state.inputRequest?.prompt, notice: state.notice ? noticeText(state.notice) : undefined, error: state.isHalted, }) diff --git a/web/test/javaParser.test.ts b/web/test/javaParser.test.ts index 2b5059ab..0f0adc5e 100644 --- a/web/test/javaParser.test.ts +++ b/web/test/javaParser.test.ts @@ -7,6 +7,8 @@ import { parseLiveJava } from '../src/core/javaParser' import { documentFromJava, mergeLiveJava, plainLiveJava, type JavaForm } from '../src/core/liveSource' import { ElementType, makeElement, type VSDocument } from '../src/core/model' import { decodeDocument } from '../src/core/xmlCodec' +import { SimulationEngine } from '../src/core/simulation' +import { generateCode } from '../src/core/codeGenerator' import { indentJava } from '../src/core/javaIndent' const labels: LiveLabels = { condition: 'Bedingung', selector: 'Wert', code: 'Dein Code', start: 'Startwert', step: 'Schritt', end: 'Ende' } @@ -152,6 +154,47 @@ describe('Java tippen → Struktogramm', () => { expect(keys('System.out.println("Scanner");')).toEqual([]) }) + it('System.out.print schreibt ohne neue Zeile, auch mit Array-Fach', () => { + const d = doc( + 'int[] intAllgemeinFach = {3, 5};\n' + + 'for (int i = 0; i < intAllgemeinFach.length; i++) {\n' + + ' System.out.print(intAllgemeinFach[i] + ": ");\n' + + ' System.out.println("ok");\n' + + '}\n' + + 'System.out.print("A");\n' + + 'System.out.print("B");\n' + + 'System.out.println();', + ) + const engine = new SimulationEngine(d) + let steps = 0 + while (engine.canStep && steps++ < 1000) engine.step() + expect(engine.message).not.toMatch(/Nicht unterstützte|Unsupported/u) + expect(engine.state.outputLines).toEqual(['3: ok', '5: ok', 'AB']) + const java = generateCode(d, 'java') + expect(java).toContain('System.out.print(intAllgemeinFach[i] + ": ");') + expect(generateCode(d, 'javascript')).toContain('process.stdout.write(String(intAllgemeinFach[i] + ": "));') + expect(generateCode(d, 'python')).toContain('print(str(intAllgemeinFach[i]) + ": ", end="")') + }) + + it('Eingabe nach einer Ausgabe fragt nicht noch einmal nach dem Variablennamen', () => { + const ask = (src: string) => { + const engine = new SimulationEngine(doc(src)) + while (engine.canStep && !engine.state.inputRequest) engine.step() + return { request: engine.state.inputRequest, lines: engine.state.outputLines } + } + const fach = 'String[] fach = {"Mathe"};\nint[] note = new int[1];\nint i = 0;\n' + expect(ask(fach + 'System.out.println("Note für Fach " + fach[i]);\nnote[i] = scanner.nextInt();')).toEqual({ + request: { variableName: 'note[i]', valueType: 'int', prompt: '' }, + lines: ['Note für Fach Mathe'], + }) + expect(ask(fach + 'System.out.print(fach[i] + ": ");\nnote[i] = scanner.nextInt();')).toEqual({ + request: { variableName: 'note[i]', valueType: 'int', prompt: '', continuesLine: true }, + lines: ['Mathe: '], + }) + // Ohne Ausgabe davor bleibt die Frage `name:`. + expect(ask(fach + 'note[i] = scanner.nextInt();').request?.prompt).toBe('note[i]:') + }) + it('Aufruf eines Unterprogramms aus einem anderen Reiter', () => { expect(parse('int y = quadrat(4);', new Set(['quadrat'])).elements[0].type).toBe(ElementType.aufruf) expect(parse('int y = quadrat(4);').elements[0].type).toBe(ElementType.anweisung) diff --git a/website/app/assets/index-BZrdbqtU.js b/website/app/assets/index-D4MtCuvD.js similarity index 97% rename from website/app/assets/index-BZrdbqtU.js rename to website/app/assets/index-D4MtCuvD.js index 899c4e89..514efe60 100644 --- a/website/app/assets/index-BZrdbqtU.js +++ b/website/app/assets/index-D4MtCuvD.js @@ -1,4 +1,4 @@ -var Of=Object.defineProperty;var Af=(i,e,t)=>e in i?Of(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var y=(i,e,t)=>Af(i,typeof e!="symbol"?e+"":e,t);(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const s of a)if(s.type==="childList")for(const r of s.addedNodes)r.tagName==="LINK"&&r.rel==="modulepreload"&&n(r)}).observe(document,{childList:!0,subtree:!0});function t(a){const s={};return a.integrity&&(s.integrity=a.integrity),a.referrerPolicy&&(s.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?s.credentials="include":a.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function n(a){if(a.ep)return;a.ep=!0;const s=t(a);fetch(a.href,s)}})();const Pf="modulepreload",jf=function(i,e){return new URL(i,e).href},j0={},Q=function(e,t,n){let a=Promise.resolve();if(t&&t.length>0){let r=function(m){return Promise.all(m.map(c=>Promise.resolve(c).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};const o=document.getElementsByTagName("link"),l=document.querySelector("meta[property=csp-nonce]"),u=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));a=r(t.map(m=>{if(m=jf(m,n),m in j0)return;j0[m]=!0;const c=m.endsWith(".css"),d=c?'[rel="stylesheet"]':"";if(!!n)for(let f=o.length-1;f>=0;f--){const x=o[f];if(x.href===m&&(!c||x.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${m}"]${d}`))return;const g=document.createElement("link");if(g.rel=c?"stylesheet":Pf,c||(g.as="script"),g.crossOrigin="",g.href=m,u&&g.setAttribute("nonce",u),document.head.appendChild(g),c)return new Promise((f,x)=>{g.addEventListener("load",f),g.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${m}`)))})}))}function s(r){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=r,window.dispatchEvent(o),!o.defaultPrevented)throw r}return a.then(r=>{for(const o of r||[])o.status==="rejected"&&s(o.reason);return e().catch(s)})};var z=(i=>(i[i.anweisung=0]="anweisung",i[i.verzweigung=1]="verzweigung",i[i.fallauswahl=2]="fallauswahl",i[i.forSchleife=3]="forSchleife",i[i.whileSchleife=4]="whileSchleife",i[i.doUntilSchleife=5]="doUntilSchleife",i[i.endlosschleife=6]="endlosschleife",i[i.aussprung=7]="aussprung",i[i.aufruf=8]="aufruf",i[i.leerElement=9]="leerElement",i))(z||{});function Cf(i){return i===3||i===4||i===5||i===6}function Bf(i){return i===1||i===2}function ve(i,e={}){return{type:i,zoomX:0,zoomY:0,textLines:[""],...e}}function Df(i){const e=i.textLines;if(!e.every(t=>t.trim()===""))switch(i.type){case z.forSchleife:return e.length<=1?e:[Mf(e)];case z.verzweigung:return Ri("if",e);case z.whileSchleife:return Ri("while",e);case z.doUntilSchleife:return Ri("while",Zf(e));case z.fallauswahl:return Ri("switch",e);default:return e}}function Zf(i){if(i.length===0)return i;const e=i[0].trim(),t=e.toLowerCase(),n=[...i];if(t==="until")n[0]="";else if(t.startsWith("until "))n[0]=e.slice(6).trim();else if(t.startsWith("until("))n[0]=e.slice(5);else return i;return n}function C0(i){const e=new Set(["if","for","while","until","switch"]),t=["input:","output:","print:"],n=i.trim(),a=n.toLowerCase();for(const o of t){if(a===o)return{keyword:n,rest:""};if(a.startsWith(o+" "))return{keyword:n.slice(0,o.length),rest:n.slice(o.length).trim()}}const s=n.indexOf(" ");if(s<0)return;const r=n.slice(0,s);if(e.has(r.toLowerCase()))return{keyword:r,rest:n.slice(s+1).trim()}}function Ri(i,e){if(e.length===0)return e;const t=e[0].trim(),n=t.toLowerCase();if(n===i||n.startsWith(i+" "))return e;const a=[...e];return a[0]=i+" "+t,a}function Mf(i){let e=[...i];for(;e.length<3;)e.push("");e=e.slice(0,3);const t=a=>{let s=a.trim();for(;s.endsWith(";");)s=s.slice(0,-1).trim();return s},n=e.map(t).join("; ").trim();return n===""?"for":"for "+n}const ud={[z.anweisung]:"Anweisung",[z.verzweigung]:"Bedingung",[z.fallauswahl]:"Fallauswahl",[z.forSchleife]:"for 0 < i < anzahl",[z.whileSchleife]:"while …",[z.doUntilSchleife]:"while …",[z.endlosschleife]:"endless",[z.aussprung]:"break",[z.aufruf]:"Aufruf()",[z.leerElement]:"ø"};function Lf(i){Object.assign(ud,i)}function bl(i){return Df(i)??[ud[i.type]]}class Pe extends Error{}const cn=i=>structuredClone(i);function Ut(){return ve(z.anweisung,{textLines:["ø"]})}function Wf(){return{caption:"",elements:[Ut()]}}function vl(i){if(i.type===z.leerElement)return!0;if(i.type===z.anweisung){const e=i.textLines;return e.length===0||e.length===1&&e[0]==="ø"}return!1}function vn(i,e){const t=Dt(i,e);return t!==void 0&&vl(t)}function Bi(i,e){if(e.length===0)throw new Pe("Invalid element path.");const[t,...n]=e;if(t<0||t>=i.length)throw new Pe("Invalid element path.");if(n.length===0)return{list:i,index:t};const[a,...s]=n;if(s.length===0)throw new Pe("Invalid element path.");return Bi(md(i[t],a),s)}function md(i,e){if(Cf(i.type)){if(e!==0||!i.loopBody)throw new Pe("Invalid element path.");return i.loopBody}if(Bf(i.type)){if(!i.cases||e<0||e>=i.cases.length)throw new Pe("Invalid element path.");return i.cases[e].elements}throw new Pe("Invalid element path.")}function kt(i,e){const{list:t,index:n}=Bi(i.elements,e);return t[n]}function Dt(i,e){try{return kt(i,e)}catch{return}}function Tn(i,e,t){const n=cn(i),{list:a,index:s}=Bi(n.elements,e);return a[s]=cn(t),n}function Gi(i,e,t){const n=cn(kt(i,e));return n.textLines=t.length===0?[""]:t,Tn(i,e,n)}function er(i,e){return e.length===0?!1:e.length===1&&i.elements.length===1?!vn(i,e):Dt(i,e)!==void 0}function gi(i,e){const t=cn(i),{list:n,index:a}=Bi(t.elements,e);if(e.length===1&&n.length===1){if(vl(n[0]))throw new Pe("The last root element cannot be deleted.");return n[0]=Ut(),t}return n.splice(a,1),e.length>1&&n.length===0&&n.push(Ut()),t}function X1(i,e,t,n){const a=cn(i);let s;if(e.length===0)s=a.elements;else{const r=e.slice(0,-1),o=e[e.length-1],{list:l,index:u}=Bi(a.elements,r);s=md(l[u],o)}return s.splice(Math.min(Math.max(0,t),s.length),0,cn(n)),a}function cd(i,e,t){if(t.length===0)throw new Pe("Invalid element path.");return X1(i,t.slice(0,-1),t[t.length-1],e)}function Ur(i,e,t){if(t.length===0)throw new Pe("Invalid element path.");return X1(i,t.slice(0,-1),t[t.length-1]+1,e)}function yl(i,e){return i.lengthe[n]===t)}function wl(i,e){if(e.length===0)return i;const t=e[e.length-1],n=e.slice(0,-1);if(i.length<=n.length||!n.every((r,o)=>i[o]===r))return i;const a=n.length;if(i[a]<=t)return i;const s=[...i];return s[a]-=1,s}const zl=(i,e)=>i.length===e.length&&i.every((t,n)=>t===e[n]);function Ef(i,e,t){if(zl(e,t))return i;if(yl(e,t))throw new Pe("Invalid element path.");const n=kt(i,e),a=gi(i,e);return cd(a,n,wl(t,e))}function Nf(i,e,t){if(zl(e,t))return i;if(yl(e,t))throw new Pe("Invalid element path.");const n=kt(i,e),a=gi(i,e);return Ur(a,n,wl(t,e))}function Ff(i,e,t){if(!vn(i,t))throw new Pe("Invalid element path.");if(zl(e,t))return i;if(yl(e,t))throw new Pe("Invalid element path.");const n=kt(i,e),a=gi(i,e);return Tn(a,wl(t,e),n)}function Jf(i,e){const t=cn(kt(i,e)),n=t.cases;if(t.type!==z.fallauswahl||!n||n.length===0)throw new Pe("Invalid element path.");const a=n[n.length-1].name.toLowerCase()==="default",s=a?n.length-1:n.length,r=String(a?n.length:n.length+1);return n.splice(s,0,{name:r,elements:[Ut()]}),{doc:Tn(i,e,t),path:[...e,s,0]}}function Rf(i,e,t){const n=cn(kt(i,e)),a=n.cases;if(n.type!==z.fallauswahl||!a)throw new Pe("Invalid element path.");if(a.length<=2)throw new Pe("A switch needs at least two cases.");if(t<0||t>=a.length)throw new Pe("Invalid element path.");a.splice(t,1);const s=Math.min(t,a.length-1);return{doc:Tn(i,e,n),path:[...e,s,0]}}function Gf(i,e,t,n){const a=cn(kt(i,e)),s=a.cases;if(a.type!==z.fallauswahl||!s)throw new Pe("Invalid element path.");if(t<0||t>=s.length)throw new Pe("Invalid element path.");const r=n.trim();if(r==="")throw new Pe("Invalid element path.");return s[t].name=r,Tn(i,e,a)}function Hf(i,e){var t;if(!(!i||i.length===0))for(let n=i.length;n>=1;n--){const a=i.slice(0,n);if(((t=Dt(e,a))==null?void 0:t.type)===z.fallauswahl)return a}}function Vf(i,e){if(!(!i||i.length<=e.length))return i[e.length]}function tr(i,e){if(e.elements.length!==0)return!i||!Dt(e,i)?[0]:i}const dd=i=>i!==void 0&&/\s/.test(i);function Ra(i){const e=i.trim().toLowerCase();return e.startsWith("input:")?"input":e.startsWith("output:")||e.startsWith("print:")?"output":"statement"}function Qf(i){const e=i.trim(),t=e.toLowerCase();return t.startsWith("input:")?e.slice(6).trim():t.startsWith("output:")?e.slice(7).trim():t.startsWith("print:")?e.slice(6).trim():i}function B0(i,e){const t=e.trim();return t===""?`${i} `:`${i} ${t}`}function qf(i,e){const t=Qf(e);switch(i){case"statement":return t;case"input":return B0("input:",t);case"output":return B0("output:",t)}}const Oa=i=>dd(i[0])?i.slice(1):i;function Uf(i){const e=i.replace(/^\s+/,""),t=e.toLowerCase();return t.startsWith("input:")?Oa(e.slice(6)):t.startsWith("output:")?Oa(e.slice(7)):t.startsWith("print:")?Oa(e.slice(6)):i}function D0(i,e){const t=e.replace(/^\s+/,"");if(!t.toLowerCase().startsWith(i.toLowerCase()))return e;const n=t.slice(i.length);if(!(n===""||dd(n[0])||n[0]==="("))return e;const a=Oa(n);return a.startsWith("(")&&a.endsWith(")")&&a.length>=2?a.slice(1,-1):a}function Z0(i,e){if(i==="input:"||i==="output:")return Uf(e);const t=D0(i,e);if(i==="while"&&t===e){const n=D0("until",e);if(n!==e)return n}return t}function $f(i,e){return e===""?`${i} `:`${i} ${e}`}function hd(i){return i.replace(/[“”„«»]/g,'"').replace(/[’‘‚´]/g,"'")}function M0(i){const e=i.length===0?[""]:i.slice(0,3);for(;e.length<3;)e.push("");return e}function Yf(i){let e=hd(i);for(;;){const t=e.trim();if(!t.endsWith(";"))return e;e=t.slice(0,-1).trim()}}const Cs='system-ui, -apple-system, "Segoe UI", Roboto, sans-serif';function Xf(i,e){return`${e==="bold"?700:500} ${i}px ${Cs}`}const gd=(i,e,t)=>[...i].length*e*(t==="bold"?.68:.62);function Kf(){if(typeof document>"u"||!document.body)return;const i="http://www.w3.org/2000/svg",e=document.createElementNS(i,"svg");e.setAttribute("aria-hidden","true"),e.setAttribute("width","0"),e.setAttribute("height","0"),e.style.cssText="position:absolute;left:-9999px;top:0;visibility:hidden;overflow:hidden";const t=document.createElementNS(i,"text");if(t.setAttribute("font-family",Cs),t.style.whiteSpace="pre",e.append(t),document.body.append(e),typeof t.getComputedTextLength!="function"||typeof t.getBBox!="function"){e.remove();return}if(t.textContent="Mg",t.setAttribute("font-size","20"),!(t.getComputedTextLength()>0)){e.remove();return}return t}let nr;function pd(){return nr===void 0&&(nr=Kf()??null),nr??void 0}function fd(i,e,t){i.setAttribute("font-size",String(e)),i.setAttribute("font-weight",t==="bold"?"700":"500")}function L0(i,e){const t=`${i}|${e}`;let n=W0.get(t);if(!n){const a=pd();if(n={ascent:i*.95,descent:i*.24},a){fd(a,i,e),a.setAttribute("y","0"),a.textContent="Mg";const s=a.getBBox();s.height>0&&(n={ascent:-s.y,descent:s.height+s.y})}W0.set(t,n)}return n}const W0=new Map;function e2(){const i=pd();if(i){const n=new Map;return(a,s,r)=>{const o=`${s}|${r}|${a}`;let l=n.get(o);return l===void 0&&(fd(i,s,r),i.textContent=a,l=a===""?0:i.getComputedTextLength(),n.size>2e3&&n.clear(),n.set(o,l)),l}}const e=typeof document<"u"?document.createElement("canvas").getContext("2d"):null;if(!e)return gd;const t=new Map;return(n,a,s)=>{const r=`${a}|${s}|${n}`;let o=t.get(r);return o===void 0&&(e.font=Xf(a,s),o=e.measureText(n).width,t.size>2e3&&t.clear(),t.set(r,o)),o}}const xd={fontSize:15,lineHeight:20,charWidth:7,baseHeaderExtra:20,minSidePadding:42,cellTextInsetY:15,doUntilDoLabelTopInset:2,doUntilFooterTopInset:6,doUntilFooterBottomInset:8};function t2(i){return{...xd,fontSize:14,lineHeight:21,charWidth:5.5*(14/12),baseHeaderExtra:21,minSidePadding:40}}const Hi=i=>i===z.forSchleife||i===z.whileSchleife||i===z.doUntilSchleife||i===z.endlosschleife,Vi=i=>i===z.fallauswahl||i===z.verzweigung;function Qi(i,e,t,n=0){return{idPath:i,element:e,frame:t,headerBandHeight:n,topBandHeight:0,loopBodyLeadingInset:0,caseColumnFrames:[],children:[]}}function Ve(i){return{...i,frame:{...i.frame}}}class bd{constructor(e=xd,t=gd){this.metrics=e,this.measure=t}layout(e,t={left:28,top:28}){const a=this.layoutList(e.elements,t.left,t.top,[]).map(l=>this.stretchLoopBodiesVertically(l));let s=0,r=0;const o=l=>{s=Math.max(s,l.frame.x+l.frame.width),r=Math.max(r,l.frame.y+l.frame.height),l.children.forEach(o)};return a.forEach(o),{canvasSize:{width:s+t.left,height:r+t.top},elements:a}}lineWidth(e){return Math.ceil(this.measure(e,this.metrics.fontSize,"medium"))}lineWidthBold(e){return Math.ceil(this.measure(e,this.metrics.fontSize,"bold"))}layoutList(e,t,n,a){let s=[],r=n;e.forEach((l,u)=>{const m=this.layoutElement(l,t,r,[...a,u]);s.push(m),r+=m.frame.height});const o=Math.max(0,...s.map(l=>l.frame.width));return o>0&&(s=s.map(l=>this.stretchNodeTreeToWidth(l,o))),s}stretchMultiwayNodeToWidth(e,t){const n=Ve(e),a=n.frame.width;if(!(a>0)||n.caseColumnFrames.length===0)return n;const s=t/a;n.frame.width=t;let r=n.frame.x;const o=n.caseColumnFrames.map(l=>{const u=l.width*s,m={x:r,y:l.y,width:u,height:l.height};return r+=u,m});return n.caseColumnFrames=o,n.dividerX=o.length>0?o[o.length-1].x:n.frame.x+t,n.columns&&n.columns.length===o.length&&(n.columns=n.columns.map((l,u)=>{const m=o[u];return l.map(c=>{const d=Ve(c);return d.frame.x=m.x,d.frame.width=m.width,this.stretchDescendantsWidths(d,m.width)})}),n.children=n.columns.flat()),n}stretchLoopChildren(e,t){const n=this.effectiveLoopBodyLeading(e),a=Math.max(0,t-n);e.children=e.children.map(s=>{const r=Ve(s);return r.frame.x=e.frame.x+n,r.frame.width=a,this.stretchDescendantsWidths(r,a)})}stretchNodeTreeToWidth(e,t){const n=Ve(e);return n.frame.width>0?Vi(n.element.type)&&n.caseColumnFrames.length>0?this.stretchMultiwayNodeToWidth(n,t):(n.frame.width=t,Hi(n.element.type)?this.stretchLoopChildren(n,t):n.children=n.children.map(s=>this.stretchDescendantsWidths(s,t)),n):n}stretchDescendantsWidths(e,t){let n=Ve(e);return Vi(n.element.type)?n=this.stretchNodeTreeToWidth(n,t):Hi(n.element.type)?(n.frame.width=t,this.stretchLoopChildren(n,t)):(n.frame.width=t,n.children=n.children.map(a=>this.stretchDescendantsWidths(a,t))),n}stretchLoopBodiesVertically(e){const t=Ve(e);if(t.columns&&t.columns.length>0)return t.columns=t.columns.map(s=>s.map(r=>this.stretchLoopBodiesVertically(r))),t.children=t.columns.flat(),t;t.children=t.children.map(s=>this.stretchLoopBodiesVertically(s));const n=s=>s===z.anweisung||s===z.leerElement||s===z.aufruf||s===z.aussprung||Hi(s);let a;switch(t.element.type){case z.forSchleife:case z.whileSchleife:case z.endlosschleife:{const s=t.element.type===z.endlosschleife?40:0;a=t.frame.y+t.frame.height-s;break}case z.doUntilSchleife:a=t.frame.y+t.frame.height-t.headerBandHeight;break}if(a!==void 0&&t.children.length>0){const s=t.children.length-1;let r=Ve(t.children[s]);const o=a-(r.frame.y+r.frame.height);o>.5&&n(r.element.type)&&(r.frame.height+=o,r=this.stretchLoopBodiesVertically(r),t.children=[...t.children.slice(0,s),r])}return t}headerHeight(e){const t=this.metrics,n=Math.max(1,e.textLines.length);if(e.type===z.doUntilSchleife)return t.doUntilFooterTopInset+n*t.lineHeight+t.doUntilFooterBottomInset+e.zoomY;let a;switch(e.type){case z.fallauswahl:a=40;break;case z.verzweigung:a=20;break;case z.forSchleife:case z.whileSchleife:case z.endlosschleife:a=t.baseHeaderExtra+4;break;default:a=14}return a+n*t.lineHeight+e.zoomY}doUntilBodyLeadingInset(){return Math.max(20,this.lineWidthBold("do")+12)}effectiveLoopBodyLeading(e){return e.element.type===z.doUntilSchleife?e.loopBodyLeadingInset>0?e.loopBodyLeadingInset:this.doUntilBodyLeadingInset():20}horizontalPaddingInsideCell(e){return Vi(e)?Math.max(100,this.metrics.minSidePadding*2.45):this.metrics.minSidePadding}minWidth(e){const t=e.textLines.length===0?0:Math.max(...e.textLines.map(s=>this.lineWidth(s)));let n=t+e.zoomX+this.horizontalPaddingInsideCell(e.type);if(e.type===z.aufruf){const s=Math.max(68,this.metrics.minSidePadding*1.7),r=Math.max(8,this.metrics.minSidePadding*.2);n=Math.max(n,t+e.zoomX+s+r)}const a=e.type===z.leerElement?76:e.type===z.aufruf?104:72;return Math.max(a,n)}layoutElement(e,t,n,a){if(Vi(e.type))return this.layoutMultiway(e,t,n,a);if(Hi(e.type))return this.layoutLoop(e,t,n,a);const s=this.headerHeight(e);return Qi(a,e,{x:t,y:n,width:this.minWidth(e),height:s},s)}layoutLoop(e,t,n,a){const s=x=>x.reduce((b,v)=>b+v.frame.height,0),r=x=>Math.max(0,...x.map(b=>b.frame.width)),o=e.loopBody??[];if(e.type===z.doUntilSchleife){const x=this.doUntilBodyLeadingInset(),b=e.zoomY,v=this.headerHeight(e),w=this.layoutList(o,t+x,n+b,[...a,0]),k=Math.max(this.minWidth(e),r(w)+x),I=s(w)+v+b,T=Math.max(0,k-x),S=Qi(a,e,{x:t,y:n,width:k,height:I},v);return S.topBandHeight=b,S.loopBodyLeadingInset=x,S.children=w.map(_=>{const C=Ve(_);return C.frame.x=t+x,C.frame.width=T,this.stretchDescendantsWidths(C,T)}),S}const l=20,u=this.headerHeight(e),m=e.type===z.endlosschleife?40:0,c=this.layoutList(o,t+l,n+u,[...a,0]),d=Math.max(this.minWidth(e),r(c)+l),h=u+m+s(c),g=Math.max(0,d-l),f=Qi(a,e,{x:t,y:n,width:d,height:h},u);return f.children=c.map(x=>{const b=Ve(x);return b.frame.x=t+l,b.frame.width=g,this.stretchDescendantsWidths(b,g)}),f}layoutMultiway(e,t,n,a){const s=this.headerHeight(e),r=e.cases??[],o=Math.max(1,r.length),l=Math.max(this.minWidth(e)/o,132);let u=[],m=[],c=0,d=0;if(r.forEach((x,b)=>{const v=t+c,w=this.layoutList(x.elements,v,n+s,[...a,b]),k=Math.max(0,...w.map(S=>S.frame.width));let I;e.type===z.verzweigung&&o===2?I=Math.max(k,(b===0?"true":"false").length*this.metrics.charWidth+24):I=Math.max(l,k);const T=w.reduce((S,_)=>S+_.frame.height,0);d=Math.max(d,T),u.push({x:v,y:n+s,width:I,height:T}),m.push(w.map(S=>{const _=Ve(S);return _.frame.x=v,_.frame.width=I,this.stretchDescendantsWidths(_,I)})),c+=I}),e.type===z.verzweigung&&o===2&&u.length===2){const x=Math.max(u[0].width,u[1].width),b=t,v=t+x,w=v-u[1].x;u[0]={...u[0],x:b,width:x},u[1]={...u[1],x:v,width:x},c=x*2,m[0]=m[0].map(k=>{const I=Ve(k);return I.frame.x=b,I.frame.width=x,this.stretchDescendantsWidths(I,x)}),m[1]=m[1].map(k=>{const I=$r(k,w);return I.frame.width=x,this.stretchDescendantsWidths(I,x)})}if(m.length>0){const x=n2(m,n+s);m=x.columns.map(b=>b.map(v=>this.stretchLoopBodiesVertically(v)));for(let b=0;b0?Math.max(...x.columnHeights):d}let h=Math.max(c,this.minWidth(e));if(c>.5&&h>c+.5){const x=h/c;let b=t;const v=[],w=[];u.forEach((k,I)=>{const T=k.width*x;w.push(m[I].map(S=>{const _=Ve(S);return _.frame.x=b,_.frame.width=T,this.stretchDescendantsWidths(_,T)})),v.push({x:b,y:k.y,width:T,height:k.height}),b+=T}),u=v,m=w,c=b-t,h=c}const g=u.length>0?u[u.length-1].width:c/o,f=Qi(a,e,{x:t,y:n,width:h,height:s+d},s);return f.caseColumnFrames=u,f.dividerX=u.length>0?u[u.length-1].x:t+c-g,f.dividerYInset=e.type===z.fallauswahl?-20:0,f.columns=m,f.children=m.flat(),f}}function vd(i,e){if(Math.abs(e)<=1e-4)return i;const t=Ve(i),n=a=>{const s=Ve(a);return s.frame.y+=e,vd(s,e)};return t.columns?(t.columns=t.columns.map(a=>a.map(n)),t.children=t.columns.flat()):t.children=t.children.map(n),t}function $r(i,e){if(Math.abs(e)<=1e-4)return i;const t=Ve(i);return t.frame.x+=e,t.columns?(t.columns=t.columns.map(n=>n.map(a=>$r(a,e))),t.children=t.columns.flat()):t.children=t.children.map(n=>$r(n,e)),t}function n2(i,e){if(i.length<2)return{columns:i,columnHeights:i.map(u=>u.reduce((m,c)=>m+c.frame.height,0))};const t=.5,n=[e];for(const u of i)for(const m of u)n.push(m.frame.y+m.frame.height);const a=Math.max(...n);n.push(a),n.sort((u,m)=>u-m);let s=[];for(const u of n)s.length>0&&Math.abs(u-s[s.length-1])<=t||s.push(u);(s.length===0||Math.abs(s[0]-e)>t)&&s.unshift(e),s.length===0?s=[e,a]:s[s.length-1]{let c=Math.max(0,m);for(;c{let g=Ve(d);const f=s[c],x=d.frame.y+d.frame.height,b=h===u.length-1?s.length-1:r(x,c+1),v=s[b],w=f-g.frame.y;g.frame.y=f,g.frame.height=Math.max(0,v-f),g=vd(g,w),m.push(g),c=b}),o.push(m),l.push(s[s.length-1]-e)}return{columns:o,columnHeights:l}}const i2=[{item:"anweisung",label:"Anweisung"},{item:"verzweigung",label:"Verzweigung"},{item:"fallauswahl",label:"Fallauswahl"},{item:"forZaehlSchleife",label:"For-Schleife"},{item:"whileSchleife",label:"While-Schleife"},{item:"doUntilSchleife",label:"Do-while-Schleife"},{item:"endlosschleife",label:"Endlosschleife"},{item:"aufruf",label:"Aufruf"},{item:"aussprung",label:"Aussprung"}];function E0(i){const e=Ut;switch(i){case"anweisung":return ve(z.anweisung);case"verzweigung":return ve(z.verzweigung,{cases:[{name:"true",elements:[e()]},{name:"false",elements:[e()]}]});case"fallauswahl":return ve(z.fallauswahl,{cases:[{name:"1",elements:[e()]},{name:"2",elements:[e()]},{name:"default",elements:[e()]}]});case"forZaehlSchleife":return ve(z.forSchleife,{textLines:["","",""],loopBody:[e()]});case"whileSchleife":return ve(z.whileSchleife,{loopBody:[e()]});case"doUntilSchleife":return ve(z.doUntilSchleife,{loopBody:[e()]});case"endlosschleife":return ve(z.endlosschleife,{loopBody:[e()]});case"aussprung":return ve(z.aussprung);case"aufruf":return ve(z.aufruf)}}function Ga(i){if(i==="")return"-1;";let e="";for(const t of i)e+=t.codePointAt(0)+";";return e}function Yr(i){const e=i.split(";").filter(n=>n!=="");if(e.length===1&&e[0]==="-1")return"";let t="";for(const n of e){if(!/^[+-]?\d+$/.test(n))continue;const a=Number(n);a!==-1&&(a<0||a>1114111||a>=55296&&a<=57343||(t+=String.fromCodePoint(a)))}return t}class N0 extends Error{}function Il(i){const e=new DOMParser().parseFromString(i,"application/xml");if(e.getElementsByTagName("parsererror").length>0)throw new N0("Could not read XML.");const t=e.documentElement;if(!t||t.tagName!=="struktogramm")throw new N0("Invalid XML: root element is not .");const n={caption:J0(t,"caption")??"",elements:Kr(t)},a=J0(t,"fontfamily");a!==void 0&&(n.fontFamily=a);const s=K1(t,"fontsize");s!==void 0&&(n.fontSize=s);const r=K1(t,"fontstyle");return r!==void 0&&(n.fontStyle=r),t.getAttribute("pseudocode")==="true"&&(n.pseudocode=!0),n}function n1(i){const e=(n,a)=>a===void 0?"":` ${n}="${yd(a)}"`;let t=` +var Of=Object.defineProperty;var Af=(i,e,t)=>e in i?Of(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var y=(i,e,t)=>Af(i,typeof e!="symbol"?e+"":e,t);(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const s of a)if(s.type==="childList")for(const r of s.addedNodes)r.tagName==="LINK"&&r.rel==="modulepreload"&&n(r)}).observe(document,{childList:!0,subtree:!0});function t(a){const s={};return a.integrity&&(s.integrity=a.integrity),a.referrerPolicy&&(s.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?s.credentials="include":a.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function n(a){if(a.ep)return;a.ep=!0;const s=t(a);fetch(a.href,s)}})();const Pf="modulepreload",jf=function(i,e){return new URL(i,e).href},j0={},Q=function(e,t,n){let a=Promise.resolve();if(t&&t.length>0){let r=function(m){return Promise.all(m.map(c=>Promise.resolve(c).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};const o=document.getElementsByTagName("link"),l=document.querySelector("meta[property=csp-nonce]"),u=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));a=r(t.map(m=>{if(m=jf(m,n),m in j0)return;j0[m]=!0;const c=m.endsWith(".css"),d=c?'[rel="stylesheet"]':"";if(!!n)for(let f=o.length-1;f>=0;f--){const x=o[f];if(x.href===m&&(!c||x.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${m}"]${d}`))return;const g=document.createElement("link");if(g.rel=c?"stylesheet":Pf,c||(g.as="script"),g.crossOrigin="",g.href=m,u&&g.setAttribute("nonce",u),document.head.appendChild(g),c)return new Promise((f,x)=>{g.addEventListener("load",f),g.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${m}`)))})}))}function s(r){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=r,window.dispatchEvent(o),!o.defaultPrevented)throw r}return a.then(r=>{for(const o of r||[])o.status==="rejected"&&s(o.reason);return e().catch(s)})};var z=(i=>(i[i.anweisung=0]="anweisung",i[i.verzweigung=1]="verzweigung",i[i.fallauswahl=2]="fallauswahl",i[i.forSchleife=3]="forSchleife",i[i.whileSchleife=4]="whileSchleife",i[i.doUntilSchleife=5]="doUntilSchleife",i[i.endlosschleife=6]="endlosschleife",i[i.aussprung=7]="aussprung",i[i.aufruf=8]="aufruf",i[i.leerElement=9]="leerElement",i))(z||{});function Cf(i){return i===3||i===4||i===5||i===6}function Bf(i){return i===1||i===2}function ve(i,e={}){return{type:i,zoomX:0,zoomY:0,textLines:[""],...e}}function Df(i){const e=i.textLines;if(!e.every(t=>t.trim()===""))switch(i.type){case z.forSchleife:return e.length<=1?e:[Mf(e)];case z.verzweigung:return Ri("if",e);case z.whileSchleife:return Ri("while",e);case z.doUntilSchleife:return Ri("while",Zf(e));case z.fallauswahl:return Ri("switch",e);default:return e}}function Zf(i){if(i.length===0)return i;const e=i[0].trim(),t=e.toLowerCase(),n=[...i];if(t==="until")n[0]="";else if(t.startsWith("until "))n[0]=e.slice(6).trim();else if(t.startsWith("until("))n[0]=e.slice(5);else return i;return n}function C0(i){const e=new Set(["if","for","while","until","switch"]),t=["input:","output:","print:"],n=i.trim(),a=n.toLowerCase();for(const o of t){if(a===o)return{keyword:n,rest:""};if(a.startsWith(o+" "))return{keyword:n.slice(0,o.length),rest:n.slice(o.length).trim()}}const s=n.indexOf(" ");if(s<0)return;const r=n.slice(0,s);if(e.has(r.toLowerCase()))return{keyword:r,rest:n.slice(s+1).trim()}}function Ri(i,e){if(e.length===0)return e;const t=e[0].trim(),n=t.toLowerCase();if(n===i||n.startsWith(i+" "))return e;const a=[...e];return a[0]=i+" "+t,a}function Mf(i){let e=[...i];for(;e.length<3;)e.push("");e=e.slice(0,3);const t=a=>{let s=a.trim();for(;s.endsWith(";");)s=s.slice(0,-1).trim();return s},n=e.map(t).join("; ").trim();return n===""?"for":"for "+n}const ud={[z.anweisung]:"Anweisung",[z.verzweigung]:"Bedingung",[z.fallauswahl]:"Fallauswahl",[z.forSchleife]:"for 0 < i < anzahl",[z.whileSchleife]:"while …",[z.doUntilSchleife]:"while …",[z.endlosschleife]:"endless",[z.aussprung]:"break",[z.aufruf]:"Aufruf()",[z.leerElement]:"ø"};function Lf(i){Object.assign(ud,i)}function bl(i){return Df(i)??[ud[i.type]]}class Pe extends Error{}const cn=i=>structuredClone(i);function $t(){return ve(z.anweisung,{textLines:["ø"]})}function Wf(){return{caption:"",elements:[$t()]}}function vl(i){if(i.type===z.leerElement)return!0;if(i.type===z.anweisung){const e=i.textLines;return e.length===0||e.length===1&&e[0]==="ø"}return!1}function vn(i,e){const t=Dt(i,e);return t!==void 0&&vl(t)}function Bi(i,e){if(e.length===0)throw new Pe("Invalid element path.");const[t,...n]=e;if(t<0||t>=i.length)throw new Pe("Invalid element path.");if(n.length===0)return{list:i,index:t};const[a,...s]=n;if(s.length===0)throw new Pe("Invalid element path.");return Bi(md(i[t],a),s)}function md(i,e){if(Cf(i.type)){if(e!==0||!i.loopBody)throw new Pe("Invalid element path.");return i.loopBody}if(Bf(i.type)){if(!i.cases||e<0||e>=i.cases.length)throw new Pe("Invalid element path.");return i.cases[e].elements}throw new Pe("Invalid element path.")}function kt(i,e){const{list:t,index:n}=Bi(i.elements,e);return t[n]}function Dt(i,e){try{return kt(i,e)}catch{return}}function Tn(i,e,t){const n=cn(i),{list:a,index:s}=Bi(n.elements,e);return a[s]=cn(t),n}function Gi(i,e,t){const n=cn(kt(i,e));return n.textLines=t.length===0?[""]:t,Tn(i,e,n)}function er(i,e){return e.length===0?!1:e.length===1&&i.elements.length===1?!vn(i,e):Dt(i,e)!==void 0}function gi(i,e){const t=cn(i),{list:n,index:a}=Bi(t.elements,e);if(e.length===1&&n.length===1){if(vl(n[0]))throw new Pe("The last root element cannot be deleted.");return n[0]=$t(),t}return n.splice(a,1),e.length>1&&n.length===0&&n.push($t()),t}function X1(i,e,t,n){const a=cn(i);let s;if(e.length===0)s=a.elements;else{const r=e.slice(0,-1),o=e[e.length-1],{list:l,index:u}=Bi(a.elements,r);s=md(l[u],o)}return s.splice(Math.min(Math.max(0,t),s.length),0,cn(n)),a}function cd(i,e,t){if(t.length===0)throw new Pe("Invalid element path.");return X1(i,t.slice(0,-1),t[t.length-1],e)}function Ur(i,e,t){if(t.length===0)throw new Pe("Invalid element path.");return X1(i,t.slice(0,-1),t[t.length-1]+1,e)}function yl(i,e){return i.lengthe[n]===t)}function wl(i,e){if(e.length===0)return i;const t=e[e.length-1],n=e.slice(0,-1);if(i.length<=n.length||!n.every((r,o)=>i[o]===r))return i;const a=n.length;if(i[a]<=t)return i;const s=[...i];return s[a]-=1,s}const zl=(i,e)=>i.length===e.length&&i.every((t,n)=>t===e[n]);function Ef(i,e,t){if(zl(e,t))return i;if(yl(e,t))throw new Pe("Invalid element path.");const n=kt(i,e),a=gi(i,e);return cd(a,n,wl(t,e))}function Nf(i,e,t){if(zl(e,t))return i;if(yl(e,t))throw new Pe("Invalid element path.");const n=kt(i,e),a=gi(i,e);return Ur(a,n,wl(t,e))}function Ff(i,e,t){if(!vn(i,t))throw new Pe("Invalid element path.");if(zl(e,t))return i;if(yl(e,t))throw new Pe("Invalid element path.");const n=kt(i,e),a=gi(i,e);return Tn(a,wl(t,e),n)}function Jf(i,e){const t=cn(kt(i,e)),n=t.cases;if(t.type!==z.fallauswahl||!n||n.length===0)throw new Pe("Invalid element path.");const a=n[n.length-1].name.toLowerCase()==="default",s=a?n.length-1:n.length,r=String(a?n.length:n.length+1);return n.splice(s,0,{name:r,elements:[$t()]}),{doc:Tn(i,e,t),path:[...e,s,0]}}function Rf(i,e,t){const n=cn(kt(i,e)),a=n.cases;if(n.type!==z.fallauswahl||!a)throw new Pe("Invalid element path.");if(a.length<=2)throw new Pe("A switch needs at least two cases.");if(t<0||t>=a.length)throw new Pe("Invalid element path.");a.splice(t,1);const s=Math.min(t,a.length-1);return{doc:Tn(i,e,n),path:[...e,s,0]}}function Gf(i,e,t,n){const a=cn(kt(i,e)),s=a.cases;if(a.type!==z.fallauswahl||!s)throw new Pe("Invalid element path.");if(t<0||t>=s.length)throw new Pe("Invalid element path.");const r=n.trim();if(r==="")throw new Pe("Invalid element path.");return s[t].name=r,Tn(i,e,a)}function Hf(i,e){var t;if(!(!i||i.length===0))for(let n=i.length;n>=1;n--){const a=i.slice(0,n);if(((t=Dt(e,a))==null?void 0:t.type)===z.fallauswahl)return a}}function Vf(i,e){if(!(!i||i.length<=e.length))return i[e.length]}function tr(i,e){if(e.elements.length!==0)return!i||!Dt(e,i)?[0]:i}const dd=i=>i!==void 0&&/\s/.test(i);function Ra(i){const e=i.trim().toLowerCase();return e.startsWith("input:")?"input":e.startsWith("output:")||e.startsWith("print:")?"output":"statement"}function Qf(i){const e=i.trim(),t=e.toLowerCase();return t.startsWith("input:")?e.slice(6).trim():t.startsWith("output:")?e.slice(7).trim():t.startsWith("print:")?e.slice(6).trim():i}function B0(i,e){const t=e.trim();return t===""?`${i} `:`${i} ${t}`}function qf(i,e){const t=Qf(e);switch(i){case"statement":return t;case"input":return B0("input:",t);case"output":return B0("output:",t)}}const Oa=i=>dd(i[0])?i.slice(1):i;function Uf(i){const e=i.replace(/^\s+/,""),t=e.toLowerCase();return t.startsWith("input:")?Oa(e.slice(6)):t.startsWith("output:")?Oa(e.slice(7)):t.startsWith("print:")?Oa(e.slice(6)):i}function D0(i,e){const t=e.replace(/^\s+/,"");if(!t.toLowerCase().startsWith(i.toLowerCase()))return e;const n=t.slice(i.length);if(!(n===""||dd(n[0])||n[0]==="("))return e;const a=Oa(n);return a.startsWith("(")&&a.endsWith(")")&&a.length>=2?a.slice(1,-1):a}function Z0(i,e){if(i==="input:"||i==="output:")return Uf(e);const t=D0(i,e);if(i==="while"&&t===e){const n=D0("until",e);if(n!==e)return n}return t}function $f(i,e){return e===""?`${i} `:`${i} ${e}`}function hd(i){return i.replace(/[“”„«»]/g,'"').replace(/[’‘‚´]/g,"'")}function M0(i){const e=i.length===0?[""]:i.slice(0,3);for(;e.length<3;)e.push("");return e}function Yf(i){let e=hd(i);for(;;){const t=e.trim();if(!t.endsWith(";"))return e;e=t.slice(0,-1).trim()}}const Cs='system-ui, -apple-system, "Segoe UI", Roboto, sans-serif';function Xf(i,e){return`${e==="bold"?700:500} ${i}px ${Cs}`}const gd=(i,e,t)=>[...i].length*e*(t==="bold"?.68:.62);function Kf(){if(typeof document>"u"||!document.body)return;const i="http://www.w3.org/2000/svg",e=document.createElementNS(i,"svg");e.setAttribute("aria-hidden","true"),e.setAttribute("width","0"),e.setAttribute("height","0"),e.style.cssText="position:absolute;left:-9999px;top:0;visibility:hidden;overflow:hidden";const t=document.createElementNS(i,"text");if(t.setAttribute("font-family",Cs),t.style.whiteSpace="pre",e.append(t),document.body.append(e),typeof t.getComputedTextLength!="function"||typeof t.getBBox!="function"){e.remove();return}if(t.textContent="Mg",t.setAttribute("font-size","20"),!(t.getComputedTextLength()>0)){e.remove();return}return t}let nr;function pd(){return nr===void 0&&(nr=Kf()??null),nr??void 0}function fd(i,e,t){i.setAttribute("font-size",String(e)),i.setAttribute("font-weight",t==="bold"?"700":"500")}function L0(i,e){const t=`${i}|${e}`;let n=W0.get(t);if(!n){const a=pd();if(n={ascent:i*.95,descent:i*.24},a){fd(a,i,e),a.setAttribute("y","0"),a.textContent="Mg";const s=a.getBBox();s.height>0&&(n={ascent:-s.y,descent:s.height+s.y})}W0.set(t,n)}return n}const W0=new Map;function e2(){const i=pd();if(i){const n=new Map;return(a,s,r)=>{const o=`${s}|${r}|${a}`;let l=n.get(o);return l===void 0&&(fd(i,s,r),i.textContent=a,l=a===""?0:i.getComputedTextLength(),n.size>2e3&&n.clear(),n.set(o,l)),l}}const e=typeof document<"u"?document.createElement("canvas").getContext("2d"):null;if(!e)return gd;const t=new Map;return(n,a,s)=>{const r=`${a}|${s}|${n}`;let o=t.get(r);return o===void 0&&(e.font=Xf(a,s),o=e.measureText(n).width,t.size>2e3&&t.clear(),t.set(r,o)),o}}const xd={fontSize:15,lineHeight:20,charWidth:7,baseHeaderExtra:20,minSidePadding:42,cellTextInsetY:15,doUntilDoLabelTopInset:2,doUntilFooterTopInset:6,doUntilFooterBottomInset:8};function t2(i){return{...xd,fontSize:14,lineHeight:21,charWidth:5.5*(14/12),baseHeaderExtra:21,minSidePadding:40}}const Hi=i=>i===z.forSchleife||i===z.whileSchleife||i===z.doUntilSchleife||i===z.endlosschleife,Vi=i=>i===z.fallauswahl||i===z.verzweigung;function Qi(i,e,t,n=0){return{idPath:i,element:e,frame:t,headerBandHeight:n,topBandHeight:0,loopBodyLeadingInset:0,caseColumnFrames:[],children:[]}}function Ve(i){return{...i,frame:{...i.frame}}}class bd{constructor(e=xd,t=gd){this.metrics=e,this.measure=t}layout(e,t={left:28,top:28}){const a=this.layoutList(e.elements,t.left,t.top,[]).map(l=>this.stretchLoopBodiesVertically(l));let s=0,r=0;const o=l=>{s=Math.max(s,l.frame.x+l.frame.width),r=Math.max(r,l.frame.y+l.frame.height),l.children.forEach(o)};return a.forEach(o),{canvasSize:{width:s+t.left,height:r+t.top},elements:a}}lineWidth(e){return Math.ceil(this.measure(e,this.metrics.fontSize,"medium"))}lineWidthBold(e){return Math.ceil(this.measure(e,this.metrics.fontSize,"bold"))}layoutList(e,t,n,a){let s=[],r=n;e.forEach((l,u)=>{const m=this.layoutElement(l,t,r,[...a,u]);s.push(m),r+=m.frame.height});const o=Math.max(0,...s.map(l=>l.frame.width));return o>0&&(s=s.map(l=>this.stretchNodeTreeToWidth(l,o))),s}stretchMultiwayNodeToWidth(e,t){const n=Ve(e),a=n.frame.width;if(!(a>0)||n.caseColumnFrames.length===0)return n;const s=t/a;n.frame.width=t;let r=n.frame.x;const o=n.caseColumnFrames.map(l=>{const u=l.width*s,m={x:r,y:l.y,width:u,height:l.height};return r+=u,m});return n.caseColumnFrames=o,n.dividerX=o.length>0?o[o.length-1].x:n.frame.x+t,n.columns&&n.columns.length===o.length&&(n.columns=n.columns.map((l,u)=>{const m=o[u];return l.map(c=>{const d=Ve(c);return d.frame.x=m.x,d.frame.width=m.width,this.stretchDescendantsWidths(d,m.width)})}),n.children=n.columns.flat()),n}stretchLoopChildren(e,t){const n=this.effectiveLoopBodyLeading(e),a=Math.max(0,t-n);e.children=e.children.map(s=>{const r=Ve(s);return r.frame.x=e.frame.x+n,r.frame.width=a,this.stretchDescendantsWidths(r,a)})}stretchNodeTreeToWidth(e,t){const n=Ve(e);return n.frame.width>0?Vi(n.element.type)&&n.caseColumnFrames.length>0?this.stretchMultiwayNodeToWidth(n,t):(n.frame.width=t,Hi(n.element.type)?this.stretchLoopChildren(n,t):n.children=n.children.map(s=>this.stretchDescendantsWidths(s,t)),n):n}stretchDescendantsWidths(e,t){let n=Ve(e);return Vi(n.element.type)?n=this.stretchNodeTreeToWidth(n,t):Hi(n.element.type)?(n.frame.width=t,this.stretchLoopChildren(n,t)):(n.frame.width=t,n.children=n.children.map(a=>this.stretchDescendantsWidths(a,t))),n}stretchLoopBodiesVertically(e){const t=Ve(e);if(t.columns&&t.columns.length>0)return t.columns=t.columns.map(s=>s.map(r=>this.stretchLoopBodiesVertically(r))),t.children=t.columns.flat(),t;t.children=t.children.map(s=>this.stretchLoopBodiesVertically(s));const n=s=>s===z.anweisung||s===z.leerElement||s===z.aufruf||s===z.aussprung||Hi(s);let a;switch(t.element.type){case z.forSchleife:case z.whileSchleife:case z.endlosschleife:{const s=t.element.type===z.endlosschleife?40:0;a=t.frame.y+t.frame.height-s;break}case z.doUntilSchleife:a=t.frame.y+t.frame.height-t.headerBandHeight;break}if(a!==void 0&&t.children.length>0){const s=t.children.length-1;let r=Ve(t.children[s]);const o=a-(r.frame.y+r.frame.height);o>.5&&n(r.element.type)&&(r.frame.height+=o,r=this.stretchLoopBodiesVertically(r),t.children=[...t.children.slice(0,s),r])}return t}headerHeight(e){const t=this.metrics,n=Math.max(1,e.textLines.length);if(e.type===z.doUntilSchleife)return t.doUntilFooterTopInset+n*t.lineHeight+t.doUntilFooterBottomInset+e.zoomY;let a;switch(e.type){case z.fallauswahl:a=40;break;case z.verzweigung:a=20;break;case z.forSchleife:case z.whileSchleife:case z.endlosschleife:a=t.baseHeaderExtra+4;break;default:a=14}return a+n*t.lineHeight+e.zoomY}doUntilBodyLeadingInset(){return Math.max(20,this.lineWidthBold("do")+12)}effectiveLoopBodyLeading(e){return e.element.type===z.doUntilSchleife?e.loopBodyLeadingInset>0?e.loopBodyLeadingInset:this.doUntilBodyLeadingInset():20}horizontalPaddingInsideCell(e){return Vi(e)?Math.max(100,this.metrics.minSidePadding*2.45):this.metrics.minSidePadding}minWidth(e){const t=e.textLines.length===0?0:Math.max(...e.textLines.map(s=>this.lineWidth(s)));let n=t+e.zoomX+this.horizontalPaddingInsideCell(e.type);if(e.type===z.aufruf){const s=Math.max(68,this.metrics.minSidePadding*1.7),r=Math.max(8,this.metrics.minSidePadding*.2);n=Math.max(n,t+e.zoomX+s+r)}const a=e.type===z.leerElement?76:e.type===z.aufruf?104:72;return Math.max(a,n)}layoutElement(e,t,n,a){if(Vi(e.type))return this.layoutMultiway(e,t,n,a);if(Hi(e.type))return this.layoutLoop(e,t,n,a);const s=this.headerHeight(e);return Qi(a,e,{x:t,y:n,width:this.minWidth(e),height:s},s)}layoutLoop(e,t,n,a){const s=x=>x.reduce((b,v)=>b+v.frame.height,0),r=x=>Math.max(0,...x.map(b=>b.frame.width)),o=e.loopBody??[];if(e.type===z.doUntilSchleife){const x=this.doUntilBodyLeadingInset(),b=e.zoomY,v=this.headerHeight(e),w=this.layoutList(o,t+x,n+b,[...a,0]),k=Math.max(this.minWidth(e),r(w)+x),I=s(w)+v+b,T=Math.max(0,k-x),S=Qi(a,e,{x:t,y:n,width:k,height:I},v);return S.topBandHeight=b,S.loopBodyLeadingInset=x,S.children=w.map(_=>{const C=Ve(_);return C.frame.x=t+x,C.frame.width=T,this.stretchDescendantsWidths(C,T)}),S}const l=20,u=this.headerHeight(e),m=e.type===z.endlosschleife?40:0,c=this.layoutList(o,t+l,n+u,[...a,0]),d=Math.max(this.minWidth(e),r(c)+l),h=u+m+s(c),g=Math.max(0,d-l),f=Qi(a,e,{x:t,y:n,width:d,height:h},u);return f.children=c.map(x=>{const b=Ve(x);return b.frame.x=t+l,b.frame.width=g,this.stretchDescendantsWidths(b,g)}),f}layoutMultiway(e,t,n,a){const s=this.headerHeight(e),r=e.cases??[],o=Math.max(1,r.length),l=Math.max(this.minWidth(e)/o,132);let u=[],m=[],c=0,d=0;if(r.forEach((x,b)=>{const v=t+c,w=this.layoutList(x.elements,v,n+s,[...a,b]),k=Math.max(0,...w.map(S=>S.frame.width));let I;e.type===z.verzweigung&&o===2?I=Math.max(k,(b===0?"true":"false").length*this.metrics.charWidth+24):I=Math.max(l,k);const T=w.reduce((S,_)=>S+_.frame.height,0);d=Math.max(d,T),u.push({x:v,y:n+s,width:I,height:T}),m.push(w.map(S=>{const _=Ve(S);return _.frame.x=v,_.frame.width=I,this.stretchDescendantsWidths(_,I)})),c+=I}),e.type===z.verzweigung&&o===2&&u.length===2){const x=Math.max(u[0].width,u[1].width),b=t,v=t+x,w=v-u[1].x;u[0]={...u[0],x:b,width:x},u[1]={...u[1],x:v,width:x},c=x*2,m[0]=m[0].map(k=>{const I=Ve(k);return I.frame.x=b,I.frame.width=x,this.stretchDescendantsWidths(I,x)}),m[1]=m[1].map(k=>{const I=$r(k,w);return I.frame.width=x,this.stretchDescendantsWidths(I,x)})}if(m.length>0){const x=n2(m,n+s);m=x.columns.map(b=>b.map(v=>this.stretchLoopBodiesVertically(v)));for(let b=0;b0?Math.max(...x.columnHeights):d}let h=Math.max(c,this.minWidth(e));if(c>.5&&h>c+.5){const x=h/c;let b=t;const v=[],w=[];u.forEach((k,I)=>{const T=k.width*x;w.push(m[I].map(S=>{const _=Ve(S);return _.frame.x=b,_.frame.width=T,this.stretchDescendantsWidths(_,T)})),v.push({x:b,y:k.y,width:T,height:k.height}),b+=T}),u=v,m=w,c=b-t,h=c}const g=u.length>0?u[u.length-1].width:c/o,f=Qi(a,e,{x:t,y:n,width:h,height:s+d},s);return f.caseColumnFrames=u,f.dividerX=u.length>0?u[u.length-1].x:t+c-g,f.dividerYInset=e.type===z.fallauswahl?-20:0,f.columns=m,f.children=m.flat(),f}}function vd(i,e){if(Math.abs(e)<=1e-4)return i;const t=Ve(i),n=a=>{const s=Ve(a);return s.frame.y+=e,vd(s,e)};return t.columns?(t.columns=t.columns.map(a=>a.map(n)),t.children=t.columns.flat()):t.children=t.children.map(n),t}function $r(i,e){if(Math.abs(e)<=1e-4)return i;const t=Ve(i);return t.frame.x+=e,t.columns?(t.columns=t.columns.map(n=>n.map(a=>$r(a,e))),t.children=t.columns.flat()):t.children=t.children.map(n=>$r(n,e)),t}function n2(i,e){if(i.length<2)return{columns:i,columnHeights:i.map(u=>u.reduce((m,c)=>m+c.frame.height,0))};const t=.5,n=[e];for(const u of i)for(const m of u)n.push(m.frame.y+m.frame.height);const a=Math.max(...n);n.push(a),n.sort((u,m)=>u-m);let s=[];for(const u of n)s.length>0&&Math.abs(u-s[s.length-1])<=t||s.push(u);(s.length===0||Math.abs(s[0]-e)>t)&&s.unshift(e),s.length===0?s=[e,a]:s[s.length-1]{let c=Math.max(0,m);for(;c{let g=Ve(d);const f=s[c],x=d.frame.y+d.frame.height,b=h===u.length-1?s.length-1:r(x,c+1),v=s[b],w=f-g.frame.y;g.frame.y=f,g.frame.height=Math.max(0,v-f),g=vd(g,w),m.push(g),c=b}),o.push(m),l.push(s[s.length-1]-e)}return{columns:o,columnHeights:l}}const i2=[{item:"anweisung",label:"Anweisung"},{item:"verzweigung",label:"Verzweigung"},{item:"fallauswahl",label:"Fallauswahl"},{item:"forZaehlSchleife",label:"For-Schleife"},{item:"whileSchleife",label:"While-Schleife"},{item:"doUntilSchleife",label:"Do-while-Schleife"},{item:"endlosschleife",label:"Endlosschleife"},{item:"aufruf",label:"Aufruf"},{item:"aussprung",label:"Aussprung"}];function E0(i){const e=$t;switch(i){case"anweisung":return ve(z.anweisung);case"verzweigung":return ve(z.verzweigung,{cases:[{name:"true",elements:[e()]},{name:"false",elements:[e()]}]});case"fallauswahl":return ve(z.fallauswahl,{cases:[{name:"1",elements:[e()]},{name:"2",elements:[e()]},{name:"default",elements:[e()]}]});case"forZaehlSchleife":return ve(z.forSchleife,{textLines:["","",""],loopBody:[e()]});case"whileSchleife":return ve(z.whileSchleife,{loopBody:[e()]});case"doUntilSchleife":return ve(z.doUntilSchleife,{loopBody:[e()]});case"endlosschleife":return ve(z.endlosschleife,{loopBody:[e()]});case"aussprung":return ve(z.aussprung);case"aufruf":return ve(z.aufruf)}}function Ga(i){if(i==="")return"-1;";let e="";for(const t of i)e+=t.codePointAt(0)+";";return e}function Yr(i){const e=i.split(";").filter(n=>n!=="");if(e.length===1&&e[0]==="-1")return"";let t="";for(const n of e){if(!/^[+-]?\d+$/.test(n))continue;const a=Number(n);a!==-1&&(a<0||a>1114111||a>=55296&&a<=57343||(t+=String.fromCodePoint(a)))}return t}class N0 extends Error{}function Il(i){const e=new DOMParser().parseFromString(i,"application/xml");if(e.getElementsByTagName("parsererror").length>0)throw new N0("Could not read XML.");const t=e.documentElement;if(!t||t.tagName!=="struktogramm")throw new N0("Invalid XML: root element is not .");const n={caption:J0(t,"caption")??"",elements:Kr(t)},a=J0(t,"fontfamily");a!==void 0&&(n.fontFamily=a);const s=K1(t,"fontsize");s!==void 0&&(n.fontSize=s);const r=K1(t,"fontstyle");return r!==void 0&&(n.fontStyle=r),t.getAttribute("pseudocode")==="true"&&(n.pseudocode=!0),n}function n1(i){const e=(n,a)=>a===void 0?"":` ${n}="${yd(a)}"`;let t=` `;t+=" `;for(const n of i.elements)t+=Xr(n," ");return t+=` `,t}function Xr(i,e){let t=`${e} @@ -9,15 +9,15 @@ var Of=Object.defineProperty;var Af=(i,e,t)=>e in i?Of(i,e,{enumerable:!0,config `;for(const a of n.elements)t+=Xr(a,e+" ");t+=`${e} `}return t+=`${e} `,t}function yd(i){return i.replace(/&/g,"&").replace(/"/g,""").replace(//g,">")}function a2(i){return i.replace(/&/g,"&").replace(//g,">")}function F0(i){return String(i.a<<24|i.r<<16|i.g<<8|i.b|0)}function Aa(i,e){return Array.from(i.children).filter(t=>t.tagName===e)}function Kr(i){const e=[];for(const t of Aa(i,"strelem")){const n=s2(t);n&&e.push(n)}return e}function s2(i){const e=K1(i,"typ");if(e===void 0||z[e]===void 0)return;const t={type:e,zoomX:K1(i,"zx")??0,zoomY:K1(i,"zy")??0,textLines:Aa(i,"text").map(o=>Yr((o.textContent??"").trim()))},n=R0(i.getAttribute("textcolor"));n&&(t.textColor=n);const a=R0(i.getAttribute("bgcolor"));a&&(t.backgroundColor=a),t.textLines.length===0&&(t.textLines=[""]);const s=Aa(i,"schleifeninhalt")[0];if(s){const o=Kr(s);o.length>0&&(t.loopBody=o)}const r=Aa(i,"fall").map(o=>({name:Yr(o.getAttribute("fallname")??""),elements:Kr(o)}));return r.length>0&&(t.cases=r),t}function J0(i,e){const t=i.getAttribute(e);return t===null?void 0:Yr(t)}function K1(i,e){const t=i.getAttribute(e);if(!(t===null||!/^[+-]?\d+$/.test(t)))return Number(t)}function R0(i){if(i===null||!/^[+-]?\d+$/.test(i))return;const e=Number(i);if(e<-2147483648||e>2147483647)return;const t=e>>>0;return{a:t>>>24&255,r:t>>>16&255,g:t>>>8&255,b:t&255}}const r2="http://www.w3.org/2000/svg",je={diagramLineWidth:2,outerFrameLineWidth:2,selectionLineWidth:3.5,canvasOuterMargin:16,cellTextInsetX:18,cellTextInsetY:15,multiHeaderFirstLineY:14,branchLabelInsetX:10,fallauswahlCaseLabelBand:26,callSideBarInset:14,callTextInsetFromSideBar:20,loopBodyLeadingInset:20};function fe(i,e={}){const t=document.createElementNS(r2,i);for(const[n,a]of Object.entries(e))t.setAttribute(n,String(a));return t}class wd{constructor(e,t){y(this,"usesSimulationHighlight",!1);y(this,"fillsSelection",!1);this.metrics=e,this.measure=t}get lineHeight(){return this.metrics.lineHeight}get fontSize(){return this.metrics.fontSize}render(e,t,n,a=je.canvasOuterMargin){const s=fe("svg",{width:t.width,height:t.height,viewBox:`0 0 ${t.width} ${t.height}`,"font-family":Cs,"font-size":this.fontSize,class:"diagram"});s.append(fe("rect",{x:0,y:0,width:t.width,height:t.height,fill:"#fafafa"}));const r=a;s.append(fe("rect",{x:r,y:r,width:e.canvasSize.width-2*r-1,height:e.canvasSize.height-2*r-1,fill:"none",stroke:"black","stroke-width":je.outerFrameLineWidth}));const o=fe("g");for(const l of e.elements)this.drawNode(l,o,n,{},void 0);return s.append(o),s}line(e,t){e.append(fe("polyline",{points:t.map(n=>n.join(",")).join(" "),fill:"none",stroke:"black","stroke-width":je.diagramLineWidth,"stroke-linejoin":"miter"}))}strokeCellBorder(e,t,n){const a=t.x,s=t.y,r=t.x+t.width,o=t.y+t.height;if(!n.top&&!n.left&&!n.bottom&&!n.right){e.append(fe("rect",{x:a,y:s,width:t.width,height:t.height,fill:"none",stroke:"black","stroke-width":je.diagramLineWidth}));return}n.top||this.line(e,[[a,s],[r,s]]),n.right||this.line(e,[[r,s],[r,o]]),n.bottom||this.line(e,[[r,o],[a,o]]),n.left||this.line(e,[[a,o],[a,s]])}textWidth(e){const t=C0(e);return t?this.measure(t.keyword,this.fontSize,"bold")+(t.rest===""?0:this.measure(" "+t.rest,this.fontSize,"medium")):this.measure(e,this.fontSize,"medium")}drawKeywordLine(e,t,n,a){const s=fe("text",{x:n,y:a+L0(this.fontSize,"medium").ascent,"font-weight":500});s.style.whiteSpace="pre";const r=C0(t);if(r){const o=fe("tspan",{"font-weight":700});if(o.textContent=r.keyword,s.append(o),r.rest!==""){const l=fe("tspan",{});l.textContent=" "+r.rest,s.append(l)}}else s.textContent=t;e.append(s)}drawLabel(e,t,n,a,s,r){const o=L0(this.fontSize,s?"bold":"medium"),l=fe("text",{x:n,y:r==="top"?a+o.ascent:a-o.descent,"font-weight":s?700:500});l.style.whiteSpace="pre",l.textContent=t,e.append(l)}roofMetrics(e,t,n,a){const s=t.y+n,r=e.dividerYInset??0,o=12,l=Math.max(e.element.textLines.length,1)*this.lineHeight,u=t.y+je.multiHeaderFirstLineY;if(e.element.type===z.fallauswahl){const c=Math.max(je.fallauswahlCaseLabelBand,this.lineHeight+10),d=s-c,h=Math.min(s+r,d-8),g=Math.max(h,u+l+6);return{apex:{x:a,y:g},maxTextBottom:d-o,roofBottom:s}}const m={x:a,y:s+r};return{apex:m,maxTextBottom:m.y-o,roofBottom:s}}drawNode(e,t,n,a,s){var I;const r=e.frame,o=e.element,l=r.x+r.width,u=r.y+r.height,m=o.type===z.verzweigung||o.type===z.fallauswahl,c=m?e.headerBandHeight:0,d=n!==void 0&&eo(e.idPath,n),h=bl(o),g=fe("g",{"data-path":e.idPath.join(",")});t.append(g);const f=this.usesSimulationHighlight,x=o.backgroundColor,b=x&&x.a>0?`rgba(${x.r}, ${x.g}, ${x.b}, ${x.a/255})`:"white",v=d&&(f||this.fillsSelection)?"rgba(199, 230, 255, 0.55)":b;g.append(fe("rect",{x:r.x,y:r.y,width:r.width,height:r.height,fill:v})),this.strokeCellBorder(g,r,a);const w=je.callSideBarInset;if(o.type===z.aufruf?(this.line(g,[[r.x+w,r.y],[r.x+w,u]]),this.line(g,[[l-w,r.y],[l-w,u]])):o.type===z.aussprung&&this.line(g,[[r.x+w,r.y],[r.x,r.y+r.height/2],[r.x+w,u]]),m&&e.dividerX!==void 0){const T=e.dividerX,S=this.roofMetrics(e,r,c,T),_=Math.max(h.length,1)*this.lineHeight,C=r.y+je.multiHeaderFirstLineY;this.line(g,[[r.x,r.y],[S.apex.x,S.apex.y],[l,r.y]]),o.type===z.fallauswahl&&this.line(g,[[r.x,S.roofBottom],[l,S.roofBottom]]);let B;C+_<=S.maxTextBottom?B=C:B=Math.max(r.y+2,S.maxTextBottom-(Math.max(h.length,1)-1)*this.lineHeight-this.lineHeight),h.forEach((P,A)=>{const W=this.textWidth(P);let R;if(o.type===z.verzweigung){const ne=r.x+je.cellTextInsetX,ge=l-W-je.cellTextInsetX;R=Math.min(Math.max(T-W/2,ne),ge)}else R=r.x+r.width/2-W/2;this.drawKeywordLine(g,P,R,B+A*this.lineHeight)})}else if(o.type!==z.doUntilSchleife)if(o.type===z.anweisung||o.type===z.aufruf||o.type===z.aussprung){const T=je.cellTextInsetX;let S=r.x+T,_=l-T;o.type===z.aufruf?(S=r.x+w+je.callTextInsetFromSideBar,_=l-w-je.callTextInsetFromSideBar):o.type===z.aussprung&&(S=r.x+w+T);const C=Math.max(0,_-S);let B=r.y+r.height/2-Math.max(1,h.length)*this.lineHeight/2;for(const P of h)this.drawKeywordLine(g,P,S+(C-this.textWidth(P))/2,B),B+=this.lineHeight}else{const T=Math.max(1,h.length)*this.lineHeight;let S=s===z.doUntilSchleife?r.y+r.height/2-T/2:r.y+je.cellTextInsetY;for(const _ of h)this.drawKeywordLine(g,_,r.x+je.cellTextInsetX,S),S+=this.lineHeight}e.children.forEach((T,S)=>{const _=o.type===z.doUntilSchleife&&S===0?{top:!0,left:!0}:{};this.drawNode(T,t,n,_,o.type)});const k=fe("g");if(t.append(k),o.type===z.doUntilSchleife){const T=((I=e.children[0])==null?void 0:I.frame.x)??r.x+(e.loopBodyLeadingInset>0?e.loopBodyLeadingInset:je.loopBodyLeadingInset);this.drawLabel(k,"do",r.x+4,r.y+this.metrics.doUntilDoLabelTopInset,!0,"top");const S=u-e.headerBandHeight;this.line(k,[[T,S],[l,S]]),this.line(k,[[T,r.y],[T,S]]);let _=S+this.metrics.doUntilFooterTopInset;for(const C of h)this.drawKeywordLine(k,C,r.x+je.cellTextInsetX,_),_+=this.lineHeight}if(m&&e.dividerX!==void 0&&e.caseColumnFrames.length>1){const T=this.roofMetrics(e,r,c,e.dividerX),S=T.apex;e.caseColumnFrames.forEach((C,B)=>{if(B>=e.caseColumnFrames.length-1)return;const P=C.x+C.width,A=o2(P,r,S),W=Number.isFinite(A)?Math.min(Math.max(A,r.y),u):r.y;this.line(k,[[P,u],[P,W]])});const _=o.cases;if(_&&_.length===e.caseColumnFrames.length){const C=o.type===z.fallauswahl?T.roofBottom-6:r.y+c-8,B=je.branchLabelInsetX;if(o.type===z.verzweigung&&_.length===2){this.drawLabel(k,"true",r.x+B,C,!0,"bottom");const P=e.caseColumnFrames[1],A=this.measure("false",this.fontSize,"bold");this.drawLabel(k,"false",P.x+P.width-B-A,C,!0,"bottom")}else _.forEach((P,A)=>{const W=e.caseColumnFrames[A],R=["default","true","false"].includes(P.name.toLowerCase()),ne=this.measure(P.name,this.fontSize,R?"bold":"medium");this.drawLabel(k,P.name,W.x+W.width/2-ne/2,C,R,"bottom")})}}d&&k.append(fe("rect",{x:r.x,y:r.y,width:r.width,height:r.height,class:"selection-frame",fill:"none",stroke:f?"rgba(66, 140, 242, 0.78)":"rgba(0, 122, 255, 0.9)","stroke-width":je.selectionLineWidth}))}}function o2(i,e,t){const n=e.y;if(i<=t.x){const s=t.x-e.x;return Math.abs(s)<.5?t.y:n+(t.y-n)/s*(i-e.x)}const a=e.x+e.width-t.x;return Math.abs(a)<.5?t.y:t.y+(n-t.y)/a*(i-t.x)}function eo(i,e){return i.length===e.length&&i.every((t,n)=>t===e[n])}function l2(i){const e=[],t=n=>{e.push(n),n.children.forEach(t)};return i.forEach(t),e}function Ha(i){var e,t;return{...i,textLines:bl(i),loopBody:(e=i.loopBody)==null?void 0:e.map(Ha),cases:(t=i.cases)==null?void 0:t.map(n=>({name:n.name,elements:n.elements.map(Ha)}))}}const u2=[{code:"de",name:"Deutsch"},{code:"en",name:"English"},{code:"es",name:"Español"},{code:"fr",name:"Français"},{code:"it",name:"Italiano"},{code:"pl",name:"Polski"},{code:"tr",name:"Türkçe"},{code:"ko",name:"한국어"},{code:"ja",name:"日本語"},{code:"el",name:"Ελληνικά"},{code:"uk",name:"Українська"},{code:"ar",name:"العربية"},{code:"ru",name:"Русский"},{code:"he",name:"עברית"},{code:"nl",name:"Nederlands"},{code:"sv",name:"Svenska"},{code:"da",name:"Dansk"},{code:"nb",name:"Norsk bokmål"},{code:"zh-Hans",name:"中文(简体)"},{code:"zh-Hant",name:"中文(繁體)"},{code:"pt-PT",name:"Português"},{code:"java",name:"Java (Keywords)"}],zd=["de","en","pt-PT"],Id=u2.filter(i=>zd.includes(i.code)),G0=i=>zd.includes(i),m2=Object.assign({"../../../VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/ar.lproj/Localizable.strings":()=>Q(()=>import("./Localizable-CxCno28C.js"),[],import.meta.url).then(i=>i.default),"../../../VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/da.lproj/Localizable.strings":()=>Q(()=>import("./Localizable-BAutdlBb.js"),[],import.meta.url).then(i=>i.default),"../../../VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/de.lproj/Localizable.strings":()=>Q(()=>import("./Localizable-Dk8F86qS.js"),[],import.meta.url).then(i=>i.default),"../../../VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/el.lproj/Localizable.strings":()=>Q(()=>import("./Localizable-rqA-20hM.js"),[],import.meta.url).then(i=>i.default),"../../../VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/en.lproj/Localizable.strings":()=>Q(()=>import("./Localizable-DBLIUcBd.js"),[],import.meta.url).then(i=>i.default),"../../../VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/es.lproj/Localizable.strings":()=>Q(()=>import("./Localizable-LSTVB2Q5.js"),[],import.meta.url).then(i=>i.default),"../../../VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/fr.lproj/Localizable.strings":()=>Q(()=>import("./Localizable-ByPZS4RL.js"),[],import.meta.url).then(i=>i.default),"../../../VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/he.lproj/Localizable.strings":()=>Q(()=>import("./Localizable-R-16GCrk.js"),[],import.meta.url).then(i=>i.default),"../../../VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/it.lproj/Localizable.strings":()=>Q(()=>import("./Localizable-DXAPah1g.js"),[],import.meta.url).then(i=>i.default),"../../../VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/ja.lproj/Localizable.strings":()=>Q(()=>import("./Localizable-CkJEmEEP.js"),[],import.meta.url).then(i=>i.default),"../../../VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/ko.lproj/Localizable.strings":()=>Q(()=>import("./Localizable-BudCXCER.js"),[],import.meta.url).then(i=>i.default),"../../../VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/nb.lproj/Localizable.strings":()=>Q(()=>import("./Localizable-DSvkBkp-.js"),[],import.meta.url).then(i=>i.default),"../../../VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/nl.lproj/Localizable.strings":()=>Q(()=>import("./Localizable-BJ55WGVD.js"),[],import.meta.url).then(i=>i.default),"../../../VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/pl.lproj/Localizable.strings":()=>Q(()=>import("./Localizable-BYJK0mdR.js"),[],import.meta.url).then(i=>i.default),"../../../VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/pt-PT.lproj/Localizable.strings":()=>Q(()=>import("./Localizable-CHv0OL9S.js"),[],import.meta.url).then(i=>i.default),"../../../VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/ru.lproj/Localizable.strings":()=>Q(()=>import("./Localizable-1QZ0wfvJ.js"),[],import.meta.url).then(i=>i.default),"../../../VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/sv.lproj/Localizable.strings":()=>Q(()=>import("./Localizable-M33nNbEe.js"),[],import.meta.url).then(i=>i.default),"../../../VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/tr.lproj/Localizable.strings":()=>Q(()=>import("./Localizable-BM86Igqt.js"),[],import.meta.url).then(i=>i.default),"../../../VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/uk.lproj/Localizable.strings":()=>Q(()=>import("./Localizable-UGog_aku.js"),[],import.meta.url).then(i=>i.default),"../../../VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/zh-Hans.lproj/Localizable.strings":()=>Q(()=>import("./Localizable-CaVEL1es.js"),[],import.meta.url).then(i=>i.default),"../../../VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/zh-Hant.lproj/Localizable.strings":()=>Q(()=>import("./Localizable-DqIDp_hh.js"),[],import.meta.url).then(i=>i.default)}),kd=Object.assign({"../../../VisuStruct-iOS/VisuStructXcodeOpen/VisuStruct/Java.strings":()=>Q(()=>import("./Java-Bpx1Vwvg.js"),[],import.meta.url).then(i=>i.default)}),c2=Object.assign({"../i18n/ar.strings":()=>Q(()=>import("./ar-WGaBG5hv.js"),[],import.meta.url).then(i=>i.default),"../i18n/da.strings":()=>Q(()=>import("./da-koCAf5IC.js"),[],import.meta.url).then(i=>i.default),"../i18n/de.strings":()=>Q(()=>import("./de-BXoZIww_.js"),[],import.meta.url).then(i=>i.default),"../i18n/el.strings":()=>Q(()=>import("./el-SUUletLz.js"),[],import.meta.url).then(i=>i.default),"../i18n/en.strings":()=>Q(()=>import("./en-C73wMUnL.js"),[],import.meta.url).then(i=>i.default),"../i18n/es.strings":()=>Q(()=>import("./es-DRonwtpE.js"),[],import.meta.url).then(i=>i.default),"../i18n/fr.strings":()=>Q(()=>import("./fr-CXZuqinr.js"),[],import.meta.url).then(i=>i.default),"../i18n/he.strings":()=>Q(()=>import("./he-CsI_Htol.js"),[],import.meta.url).then(i=>i.default),"../i18n/it.strings":()=>Q(()=>import("./it-BWu0GoFP.js"),[],import.meta.url).then(i=>i.default),"../i18n/ja.strings":()=>Q(()=>import("./ja-CTx7fAZr.js"),[],import.meta.url).then(i=>i.default),"../i18n/ko.strings":()=>Q(()=>import("./ko-FpGXyNsi.js"),[],import.meta.url).then(i=>i.default),"../i18n/nb.strings":()=>Q(()=>import("./nb-D1ut7Kv3.js"),[],import.meta.url).then(i=>i.default),"../i18n/nl.strings":()=>Q(()=>import("./nl-Dsn5rhjs.js"),[],import.meta.url).then(i=>i.default),"../i18n/pl.strings":()=>Q(()=>import("./pl-CGCl84p1.js"),[],import.meta.url).then(i=>i.default),"../i18n/pt-PT.strings":()=>Q(()=>import("./pt-PT-BUo8GEDc.js"),[],import.meta.url).then(i=>i.default),"../i18n/ru.strings":()=>Q(()=>import("./ru-DHObsyYC.js"),[],import.meta.url).then(i=>i.default),"../i18n/sv.strings":()=>Q(()=>import("./sv-C1WfipAE.js"),[],import.meta.url).then(i=>i.default),"../i18n/tr.strings":()=>Q(()=>import("./tr-B9AZN4-W.js"),[],import.meta.url).then(i=>i.default),"../i18n/uk.strings":()=>Q(()=>import("./uk-CklXCu2O.js"),[],import.meta.url).then(i=>i.default),"../i18n/zh-Hans.strings":()=>Q(()=>import("./zh-Hans-B8uL8a3v.js"),[],import.meta.url).then(i=>i.default),"../i18n/zh-Hant.strings":()=>Q(()=>import("./zh-Hant-CMSfiw5O.js"),[],import.meta.url).then(i=>i.default)});function Pa(i,e){var t;return(t=Object.entries(i).find(([n])=>n.endsWith(e)))==null?void 0:t[1]}function Sd(i){const e=new Map,t=i.replace(/\/\*[\s\S]*?\*\//g,"").replace(/^\s*\/\/.*$/gm,""),n=/"((?:[^"\\]|\\.)*)"\s*=\s*"((?:[^"\\]|\\.)*)"\s*;/g,a=s=>s.replace(/\\(u[0-9a-fA-F]{4}|.)/g,(r,o)=>o==="n"?` -`:o==="t"?" ":o.startsWith("u")&&o.length===5?String.fromCharCode(parseInt(o.slice(1),16)):o);for(const s of t.matchAll(n))e.set(a(s[1]),a(s[2]));return e}async function to(i){const e=i==="java"?Pa(kd,"/Java.strings"):Pa(m2,`/${i}.lproj/Localizable.strings`),t=Pa(c2,`/${i}.strings`),n=new Map;for(const a of[e,t])if(a)for(const[s,r]of Sd(await a()))n.set(s,r);return n}let _d="en",Td=new Map,Hn=new Map;const Va="appLanguageCode",kl="visustruct.keywords";let no=new Map,Sl=!1;const d2=i=>i.startsWith("element_")||i.startsWith("canvas_stub_");function h2(){try{const i=new URLSearchParams(location.search).get("lang")==="java"||localStorage.getItem(Va)==="java";return i&&(localStorage.setItem(Va,"en"),localStorage.setItem(kl,"1")),i}catch{return!1}}function g2(){try{return localStorage.getItem(kl)==="1"}catch{return!1}}async function Od(i,e=!0){if(i&&no.size===0){Hn.size===0&&(Hn=await to("en"));const t=Pa(kd,"/Java.strings");if(t)for(const[n,a]of Sd(await t()))d2(n)&&a!==Hn.get(n)&&no.set(n,a)}if(Sl=i,e)try{localStorage.setItem(kl,i?"1":"0")}catch{}}function p2(){return Sl}function f2(){if(h2())return"en";const i=new URLSearchParams(location.search).get("lang");if(i&&G0(i))return i;try{const e=localStorage.getItem(Va);if(e&&G0(e))return e}catch{}for(const e of navigator.languages??[navigator.language]){const t=e.toLowerCase();if(t.startsWith("pt"))return"pt-PT";const n=Id.find(a=>a.code===t.split("-")[0]);if(n)return n.code}return"en"}async function Ad(i,e=!0){if(Hn.size===0&&(Hn=await to("en")),Td=i==="en"?Hn:await to(i),_d=i,e)try{localStorage.setItem(Va,i)}catch{}const t=document.documentElement;t.lang=i==="java"?"en":i,t.dir=i==="ar"||i==="he"?"rtl":"ltr"}function Yn(){return _d}function p(i,...e){const t=(Sl?no.get(i):void 0)??Td.get(i)??Hn.get(i)??i;if(e.length===0)return t;let n=0;return t.replace(/%(?:(\d+)\$)?[@d]/g,(a,s)=>String(e[s?Number(s)-1:n++]??""))}const Qa=243,x2=244,Pd=40,ir=4,b2=1;function _l(i){const e=i.length,t=Qa+(e&255)+(e>>8)&255,n=i.reduce((a,s)=>a+s,0)&255;return Uint8Array.from([Qa,t,e&255,e>>8,...i,n,x2])}function v2(i,e,t){const n=Array.from(new TextEncoder().encode(i));return _l([Pd,e,t&255,t>>8&255,n.length&255,n.length>>8,...n])}function y2(i){if(i[0]!==Pd||i.length<6)return;const e=new TextDecoder().decode(Uint8Array.from(i.slice(6))),t=/"ret"\s*:\s*([^}]*)\}/.exec(e);return t?{idx:i[2]|i[3]<<8,value:z2(t[1].trim())}:void 0}function w2(i){const e=[];for(;;){const t=i.indexOf(Qa);if(t<0){i.length=0;break}if(i.splice(0,t),i.length<4)break;const n=i[2]|i[3]<<8;if(i[1]!==(Qa+i[2]+i[3]&255)||n>4096){i.splice(0,1);continue}if(i.lengthi.startsWith("element_")||i.startsWith("canvas_stub_");function h2(){try{const i=new URLSearchParams(location.search).get("lang")==="java"||localStorage.getItem(Va)==="java";return i&&(localStorage.setItem(Va,"en"),localStorage.setItem(kl,"1")),i}catch{return!1}}function g2(){try{return localStorage.getItem(kl)==="1"}catch{return!1}}async function Od(i,e=!0){if(i&&no.size===0){Vn.size===0&&(Vn=await to("en"));const t=Pa(kd,"/Java.strings");if(t)for(const[n,a]of Sd(await t()))d2(n)&&a!==Vn.get(n)&&no.set(n,a)}if(Sl=i,e)try{localStorage.setItem(kl,i?"1":"0")}catch{}}function p2(){return Sl}function f2(){if(h2())return"en";const i=new URLSearchParams(location.search).get("lang");if(i&&G0(i))return i;try{const e=localStorage.getItem(Va);if(e&&G0(e))return e}catch{}for(const e of navigator.languages??[navigator.language]){const t=e.toLowerCase();if(t.startsWith("pt"))return"pt-PT";const n=Id.find(a=>a.code===t.split("-")[0]);if(n)return n.code}return"en"}async function Ad(i,e=!0){if(Vn.size===0&&(Vn=await to("en")),Td=i==="en"?Vn:await to(i),_d=i,e)try{localStorage.setItem(Va,i)}catch{}const t=document.documentElement;t.lang=i==="java"?"en":i,t.dir=i==="ar"||i==="he"?"rtl":"ltr"}function Xn(){return _d}function p(i,...e){const t=(Sl?no.get(i):void 0)??Td.get(i)??Vn.get(i)??i;if(e.length===0)return t;let n=0;return t.replace(/%(?:(\d+)\$)?[@d]/g,(a,s)=>String(e[s?Number(s)-1:n++]??""))}const Qa=243,x2=244,Pd=40,ir=4,b2=1;function _l(i){const e=i.length,t=Qa+(e&255)+(e>>8)&255,n=i.reduce((a,s)=>a+s,0)&255;return Uint8Array.from([Qa,t,e&255,e>>8,...i,n,x2])}function v2(i,e,t){const n=Array.from(new TextEncoder().encode(i));return _l([Pd,e,t&255,t>>8&255,n.length&255,n.length>>8,...n])}function y2(i){if(i[0]!==Pd||i.length<6)return;const e=new TextDecoder().decode(Uint8Array.from(i.slice(6))),t=/"ret"\s*:\s*([^}]*)\}/.exec(e);return t?{idx:i[2]|i[3]<<8,value:z2(t[1].trim())}:void 0}function w2(i){const e=[];for(;;){const t=i.indexOf(Qa);if(t<0){i.length=0;break}if(i.splice(0,t),i.length<4)break;const n=i[2]|i[3]<<8;if(i[1]!==(Qa+i[2]+i[3]&255)||n>4096){i.splice(0,1);continue}if(i.lengthArray.from({length:e},(t,n)=>i>>>8*n&255);function _2(i){let e=0;for(let t=0;t>>0;return ei(e,4)}const ar=(i,e)=>_l([1,0,jd,i,...ei(e.length,2),...e]);function T2(i,e=I2){const t=new TextEncoder().encode(i),n=(4-t.length%Z1+Z1)%Z1,a=new Uint8Array(t.length+n).fill(10);a.set(t);const s=[ar(1,[0,...ei(a.length,4),..._2(a),...Array.from(new TextEncoder().encode(e))])],r=a.length-4;for(let o=0;oi.length===3&&i[0]===13,A2=i=>i.length===7||i.some((e,t)=>e===jd&&i[t+1]===240),Cd=()=>typeof navigator>"u"?void 0:navigator.serial,sr=()=>Cd()!==void 0,P2=(...i)=>`exec(${JSON.stringify(i.join("; "))})`,Bs=(i,e=24)=>P2("cyberpi.display.clear()",`cyberpi.display.show_label(${JSON.stringify(i)}, ${e}, 'center')`),Bd=Bs("VisuBot",32);class j2{constructor(){y(this,"port");y(this,"writer");y(this,"reader");y(this,"loop");y(this,"rx",[]);y(this,"idx",1);y(this,"frameWaiters",[]);y(this,"waiting",new Map);y(this,"queue",Promise.resolve());y(this,"listeners",new Set);y(this,"error");y(this,"connecting",!1)}listen(e){return this.listeners.add(e),()=>this.listeners.delete(e)}changed(){for(const e of this.listeners)e()}get connected(){return this.writer!==void 0&&!this.connecting}async connect(){const e=Cd();if(!e)throw new Error("Web Serial");const t=await e.requestPort();await t.open({baudRate:115200}),this.port=t,this.writer=t.writable.getWriter(),this.error=void 0,this.connecting=!0,this.changed(),this.loop=this.readLoop(),window.addEventListener("pagehide",()=>void this.disconnect(),{once:!0}),await new Promise(n=>setTimeout(n,3e3)),this.writer&&(this.rx.length=0,this.connecting=!1,this.changed(),await this.run(Bd))}async disconnect(e){if(!this.port)return this.error=e,this.changed();if(!e&&this.writer&&!this.connecting)for(const r of["mbot2.EM_stop('ALL')","cyberpi.led.off()",Bs("Bis bald!")])await this.send(r,ir,2e3).catch(()=>{});const t=this.port,n=this.writer,a=this.reader,s=this.loop;this.port=this.writer=this.reader=this.loop=void 0,this.error=e,this.connecting=!1;for(const r of this.waiting.values())r.reject(new Error(e??"getrennt"));this.waiting.clear();try{await(a==null?void 0:a.cancel()),await s,await(n==null?void 0:n.close())}catch{}try{n==null||n.releaseLock(),await t.close()}catch(r){console.warn("[mBot2] Schließen",r.message)}this.changed()}run(e){return this.send(e,ir,3e4).then(()=>{})}ask(e){return this.send(e,b2,3e3)}async upload(e,t=()=>{}){if(this.port||await this.connect(),!this.writer)throw new Error(this.error??"nicht verbunden");const n=T2(e),a=6+n.length+3;let s=0;const r=()=>t(++s,a),o=async()=>{await this.sendFrame(_l(k2),O2),r();for(const l of S2)await this.send(l,ir,3e3),r()};await o(),await o();for(const l of n)await this.sendFrame(l,A2),r();s=a-3,await o(),await this.restart()}sendFrame(e,t){const n=this.queue.then(async()=>{for(let a=0;a<3;a++){if(!this.writer)throw new Error("nicht verbunden");let s=()=>{};const r=new Promise(u=>s=u),o={match:t,resolve:s};this.frameWaiters.push(o),await this.writer.write(e);const l=await Promise.race([r.then(()=>!0),new Promise(u=>setTimeout(()=>u(!1),3e3))]);if(this.frameWaiters=this.frameWaiters.filter(u=>u!==o),l)return}throw new Error("keine Antwort")});return this.queue=n.catch(()=>{}),n}async restart(){const e=this.port;await this.disconnect("restart"),this.error=void 0,await new Promise(t=>setTimeout(t,300)),await e.open({baudRate:115200}),await new Promise(t=>setTimeout(t,500)),await e.close(),this.changed()}send(e,t,n){const a=this.queue.then(()=>new Promise((s,r)=>{if(!this.writer)return r(new Error("nicht verbunden"));const o=this.idx;this.idx=this.idx%65535+1;const l=setTimeout(()=>{this.waiting.delete(o),r(new Error("keine Antwort"))},n);this.waiting.set(o,{resolve:u=>(clearTimeout(l),s(u)),reject:u=>(clearTimeout(l),r(u))}),this.writer.write(v2(e,t,o)).catch(u=>{this.waiting.delete(o),r(u)})}));return this.queue=a.catch(()=>{}),a}async readLoop(){var e;for(;(e=this.port)!=null&&e.readable;){const t=this.port.readable.getReader();this.reader=t;try{for(;;){const{value:n,done:a}=await t.read();if(a)break;this.rx.push(...n);for(const s of w2(this.rx)){const r=this.frameWaiters.findIndex(u=>u.match(s));r>=0&&this.frameWaiters.splice(r,1)[0].resolve();const o=y2(s);if(!o)continue;const l=this.waiting.get(o.idx);this.waiting.delete(o.idx),l==null||l.resolve(o.value)}}}catch(n){const a=["BufferOverrunError","FramingError","BreakError","ParityError"].includes(n.name);console.warn("[mBot2] Lesefehler",n.name,n.message),!a&&this.port&&this.disconnect(n.message)}finally{t.releaseLock()}if(!this.writer)break}}}const oe=new j2,Dd=5,C2=i=>Number.isInteger(i)&&i>=0&&iString(Math.round(i*100)/100),pi={forward:{args:1,defaults:[H0],python:([i])=>`mbot2.straight(${pe(i)})`,label:([i])=>`${pe(i)} cm vorwärts`},backward:{args:1,defaults:[H0],python:([i])=>`mbot2.straight(${pe(-i)})`,label:([i])=>`${pe(i)} cm rückwärts`},turnLeft:{args:1,defaults:[90],python:([i])=>`mbot2.turn(${pe(-i)})`,label:([i])=>`${pe(i)}° nach links drehen`},turnRight:{args:1,defaults:[90],python:([i])=>`mbot2.turn(${pe(i)})`,label:([i])=>`${pe(i)}° nach rechts drehen`},stop:{args:0,python:()=>'mbot2.EM_stop("ALL")',label:()=>"anhalten"},drive:{args:2,python:([i,e])=>`mbot2.drive_power(${pe(i)}, ${pe(-e)})`,label:([i,e])=>`Räder links ${pe(i)} %, rechts ${pe(e)} %`},setLed:{args:3,python:([i,e,t])=>`cyberpi.led.on(${pe(i)}, ${pe(e)}, ${pe(t)})`,label:([i,e,t])=>`LEDs (${pe(i)}, ${pe(e)}, ${pe(t)})`},ledOff:{args:0,python:()=>"cyberpi.led.off()",label:()=>"LEDs aus"},ledColor:{args:1,text:!0,choices:Object.keys(qa),valid:([i])=>C2(i),python:([i],e)=>`cyberpi.led.on(${qa[e].join(", ")}, id=${i+1})`,label:([i],e)=>`LED ${i}: ${e}`},playTone:{args:2,python:([i,e])=>`cyberpi.audio.play_tone(${pe(i)}, ${pe(e/1e3)})`,label:([i,e])=>`Ton ${pe(i)} Hz, ${pe(e)} ms`},pause:{args:1,label:([i])=>`${pe(i)} ms warten`},resetTimer:{args:0,python:()=>"cyberpi.timer.reset()",label:()=>"Stoppuhr auf 0"},emotion:{args:0,text:!0,choices:B2,python:(i,e)=>`cyberpi.emotion.${e}()`,label:(i,e)=>`Gefühl: ${e}`},showText:{args:0,text:!0,python:(i,e)=>Bs(e),label:(i,e)=>`Bildschirm: ${e}`}},V0={red:{de:"rot",en:"red"},green:{de:"grün",en:"green"},blue:{de:"blau",en:"blue"},yellow:{de:"gelb",en:"yellow"},cyan:{de:"türkis",en:"cyan"},purple:{de:"lila",en:"purple"},white:{de:"weiß",en:"white"},black:{de:"schwarz",en:"black"}};let Tl="en";function D2(i){Tl=i==="de"?"de":"en"}const Z2=()=>Tl;function Zd(i){const e=i.trim().toLowerCase(),t=V0[e]??Object.values(V0).find(n=>n.de===e);return t?t[Tl]:e}const i1=i=>({python:`cyberpi.controller.is_press('${i}')`,simulated:!1}),wt={getDistance:{python:"mbuild.ultrasonic2.get(1)",simulated:100},getLine:{python:"mbuild.quad_rgb_sensor.get_line_sta('all', 1)",simulated:0},isLineLeft:{python:"mbuild.quad_rgb_sensor.is_line('L1', 1)",simulated:!1},isLineRight:{python:"mbuild.quad_rgb_sensor.is_line('R1', 1)",simulated:!1},getColor:{python:"mbuild.quad_rgb_sensor.get_color_sta('L1', 1)",simulated:"white"},isButtonA:i1("a"),isButtonB:i1("b"),isJoystickUp:i1("up"),isJoystickDown:i1("down"),isJoystickLeft:i1("left"),isJoystickRight:i1("right"),getBrightness:{python:"cyberpi.get_bri()",simulated:50},getLoudness:{python:"cyberpi.get_loudness('maximum')",simulated:0},getPitch:{python:"cyberpi.get_pitch()",simulated:0},getRoll:{python:"cyberpi.get_roll()",simulated:0},isShaken:{python:"cyberpi.is_shake()",simulated:!1},getBattery:{python:"cyberpi.get_battery()",simulated:100},getTimer:{python:"cyberpi.timer.get()",simulated:0}};function M2(i){const e=new Set;for(const t of i.matchAll(/\bmbot\s*\.\s*([A-Za-z_]\w*)\s*\(\s*\)/gu))t[1]in wt&&e.add(t[1]);return[...e]}function L2(i){const e=/^mbot\s*\.\s*led\s*\(([^()]*(?:\([^()]*\)[^()]*)*)\)\s*\.\s*setColor\s*\(([\s\S]*)\)\s*;?$/u.exec(i.trim());if(e)return{method:"ledColor",args:[e[1].trim(),e[2].trim()]};const t=/^mbot\s*\.\s*([A-Za-z_]\w*)\s*\(([\s\S]*)\)\s*;?$/u.exec(i.trim());if(!t)return;const n=t[2].trim();return{method:t[1],args:n===""?[]:N2(n)}}function Ua(i,e){const t=pi[i];if(!t)return;const n=e.length===0&&t.defaults?t.defaults:e;if(n.length===t.args)return!t.valid||t.valid(n)?n:void 0}function Q0(i,e,t=""){var a;const n=pi[i];return{method:i,args:e,python:(a=n.python)==null?void 0:a.call(n,e,t),waitMs:i==="pause"?Math.max(0,e[0]):void 0,label:n.label(e,t),...n.text?{text:t}:{}}}function Md(i){return i.map(e=>[e.method,...e.args.map(pe),...e.text!==void 0?[JSON.stringify(e.text)]:[]].join(" "))}function W2(i){let e=0;const t=i.trim(),n=()=>{const s=[];for(;;){for(;t[e]===" "||t[e]===",";)e++;if(e>=t.length||t[e]===")")return s;const r=/^(\d+)\s*[x×]\s*\(/u.exec(t.slice(e));if(r){e+=r[0].length;const c=n();if(t[e]!==")")throw new Error(`„)“ fehlt in „${i}“`);e++;for(let d=0;d{if(!(n in wt))return t;const a=e(n);return typeof a=="string"?JSON.stringify(n==="getColor"?Zd(a):a):String(a)}):i}function N2(i){const e=[];let t=0,n=!1,a=0;for(let s=0;s{const a=t==="turn"?((n+180)%360+360)%360-180:n;if(Math.abs(a)<1e-6)return[];const s=Math.round(Math.abs(a)*100)/100;return t==="drive"?[`${a>0?"forward":"backward"} ${s}`]:[a===-180?"turnRight 180":`${a>0?"turnRight":"turnLeft"} ${s}`]})}function Ld(i){let e=0;const t=i.trim(),n=()=>{const s=[];for(;;){for(;t[e]===" "||t[e]===",";)e++;if(e>=t.length||t[e]===")")return s;const r=/^(\d+)\s*[x×]\s*\(/u.exec(t.slice(e));if(r){e+=r[0].length;const u=n();if(t[e]!==")")throw new Error(`„)“ fehlt in „${i}“`);e++;for(let m=0;ma===i[s%t])){const a=V1(i.slice(0,t));return`${n} x ${t===1?a:`(${a})`}`}}return i.join(", ")}const Wd=["cyberpi","screen","joystick","buttons","leds","lightSensor","microphone","shield","powerSwitch","motors","wheels","ultrasonic","lineSensor","caster","chassis"],F2=i=>Wd.includes(i),J2=100;function Ed(i){switch(i.kind){case"finished":return"Simulation finished.";case"infiniteLoopWithoutBody":return"Infinite loop has no body.";case"unsupportedStatement":return`Unsupported statement: ${i.text}`;case"invalidExpression":return`Invalid expression: ${i.text}`;case"unknownVariable":return`Unknown variable: ${i.text}`;case"divisionByZero":return"Division by zero.";case"wholeNumberExpected":return"Please enter a whole number.";case"numberExpected":return"Please enter a number.";case"booleanExpected":return"Please enter true or false.";case"subprogramNotFound":return`No open diagram is called ${i.text}. The call was skipped.`;case"callTooDeep":return"Too many nested calls. Does a subprogram call itself?";case"callArguments":return`The call does not match the header of ${i.text}. Check the values in the parentheses.`;case"missingReturn":return`${i.text} ended without returning a value with return.`;case"fileNotFound":return`There is no file called ${i.text}.`;case"endOfFile":return`The file ${i.text} has no more lines.`;case"nullValue":return`${i.text} is null.`;case"other":return i.text}}class Be extends Error{constructor(e){super(Ed(e)),this.notice=e}}const Ge=i=>new Be({kind:"unsupportedStatement",text:i}),N=i=>new Be({kind:"invalidExpression",text:i}),Q1=i=>new Be({kind:"unknownVariable",text:i}),R2=()=>new Be({kind:"divisionByZero"}),Ya=new Map;function G2(i,e){Ya.set(i,e)}const Nd=()=>[...Ya];function q0(i){return i instanceof Be?i.notice:{kind:"other",text:i instanceof Error?i.message:String(i)}}function H2(i){if(i===0)return"0";if(!Number.isFinite(i))return Number.isNaN(i)?"nan":i>0?"inf":"-inf";const e=Math.floor(Math.log10(Math.abs(Number(i.toPrecision(12)))));if(e<-4||e>=12){const[n,a]=i.toExponential(11).split("e"),s=n.includes(".")?n.replace(/0+$/,"").replace(/\.$/,""):n,r=Number(a);return`${s}e${r<0?"-":"+"}${String(Math.abs(r)).padStart(2,"0")}`}const t=i.toFixed(Math.max(0,11-e));return t.includes(".")?t.replace(/0+$/,"").replace(/\.$/,""):t}function U0(i){return Number.isFinite(i)&&Math.round(i)===i?i.toFixed(1):H2(i)}function ke(i){switch(i.kind){case"int":return String(i.value);case"double":return U0(i.value);case"string":return i.value;case"boolean":return String(i.value);case"intArray":return"["+i.value.map(String).join(", ")+"]";case"doubleArray":return"["+i.value.map(U0).join(", ")+"]";case"stringArray":return"["+i.value.join(", ")+"]";case"booleanArray":return"["+i.value.map(String).join(", ")+"]";case"grid":return"["+V2(i).join(", ")+"]";case"reader":return`${i.className}(${i.file})`;case"writer":return`PrintWriter(${i.file})`;case"null":return"null"}}function V2(i){return i.value.map(e=>"["+e.map(t=>ke(Fd(i.elementType,t))).join(", ")+"]")}function Fd(i,e){switch(i){case"int":return{kind:"int",value:e};case"double":return{kind:"double",value:e};case"string":return{kind:"string",value:e};case"boolean":return{kind:"boolean",value:e}}}function Q2(i){return i==="string"?"":i==="boolean"?!1:0}function io(i){return i.kind==="intArray"||i.kind==="doubleArray"||i.kind==="stringArray"||i.kind==="booleanArray"||i.kind==="grid"}function q2(i){return i.kind==="int"||i.kind==="double"?i.value:NaN}const xt=i=>({kind:"int",value:i}),bt=i=>({kind:"double",value:i}),Ol=i=>i!==void 0&&/\s/u.test(i),Xa=i=>new RegExp("\\p{L}","u").test(i),q1=i=>new RegExp("\\p{N}","u").test(i);function ti(i){const e=Array.from(i);return e.length===0||!(Xa(e[0])||e[0]==="_")?!1:e.every(t=>Xa(t)||q1(t)||t==="_")}function sn(i){switch(i.toLowerCase()){case"int":return"int";case"double":return"double";case"string":return"string";case"char":return"string";case"boolean":case"bool":return"boolean";default:return}}function $0(i){return i.kind==="int"?"int":i.kind==="double"?"double":i.kind==="boolean"?"boolean":"string"}function st(i){const e=Array.from(i);if(e.length===3&&e[0]==="'"&&e[2]==="'")return e[1];if(e.length<2||e[0]!=='"'||e[e.length-1]!=='"')return;const t=e.slice(1,-1).join("");if(/^(?:[^"\\]|\\.)*$/u.test(t))return t.replaceAll('\\"','"').replaceAll("\\n",` -`)}function Y0(i){return i.replaceAll("(int)","").replaceAll("(double)","").trim()}function Al(i){const e=new Array(i.length).fill(!1);let t=0,n=!1,a=!1;return i.forEach((s,r)=>{if(n){a?a=!1:s==="\\"?a=!0:s==='"'&&(n=!1);return}switch(s){case'"':n=!0;break;case"(":case"[":t+=1;break;case")":case"]":t-=1;break;default:e[r]=t===0}}),e}function Ka(i,e){const t=Array.from(i),n=Array.from(e),a=Al(t),s=[];let r=[],o=0;for(;ot[o+m]===u)&&a.slice(o,l).every(Boolean)){s.push(r.join("").trim()),r=[],o=l;continue}r.push(t[o]),o+=1}return s.push(r.join("").trim()),s}function U2(i){const e=Array.from(i),t=Al(e);for(let n=0;n=","<=","==","!="].includes(o)&&(a=o)}if(a===void 0&&(e[n]==="<"||e[n]===">")&&(a=e[n]),a===void 0)continue;const s=e.slice(0,n).join("").trim(),r=e.slice(n+a.length).join("").trim();return{lhs:s,op:a,rhs:r}}}function Ds(i,e){let t=0,n=!1,a=!1;for(let s=e;se.length||!t.every((r,o)=>e[a+o]===r))continue;const s=a+t.length-1;if(Ds(e,s)===e.length-1)return{lhs:e.slice(0,a).join("").trim(),rhs:e.slice(s+1,-1).join("").trim()}}}function qi(i){const e=i.trim();for(const t of["if","while","until","switch"]){if(!e.startsWith(t))continue;const n=e.slice(t.length);if(!(n===""||Ol(n[0])||n[0]==="("))continue;let a=n.trim();const s=Jd(a);return s!==void 0&&(a=s),a===""?"true":a}return e===""?"true":e}function o1(i){const e=i.trim(),t=e.indexOf("[");if(!e.endsWith("]")||t<0)return;const n=e.slice(0,t).trim();if(!ti(n))return;const a=[];let s=t;for(;s2))return{arrayName:n,indexExpressions:a}}function Y2(i){const e=i.trim();if(!e.endsWith(")"))return;const t=/^([A-Za-z_]\w*(?:\s*\[[^\[\]]*\])*|"(?:[^"\\]|\\.)*")\s*\.\s*([A-Za-z_]\w*)\s*\(/u.exec(e);if(!t)return;const n=Array.from(e),a=Array.from(t[0]).length-1;if(Ds(n,a)!==n.length-1)return;const s=n.slice(a+1,-1).join("").trim();return{target:t[1],method:t[2],args:s===""?[]:Ka(s,",")}}function X0(i){return ti(i)||o1(i)!==void 0}function K0(i){const e=[];let t="",n=!1,a=!1,s=0;for(const r of i){if(a){t+=r,a=!1;continue}if(r==="\\"){t+=r,a=!0;continue}if(r==='"'){n=!n,t+=r;continue}if(!n&&r==="("&&(s+=1),!n&&r===")"&&(s-=1),r==="+"&&!n&&s===0){e.push(t),t="";continue}t+=r}if(n)throw N(i);return e.push(t),e}function X2(i){const e=[];let t=0,n="";for(const a of i){if(a==="{"&&(t+=1),a==="}"&&(t-=1),a===","&&t===0){e.push(n),n="";continue}n+=a}return n.trim()!==""&&e.push(n),e}function eu(i){const e=Array.from(i),t=[];let n=0;for(;n1)throw N(i)}else if(!q1(e[n]))break;n+=1}const o=e.slice(s,n).join("");if(o==="."||!/^[0-9]*\.?[0-9]*$/.test(o))throw N(i);t.push({t:"number",literal:o,value:Number(o)});continue}if(Xa(a)||a==="_"){const s=n;for(;n=0&&s=0&&o=0&&sk1(t).trim());return e.length===1&&e[0].includes(";")?tu(e[0].split(";").map(t=>t.trim())):tu(e)}const nt=i=>i.frame?{frame:i.frame,callPath:i.callPath}:{};function Gt(i,e=[],t={}){const n=[],a=s=>n.push(t.frame?{...s,...t}:s);return i.forEach((s,r)=>{const o=[...e,r],l=s.textLines.join(" ").trim();switch(s.type){case z.anweisung:l!==""&&l!=="ø"&&a({path:o,text:l,kind:"statement"});break;case z.verzweigung:a({path:o,text:l||"true",kind:"branch",cases:s.cases});break;case z.fallauswahl:a({path:o,text:l||"0",kind:"switchSelection",cases:s.cases});break;case z.forSchleife:a({path:o,text:l,kind:"forLoopStart",loopBody:s.loopBody,forParts:so(s.textLines)});break;case z.whileSchleife:a({path:o,text:l||"true",kind:"whileLoop",loopBody:s.loopBody});break;case z.doUntilSchleife:a({path:o,text:l||"true",kind:"doUntilLoop",loopBody:s.loopBody});break;case z.endlosschleife:a({path:o,text:l||"true",kind:"infiniteLoop",loopBody:s.loopBody});break;case z.aussprung:a({path:o,text:l,kind:"jump"});break;case z.aufruf:l!==""&&l!=="ø"&&a({path:o,text:l,kind:"call"});break}}),n}function e3(i,e){const t=i.trim().replaceAll(",",".");switch(e){case"int":if(!/^[+-]?[0-9]+$/.test(t))throw new Be({kind:"wholeNumberExpected"});return xt(Number(t));case"double":if(!/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][+-]?[0-9]+)?$/.test(t))throw new Be({kind:"numberExpected"});return bt(Number(t));case"string":return{kind:"string",value:i};case"boolean":switch(t.toLowerCase()){case"true":case"wahr":return{kind:"boolean",value:!0};case"false":case"falsch":return{kind:"boolean",value:!1};default:throw new Be({kind:"booleanExpected"})}}}function nu(){return{stepIndex:0,variables:new Map,outputLines:[],isHalted:!1,files:new Map,robotActions:[]}}function t3(i,e){for(let t=0;tt===e.path[n])}function pt(i){const e=/^(void|int|double|String|boolean)\s+([A-Za-z_]\w*)\s*\((.*)\)$/u.exec(k1(i));if(!e)return;const t=[];if(e[3].trim()!=="")for(const n of e[3].split(",")){const a=/^(int|double|String|boolean|char)\s*((?:\[\s*\]){0,2})\s+([A-Za-z_]\w*)$/u.exec(n.trim());if(!a)return;const s=(a[2].match(/\[/gu)??[]).length;t.push({type:sn(a[1]),name:a[3],...s>0?{dims:s}:{}})}return{returnType:sn(e[1]),name:e[2],params:t}}function Rd(i){const e=/^(?:(?:(int|double|String|boolean)\s+)?([A-Za-z_]\w*)\s*=\s*)?([A-Za-z_]\w*)\s*\((.*)\)$/u.exec(k1(i));if(e)return{targetType:e[1]?sn(e[1]):void 0,target:e[2],name:e[3],args:e[4].trim()===""?[]:Ka(e[4],",")}}function es(i){var t,n;const e=k1(i);return((t=pt(e))==null?void 0:t.name)??((n=Rd(e))==null?void 0:n.name)??e.replace(/\(\s*\)$/u,"").trim()}class fi{constructor(e,t=()=>{}){y(this,"steps");y(this,"state",nu());y(this,"nextFrame",1);y(this,"callDepth",0);y(this,"frames",new Map);y(this,"peeking",!1);y(this,"robotSensors",{});this.resolveSubprogram=t,this.steps=Gt(e.elements)}get currentStepPath(){const e=this.steps[this.state.stepIndex];return(e==null?void 0:e.callPath)??(e==null?void 0:e.path)}get canStep(){return!this.state.isHalted&&!this.state.inputRequest&&this.state.stepIndex ${ke(n)}`}catch(n){this.state.inputErrorNotice=q0(n);return}this.state.inputRequest=void 0,this.state.inputErrorNotice=void 0,this.state.stepIndex+=1,this.state.notice=this.finishedIfAtEnd()}}finishedIfAtEnd(){return this.state.stepIndex>=this.steps.length?{kind:"finished"}:void 0}splice(e){this.steps.splice(this.state.stepIndex,1,...e)}noticeAfterEntering(e){return e.length>0?void 0:this.finishedIfAtEnd()}executeBranch(e){const t=e.cases;if(!t||t.length<2)throw Ge(e.text);const n=qi(e.text),a=this.evaluateBool(n),s=a?0:1,r=Gt(t[s].elements,[...e.path,s],nt(e));this.splice(r),this.state.lastTrace=`${n} -> ${a}`,this.state.notice=this.noticeAfterEntering(r)}executeSwitchSelection(e){const t=e.cases;if(!t||t.length===0)throw Ge(e.text);const n=qi(e.text),a=this.evaluateSwitchSelector(n),s=t3(a,t)??t.length-1,r=Gt(t[s].elements,[...e.path,s],nt(e));this.splice(r),this.state.lastTrace=`${n} -> ${t[s].name}`,this.state.notice=this.noticeAfterEntering(r)}executeForLoopStart(e){const t=so(e.forParts??[e.text]);t[0]!==""&&this.executeStatement(t[0]),this.splice([{...nt(e),path:e.path,text:t[1],kind:"forLoopCondition",loopBody:e.loopBody,forParts:t}])}executeForLoopCondition(e){const t=so(e.forParts??[e.text]),n=t[1]===""?"true":t[1],a=this.evaluateBool(n);if(this.state.lastTrace=`${n} -> ${a}`,a){const s=Gt(e.loopBody??[],[...e.path,0],nt(e));this.splice([...s,{...nt(e),path:e.path,text:t[2],kind:"forLoopIncrement",loopBody:e.loopBody,forParts:t},{...nt(e),path:e.path,text:t[1],kind:"forLoopCondition",loopBody:e.loopBody,forParts:t}])}else this.splice([]),this.state.notice=this.finishedIfAtEnd()}executeForLoopIncrement(e){const t=e.text.trim();t!==""&&this.executeIncrement(t),this.splice([])}executeWhileLoop(e){const t=qi(e.text),n=this.evaluateBool(t);if(this.state.lastTrace=`${t} -> ${n}`,n){const a=Gt(e.loopBody??[],[...e.path,0],nt(e));this.splice([...a,{...nt(e),path:e.path,text:e.text,kind:"whileLoop",loopBody:e.loopBody}]),this.state.notice=this.noticeAfterEntering(a)}else this.splice([]),this.state.notice=this.finishedIfAtEnd()}enterDoUntilLoop(e){const t=Gt(e.loopBody??[],[...e.path,0],nt(e));this.splice([...t,{...nt(e),path:e.path,text:e.text,kind:"doUntilCondition",loopBody:e.loopBody}]),this.state.notice=this.noticeAfterEntering(t)}executeDoUntilCondition(e){const t=qi(e.text),n=this.evaluateBool(t);if(this.state.lastTrace=`${t} -> ${n}`,n){const a=Gt(e.loopBody??[],[...e.path,0],nt(e));this.splice([...a,{...nt(e),path:e.path,text:e.text,kind:"doUntilCondition",loopBody:e.loopBody}])}else this.splice([]),this.state.notice=this.finishedIfAtEnd()}enterInfiniteLoop(e){const t=Gt(e.loopBody??[],[...e.path,0],nt(e));this.splice([...t,{...nt(e),path:e.path,text:e.text,kind:"infiniteLoop",loopBody:e.loopBody}]),this.state.lastTrace="true -> true",this.state.notice=t.length>0?void 0:{kind:"infiniteLoopWithoutBody"}}executeJump(e){const t=e.frame??0,n=o=>o.lengthl===e.path[u]);let a=this.steps.length,s="end";for(let o=this.state.stepIndex+1;o ${s}`,s==="return"&&this.finishFrame(r),this.state.notice=this.finishedIfAtEnd()}executeCall(e){const t=e.text,n=this.resolveSubprogram(es(t));if(!n){this.splice([]),this.state.lastTrace=`${t} -> ?`,this.state.notice={kind:"subprogramNotFound",text:t},this.state.stepIndex>=this.steps.length&&(this.state.notice={kind:"finished"});return}const a=Rd(t),s=pt(n.caption);if(s?((a==null?void 0:a.args.length)??0)!==s.params.length||(a==null?void 0:a.target)!==void 0&&!s.returnType:a!==void 0&&(a.args.length>0||a.target!==void 0))throw new Be({kind:"callArguments",text:(s==null?void 0:s.name)??es(t)});if(this.callDepth>=J2)throw new Be({kind:"callTooDeep"});const o=new Map,l=[];s==null||s.params.forEach((d,h)=>{const g=a.args[h].trim();if(!d.dims){o.set(d.name,this.evaluateExpression(g,d.type));return}const f=this.state.variables.get(g);if(!f)throw/^[A-Za-z_]\w*$/u.test(g)?new Be({kind:"unknownVariable",text:g}):N(g);if(!(d.dims===1?f.kind===`${d.type}Array`:f.kind==="grid"&&f.elementType===d.type))throw N(g);o.set(d.name,f),l.push({param:d.name,callerName:g})}),this.callDepth+=1;const u={frame:this.nextFrame++,callPath:e.callPath??e.path};s&&(this.frames.set(u.frame,{saved:this.state.variables,header:s,call:a,references:l}),this.state.variables=o);const m=Gt(n.elements,[],u);this.splice([...m,{...u,path:e.path,text:t,kind:"callEnd"}]);const c=s==null?void 0:s.params.map((d,h)=>`${d.name} = ${d.dims?a.args[h].trim():ke(o.get(d.name))}`).join(", ");this.state.lastTrace=c?`${t} -> ${c}`:`${t} -> call`}executeCallEnd(e){this.callDepth-=1,this.splice([]),this.state.lastTrace=`${e.text} -> return`,this.finishFrame(e),this.state.notice=this.finishedIfAtEnd()}executeReturn(e){const t=e.frame??0,n=k1(e.text).slice(6).trim(),a=this.frames.get(t);if(a&&n!==""){if(!a.header.returnType)throw N(e.text);a.returnValue=this.evaluateExpression(n,a.header.returnType)}const s=a!=null&&a.returnValue?`${e.text} -> ${ke(a.returnValue)}`:`${e.text} -> return`;if(t===0){this.steps.splice(this.state.stepIndex),this.state.lastTrace=s,this.state.notice={kind:"finished"};return}let r=this.state.stepIndex+1;for(;r0?new Map(t.saved):t.saved;for(const m of t.references){const c=this.state.variables.get(m.param);c&&n.set(m.callerName,c)}this.state.variables=n;const a=t.returnValue;if(t.header.returnType&&!a)throw new Be({kind:"missingReturn",text:t.header.name});const s=(l=t.call)==null?void 0:l.target;if(!s||!a)return;let r=(u=t.call)==null?void 0:u.targetType;if(!r)try{r=this.inferTargetValueType(s)}catch{r=t.header.returnType}const o=r==="double"&&a.kind==="int"?bt(a.value):r==="string"?{kind:"string",value:ke(a)}:a;if($0(o)!==r)throw N(e.text);this.assignValue(o,s),this.state.lastTrace=`${s} = ${e.text.slice(e.text.indexOf("=")+1).trim()} -> ${ke(o)}`}executeStatement(e){const t=this.state,n=e.trim(),a=n.toLowerCase();if(a.startsWith("input:")){t.inputRequest=this.parseInputRequest(n),t.inputErrorNotice=void 0;return}if(a.startsWith("output:")||a.startsWith("print:")){const g=n.slice(a.startsWith("output:")?7:6),f=this.peek(()=>this.renderOutputExpression(g)),x=this.evaluateOutputExpression(g);t.outputLines.push(x),t.lastTrace=`${f} -> ${x}`;return}const s=L2(n);if(s){this.executeMBotCommand(s.method,s.args,n);return}if(this.executeFileStatement(n))return;if(n.endsWith("++")||n.endsWith("--")||n.includes("+=")||n.includes("-=")){this.executeIncrement(n);return}const r=n.indexOf("=");if(r<0)throw Ge(n);const o=n.slice(0,r).trim(),l=n.slice(r+1),u=this.parseArrayDeclaration(o,l);if(u){t.variables.set(u.name,u.value),t.lastTrace=`${u.name} = new ${u.typeName}[${u.count}]`;return}const m=this.parseAssignmentTarget(o);let c;try{c=this.peek(()=>this.renderNumericExpression(l))}catch{c=l.trim()}let d=m.valueType;if(!d)try{d=this.inferTargetValueType(m.variableName)}catch{d="int"}const h=this.evaluateExpression(l,d);this.assignValue(h,m.variableName),t.lastTrace=`${m.variableName} = ${c} -> ${ke(h)}`}executeMBotCommand(e,t,n){var r;if((r=pi[e])!=null&&r.text){const o=pi[e];if(t.length!==o.args+1)throw N(n);const l=Ua(e,t.slice(0,-1).map(c=>this.evaluateDouble(c)));if(!l)throw N(n);const u=Q0(e,l,this.evaluateOutputExpression(t[t.length-1])),m=o.choices;if(m&&!m.includes(u.text??""))throw N(`${n} (${m.join(", ")})`);this.state.robotActions.push(u),this.state.lastTrace=`${n} -> ${u.label}`;return}const a=Ua(e,t.map(o=>this.evaluateDouble(o)));if(!a)throw N(n);const s=Q0(e,a);this.state.robotActions.push(s),this.state.lastTrace=`${n} -> ${s.label}`}executeFileStatement(e){const t=this.state,n=k1(e).trim(),a=/^(?:(Scanner|BufferedReader|PrintWriter)\s+)?([A-Za-z_]\w*)\s*=\s*new\s+(Scanner|BufferedReader|PrintWriter)\s*\(([\s\S]*)\)$/u.exec(n);if(a){const[,m,c,d,h]=a;if(m&&m!==d)throw N(n);const g=d==="Scanner"?/^new\s+File\s*\(([\s\S]+)\)$/u.exec(h.trim()):d==="BufferedReader"?/^new\s+FileReader\s*\(([\s\S]+)\)$/u.exec(h.trim()):/^(?:new\s+(?:File|FileWriter)\s*\(([\s\S]+)\)|([\s\S]+))$/u.exec(h.trim());if(!g)throw Ge(n);const f=this.fileNameValue(g[1]??g[2]);if(d==="PrintWriter")t.variables.set(c,{kind:"writer",file:f,text:""});else{const b=this.fileContent(f).split(/\r?\n/u);b[b.length-1]===""&&b.pop(),t.variables.set(c,{kind:"reader",className:d,file:f,lines:b,next:0})}return t.lastTrace=`${c} = new ${d}(${f})`,!0}const s=/^Files\s*\.\s*writeString\s*\(\s*(?:Path\s*\.\s*of|Paths\s*\.\s*get)\s*\(([^()]+)\)\s*,([\s\S]+)\)$/u.exec(n);if(s){const m=this.fileNameValue(s[1]),c=this.evaluateOutputExpression(s[2]);return t.files.set(m,c),t.lastTrace=`${m} ← ${JSON.stringify(c)}`,!0}const r=/^([A-Za-z_]\w*)\s*\.\s*(println|print|close)\s*\(([\s\S]*)\)$/u.exec(n),o=r&&t.variables.get(r[1]);if(!r||!o)return!1;if(o.kind==="null")throw new Be({kind:"nullValue",text:r[1]});if(o.kind==="reader"&&r[2]==="close")return t.lastTrace=`${r[1]}.close()`,!0;if(o.kind!=="writer")return!1;if(r[2]==="close")return t.files.set(o.file,o.text),t.lastTrace=`${o.file} ← ${JSON.stringify(o.text)}`,!0;const l=r[3].trim()===""?"":this.evaluateOutputExpression(r[3]),u=r[2]==="println"?l+` -`:l;return t.variables.set(r[1],{...o,text:o.text+u}),t.lastTrace=`${r[1]}.${r[2]}(${JSON.stringify(l)})`,!0}fileNameValue(e){const t=e.trim(),n=st(t);if(n!==void 0)return n;const a=this.evaluateReference(t);if((a==null?void 0:a.kind)==="string")return a.value;throw N(t)}fileContent(e){const t=this.state.files.get(e)??Ya.get(e);if(t===void 0)throw new Be({kind:"fileNotFound",text:e});return t}readerMethod(e,t,n,a){if(n.args.length)throw N(a);const s=t.next0?"+":"-";if(r.kind==="int"){t.set(s,xt(r.value+a)),this.state.lastTrace=`${s} = ${r.value} ${o} 1 -> ${r.value+a}`;return}if(r.kind==="double"){const l=r.value+a;t.set(s,bt(l)),this.state.lastTrace=`${s} = ${ke(r)} ${o} 1 -> ${ke(bt(l))}`;return}throw Ge(e)}for(const[n,a]of[["+=",1],["-=",-1]]){const s=e.indexOf(n);if(s<0)continue;const r=e.slice(0,s).trim(),o=e.slice(s+2),l=t.get(r);if(!ti(r)||!l)throw Ge(e);const u=a>0?"+":"-";if(l.kind==="int"){const m=this.evaluateInt(o),c=l.value+a*m;t.set(r,xt(c)),this.state.lastTrace=`${r} = ${l.value} ${u} ${m} -> ${c}`;return}if(l.kind==="double"){const m=this.evaluateDouble(o),c=l.value+a*m;t.set(r,bt(c)),this.state.lastTrace=`${r} = ${ke(l)} ${u} ${ke(bt(m))} -> ${ke(bt(c))}`;return}throw Ge(e)}this.executeStatement(e)}parseAssignmentTarget(e){if(o1(e))return{variableName:e.trim()};const t=e.split(/\s+/u).filter(Boolean);let n,a;if(t.length===1)n=t[0];else if(t.length===2&&sn(t[0]))n=t[1],a=sn(t[0]);else if(t.length===3&&t[0]==="const"&&sn(t[1]))n=t[2],a=sn(t[1]);else throw Ge(e);if(!X0(n))throw Ge(e);return{variableName:n,valueType:a}}parseInputRequest(e){const t=e.slice(6).trim(),n=/^(\S+)(?:\s+(\S+))?(?:\s+([\s\S]*))?$/u.exec(t);if(!n)throw Ge(e);const a=[n[1],n[2],n[3]].filter(m=>m!==void 0);let s,r,o;const l=sn(a[0]);if(a.length>=2&&l?(s=a[1],r=l,o=(a[2]??"").trim()):(s=a[0],r=this.inferTargetValueType(s),o=(a[1]??"").trim()),!X0(s))throw Ge(e);const u=st(o)??o;return{variableName:s,valueType:r,prompt:u===""?`${s}:`:u}}parseArrayDeclaration(e,t){const n=e.split(/\s+/u).filter(Boolean);if(n.length!==2||!n[0].endsWith("[]"))return;const a=n[0].endsWith("[][]"),s=n[0].slice(0,a?-4:-2),r=sn(s),o=n[1];if(!r||!ti(o))throw Ge(e);if(a)return this.parseGridDeclaration(o,s,r,t);const l=t.trim();if(l.startsWith("{")&&l.endsWith("}")){const h=l.slice(1,-1).split(",").map(f=>f.trim());let g;switch(r){case"int":g={kind:"intArray",value:h.map(f=>this.evaluateInt(f))};break;case"double":g={kind:"doubleArray",value:h.map(f=>this.evaluateDouble(f))};break;case"string":g={kind:"stringArray",value:h.map(f=>st(f)??this.evaluateOutputExpression(f))};break;case"boolean":g={kind:"booleanArray",value:h.map(f=>this.evaluateBool(f))};break}return{name:o,typeName:s,count:h.length,value:g}}const u=`new ${s}[`;if(!l.startsWith(u)){const h=this.evaluateStringMethod(l);if((h==null?void 0:h.kind)==="stringArray"&&r==="string")return{name:o,typeName:s,count:h.value.length,value:h}}if(!l.startsWith(u)||!l.endsWith("]"))throw Ge(t);const m=l.slice(u.length,-1),c=this.evaluateInt(m);if(c<0)throw N(m);const d=r==="int"?{kind:"intArray",value:new Array(c).fill(0)}:r==="double"?{kind:"doubleArray",value:new Array(c).fill(0)}:r==="boolean"?{kind:"booleanArray",value:new Array(c).fill(!1)}:{kind:"stringArray",value:new Array(c).fill("")};return{name:o,typeName:s,count:c,value:d}}parseGridDeclaration(e,t,n,a){var c;const s=a.trim(),r=d=>{switch(n){case"int":return this.evaluateInt(d);case"double":return this.evaluateDouble(d);case"boolean":return this.evaluateBool(d);case"string":return st(d.trim())??this.evaluateOutputExpression(d)}};if(s.startsWith("{")&&s.endsWith("}")){const d=X2(s.slice(1,-1)).map(h=>{const g=h.trim();if(!g.startsWith("{")||!g.endsWith("}"))throw N(g);return g.slice(1,-1).trim()===""?[]:g.slice(1,-1).split(",").map(f=>r(f.trim()))});return{name:e,typeName:t,count:`${d.length}][${((c=d[0])==null?void 0:c.length)??0}`,value:{kind:"grid",elementType:n,value:d}}}const o=new RegExp(String.raw`^new\s+${t}\s*\[(.+)\]\s*\[(.+)\]$`,"u").exec(s);if(!o)throw Ge(a);const l=this.evaluateInt(o[1]),u=this.evaluateInt(o[2]);if(l<0)throw N(o[1]);if(u<0)throw N(o[2]);const m={kind:"grid",elementType:n,value:Array.from({length:l},()=>new Array(u).fill(Q2(n)))};return{name:e,typeName:t,count:`${l}][${u}`,value:m}}arrayIndex(e){const t=this.evaluateInt(e);if(t<0)throw N(e);return t}evaluateReference(e){const t=e.trim(),n=this.state.variables.get(t);if(n)return n;const a=this.evaluateStringMethod(t);if(a)return a;const s=/^\(\s*char\s*\)\s*(.+)$/su.exec(t);if(s){const o=this.evaluateInt(s[1]);if(!(o>=0&&o<=1114111))throw N(t);return{kind:"string",value:String.fromCodePoint(o)}}const r=o1(t);if(r)return this.valueInArray(r.arrayName,r.indexExpressions.map(o=>this.arrayIndex(o)))}evaluateStringMethod(e){const t=Y2(e);if(!t)return;const n=this.evaluateStaticCall(e,t);if(n)return n;const a=this.state.variables.get(t.target.trim());if((a==null?void 0:a.kind)==="reader")return this.readerMethod(t.target.trim(),a,t,e);if((a==null?void 0:a.kind)==="null")throw new Be({kind:"nullValue",text:t.target.trim()});const s=st(t.target)??this.stringValueOf(t.target);if(s===void 0)return;const r=t.args,o=d=>{const h=r[d];if(h===void 0)throw N(e);const g=st(h.trim());if(g!==void 0)return g;const f=this.evaluateReference(h);if((f==null?void 0:f.kind)==="string")return f.value;throw N(h)},l=d=>{if(r[d]===void 0)throw N(e);return this.evaluateInt(r[d])},u=d=>{if(r.length!==d)throw N(e)},m=Array.from(s),c=(d,h)=>{if(d<0||d>h)throw N(e);return d};switch(t.method){case"length":return u(0),xt(m.length);case"charAt":return u(1),{kind:"string",value:m[c(l(0),m.length-1)]};case"substring":{if(r.length!==1&&r.length!==2)throw N(e);const d=c(l(0),m.length),h=r.length===2?c(l(1),m.length):m.length;if(h0&&h[h.length-1]==="";)h.pop();return{kind:"stringArray",value:h}}default:return}}evaluateStaticCall(e,t){const n=()=>{if(t.args.length!==1)throw N(e);return t.args[0]},a=s=>{const r=st(s.trim());if(r!==void 0)return r;const o=this.evaluateReference(s);if((o==null?void 0:o.kind)==="string")return o.value;throw N(s)};switch(`${t.target}.${t.method}`){case"Integer.parseInt":{const s=a(n()).trim();if(!/^[+-]?\d+$/u.test(s))throw new Be({kind:"wholeNumberExpected"});return xt(Number(s))}case"Double.parseDouble":{const s=Number(a(n()).trim());if(!Number.isFinite(s))throw new Be({kind:"numberExpected"});return bt(s)}case"String.valueOf":return{kind:"string",value:this.evaluateOutputExpression(n())};case"Files.readString":{const s=/^(?:Path\s*\.\s*of|Paths\s*\.\s*get)\s*\(\s*("(?:[^"\\]|\\.)*")\s*\)$/u.exec(n().trim());if(!s)throw N(e);const r=st(s[1]),o=Ya.get(r);if(o===void 0)throw new Be({kind:"fileNotFound",text:r});return{kind:"string",value:o}}default:return}}stringValueOf(e){const t=e.trim(),n=this.state.variables.get(t);if(n)return n.kind==="string"?n.value:void 0;const a=o1(t);if(!a)return;const s=this.valueInArray(a.arrayName,a.indexExpressions.map(r=>this.arrayIndex(r)));return s.kind==="string"?s.value:void 0}substituteStringCalls(e){if(!e.includes("("))return e;let t="",n=e;const a=/([A-Za-z_]\w*(?:\[[^\[\]]*\])*|"(?:[^"\\]|\\.)*")\s*\.\s*(length|indexOf|lastIndexOf|compareTo|charAt|parseInt|parseDouble)\s*\(/u;for(let s=a.exec(n);s;s=a.exec(n)){const r=s.index+s[0].length-1,o=Ds(Array.from(n),Array.from(n.slice(0,r)).length);if(o===void 0)break;const l=Array.from(n),u=l.slice(Array.from(n.slice(0,s.index)).length,o+1).join(""),m=this.evaluateStringMethod(u),c=l.slice(0,Array.from(n.slice(0,s.index)).length).join(""),d=(m==null?void 0:m.kind)==="string"?ao(m.value):void 0;(m==null?void 0:m.kind)==="int"?t+=c+String(m.value):(m==null?void 0:m.kind)==="double"?t+=c+(Number.isInteger(m.value)?m.value.toFixed(1):String(m.value)):d!==void 0?t+=c+String(d):t+=c+u,n=l.slice(o+1).join("")}return t+n}valueInArray(e,t){const n=this.state.variables.get(e);if(!n)throw Q1(e);const a=`${e}[${t.join("][")}]`;if(n.kind==="grid"){if(t.length!==2)throw N(a);const r=n.value[t[0]];if(!r||t[1]>=r.length)throw N(a);return Fd(n.elementType,r[t[1]])}if(t.length!==1)throw N(a);const s=t[0];if(!io(n))throw N(e);if(s>=n.value.length)throw N(a);switch(n.kind){case"intArray":return xt(n.value[s]);case"doubleArray":return bt(n.value[s]);case"stringArray":return{kind:"string",value:n.value[s]};case"booleanArray":return{kind:"boolean",value:n.value[s]};default:throw N(e)}}inferTargetValueType(e){const t=e.trim(),n=this.state.variables.get(t);if(n)return $0(n);const a=o1(t);if(a){const s=this.state.variables.get(a.arrayName);if(!s)throw Q1(a.arrayName);if(s.kind==="intArray")return"int";if(s.kind==="doubleArray")return"double";if(s.kind==="stringArray")return"string";if(s.kind==="booleanArray")return"boolean";if(s.kind==="grid")return s.elementType;throw N(a.arrayName)}throw Ge(e)}assignValue(e,t){const n=t.trim(),a=o1(n);if(!a){this.state.variables.set(n,e);return}const s=a.indexExpressions.map(u=>this.arrayIndex(u)),r=this.state.variables.get(a.arrayName);if(!r)throw Q1(a.arrayName);if(r.kind==="grid"){if(s.length!==2||s[0]>=r.value.length||s[1]>=r.value[s[0]].length)throw N(n);const u=r.elementType==="double"&&e.kind==="int"||e.kind===r.elementType?e.value:void 0;if(u===void 0||io(e))throw N(n);const m=r.value.map(c=>[...c]);m[s[0]][s[1]]=u,this.state.variables.set(a.arrayName,{...r,value:m});return}if(s.length!==1)throw N(n);const o=s[0];let l;if(r.kind==="intArray"&&e.kind==="int")l={kind:"intArray",value:[...r.value]};else if(r.kind==="doubleArray"&&(e.kind==="double"||e.kind==="int"))l={kind:"doubleArray",value:[...r.value]};else if(r.kind==="stringArray"&&e.kind==="string")l={kind:"stringArray",value:[...r.value]};else if(r.kind==="booleanArray"&&e.kind==="boolean")l={kind:"booleanArray",value:[...r.value]};else throw N(n);if(o>=l.value.length)throw N(n);l.value[o]=e.value,this.state.variables.set(a.arrayName,l)}evaluateOutputExpression(e){let t,n;for(const a of K0(this.withSensors(e))){const s=a.trim(),r=st(s),o=r!==void 0?{kind:"string",value:r}:this.evaluateReference(s)??this.evaluateNumeric(s),l=o.kind==="int"||o.kind==="double";if(n===void 0&&l){t?t=t.kind==="int"&&o.kind==="int"?xt(t.value+o.value):bt(t.value+o.value):t=o;continue}n=(n??(t?ke(t):""))+ke(o),t=void 0}return n??(t?ke(t):"")}renderOutputExpression(e){return K0(e).map(t=>{const n=t.trim();if(st(n)!==void 0)return n;const a=this.evaluateReference(n);if(a)return ke(a);try{return this.renderNumericExpression(n)}catch{return n}}).join(" + ")}evaluateExpression(e,t){switch(t){case"int":return xt(this.evaluateInt(e));case"double":return bt(this.evaluateDouble(e));case"string":{const n=e.trim(),a=st(n);if(a!==void 0)return{kind:"string",value:a};if(n==="null")return{kind:"null"};const s=this.evaluateReference(n);return(s==null?void 0:s.kind)==="null"?s:s?{kind:"string",value:ke(s)}:{kind:"string",value:this.evaluateOutputExpression(e)}}case"boolean":return{kind:"boolean",value:this.evaluateBool(e)}}}evaluateNumeric(e){const{v:t,int:n}=this.parser(e).parseNumber();return n||Number.isFinite(t)&&Math.round(t)===t?xt(t):bt(t)}parser(e){const t=this.withSensors(e);return new K2(eu(Y0(this.substituteStringCalls(t))),this.state.variables)}withSensors(e){return E2(e,t=>this.robotSensors[t]??wt[t].simulated)}evaluateInt(e){return this.parser(e).parseInt()}evaluateDouble(e){return this.parser(e).parseDouble()}evaluateBool(e){const t=this.withSensors(e).trim();if(t==="true")return!0;if(t==="false")return!1;const n=this.evaluateReference(t);if((n==null?void 0:n.kind)==="boolean")return n.value;const a=Ka(t,"||");if(a.length>1)return a.some(u=>this.evaluateBool(u));const s=Ka(t,"&&");if(s.length>1)return s.every(u=>this.evaluateBool(u));if(t.startsWith("!")&&!t.startsWith("!="))return!this.evaluateBool(t.slice(1));const r=Jd(t);if(r!==void 0)return this.evaluateBool(r);const o=$2(t);if(o)return this.evaluateComparison(o.lhs,"==",o.rhs);const l=U2(t);if(l)return this.evaluateComparison(l.lhs,l.op,l.rhs);if(this.stringOperand(t)!==void 0)throw N(t);return this.evaluateDouble(t)!==0}evaluateComparison(e,t,n){if((e.trim()==="null"||n.trim()==="null")&&(t==="=="||t==="!=")){const m=d=>{var h;return d.trim()==="null"||((h=this.evaluateReference(d))==null?void 0:h.kind)==="null"},c=m(e)===m(n);return t==="=="?c:!c}const a=this.booleanOperand(e),s=this.booleanOperand(n);if((a!==void 0||s!==void 0)&&(t==="=="||t==="!=")){const m=a??this.evaluateBool(e),c=s??this.evaluateBool(n);return t==="=="?m===c:m!==c}const r=this.stringOperand(e),o=this.stringOperand(n);let l,u;if(r!==void 0||o!==void 0){if(r===void 0||o===void 0)throw N(`${e} ${t} ${n}`);l=r,u=o}else l=this.evaluateDouble(e),u=this.evaluateDouble(n);switch(t){case"==":return l===u;case"!=":return l!==u;case"<":return l":return l>u;case">=":return l>=u;default:throw N(`${e} ${t} ${n}`)}}booleanOperand(e){const t=e.trim();if(t==="true")return!0;if(t==="false")return!1;const n=this.evaluateReference(t);return(n==null?void 0:n.kind)==="boolean"?n.value:void 0}stringOperand(e){const t=e.trim(),n=st(t);if(n!==void 0)return n;const a=this.evaluateReference(t);return(a==null?void 0:a.kind)==="string"?a.value:void 0}evaluateSwitchSelector(e){const t=this.withSensors(e).trim(),n=st(t);if(n!==void 0)return{kind:"text",value:n};const a=this.state.variables.get(t);if(a)switch(a.kind){case"int":return{kind:"int",value:a.value};case"double":return{kind:"int",value:Math.trunc(a.value)};case"string":return{kind:"text",value:a.value};default:throw N(t)}return/^[+-]?[0-9]+$/.test(t)?{kind:"int",value:Number(t)}:{kind:"int",value:this.evaluateInt(t)}}renderNumericExpression(e){return eu(Y0(e)).map(t=>{if(t.t==="number")return t.literal;if(t.t==="identifier"){const n=this.state.variables.get(t.name);if(!n)throw Q1(t.name);return ke(n)}return t.t}).join(" ").replaceAll("( ","(").replaceAll(" )",")").replaceAll(" . ",".").replaceAll("[ ","[").replaceAll(" ]","]")}}const Gd={baseIndent:0,indentPerLevel:4,includeDiagramTextAsComments:!1,includeEmptyElseBranch:!0,pseudocodeNote:"Pseudocode – not a runnable program"};function ts(i,e,t={},n=[]){const a=Pl(i,e,t);let s="";e==="javascript"&&(s+=`"use strict"; +`)}function Y0(i){return i.replaceAll("(int)","").replaceAll("(double)","").trim()}function Al(i){const e=new Array(i.length).fill(!1);let t=0,n=!1,a=!1;return i.forEach((s,r)=>{if(n){a?a=!1:s==="\\"?a=!0:s==='"'&&(n=!1);return}switch(s){case'"':n=!0;break;case"(":case"[":t+=1;break;case")":case"]":t-=1;break;default:e[r]=t===0}}),e}function Ka(i,e){const t=Array.from(i),n=Array.from(e),a=Al(t),s=[];let r=[],o=0;for(;ot[o+m]===u)&&a.slice(o,l).every(Boolean)){s.push(r.join("").trim()),r=[],o=l;continue}r.push(t[o]),o+=1}return s.push(r.join("").trim()),s}function U2(i){const e=Array.from(i),t=Al(e);for(let n=0;n=","<=","==","!="].includes(o)&&(a=o)}if(a===void 0&&(e[n]==="<"||e[n]===">")&&(a=e[n]),a===void 0)continue;const s=e.slice(0,n).join("").trim(),r=e.slice(n+a.length).join("").trim();return{lhs:s,op:a,rhs:r}}}function Ds(i,e){let t=0,n=!1,a=!1;for(let s=e;se.length||!t.every((r,o)=>e[a+o]===r))continue;const s=a+t.length-1;if(Ds(e,s)===e.length-1)return{lhs:e.slice(0,a).join("").trim(),rhs:e.slice(s+1,-1).join("").trim()}}}function qi(i){const e=i.trim();for(const t of["if","while","until","switch"]){if(!e.startsWith(t))continue;const n=e.slice(t.length);if(!(n===""||Ol(n[0])||n[0]==="("))continue;let a=n.trim();const s=Jd(a);return s!==void 0&&(a=s),a===""?"true":a}return e===""?"true":e}function o1(i){const e=i.trim(),t=e.indexOf("[");if(!e.endsWith("]")||t<0)return;const n=e.slice(0,t).trim();if(!ti(n))return;const a=[];let s=t;for(;s2))return{arrayName:n,indexExpressions:a}}function Y2(i){const e=i.trim();if(!e.endsWith(")"))return;const t=/^([A-Za-z_]\w*(?:\s*\[[^\[\]]*\])*|"(?:[^"\\]|\\.)*")\s*\.\s*([A-Za-z_]\w*)\s*\(/u.exec(e);if(!t)return;const n=Array.from(e),a=Array.from(t[0]).length-1;if(Ds(n,a)!==n.length-1)return;const s=n.slice(a+1,-1).join("").trim();return{target:t[1],method:t[2],args:s===""?[]:Ka(s,",")}}function X0(i){return ti(i)||o1(i)!==void 0}function K0(i){const e=[];let t="",n=!1,a=!1,s=0;for(const r of i){if(a){t+=r,a=!1;continue}if(r==="\\"){t+=r,a=!0;continue}if(r==='"'){n=!n,t+=r;continue}if(!n&&r==="("&&(s+=1),!n&&r===")"&&(s-=1),r==="+"&&!n&&s===0){e.push(t),t="";continue}t+=r}if(n)throw N(i);return e.push(t),e}function X2(i){const e=[];let t=0,n="";for(const a of i){if(a==="{"&&(t+=1),a==="}"&&(t-=1),a===","&&t===0){e.push(n),n="";continue}n+=a}return n.trim()!==""&&e.push(n),e}function eu(i){const e=Array.from(i),t=[];let n=0;for(;n1)throw N(i)}else if(!q1(e[n]))break;n+=1}const o=e.slice(s,n).join("");if(o==="."||!/^[0-9]*\.?[0-9]*$/.test(o))throw N(i);t.push({t:"number",literal:o,value:Number(o)});continue}if(Xa(a)||a==="_"){const s=n;for(;n=0&&s=0&&o=0&&sk1(t).trim());return e.length===1&&e[0].includes(";")?tu(e[0].split(";").map(t=>t.trim())):tu(e)}const nt=i=>i.frame?{frame:i.frame,callPath:i.callPath}:{};function Ht(i,e=[],t={}){const n=[],a=s=>n.push(t.frame?{...s,...t}:s);return i.forEach((s,r)=>{const o=[...e,r],l=s.textLines.join(" ").trim();switch(s.type){case z.anweisung:l!==""&&l!=="ø"&&a({path:o,text:l,kind:"statement"});break;case z.verzweigung:a({path:o,text:l||"true",kind:"branch",cases:s.cases});break;case z.fallauswahl:a({path:o,text:l||"0",kind:"switchSelection",cases:s.cases});break;case z.forSchleife:a({path:o,text:l,kind:"forLoopStart",loopBody:s.loopBody,forParts:so(s.textLines)});break;case z.whileSchleife:a({path:o,text:l||"true",kind:"whileLoop",loopBody:s.loopBody});break;case z.doUntilSchleife:a({path:o,text:l||"true",kind:"doUntilLoop",loopBody:s.loopBody});break;case z.endlosschleife:a({path:o,text:l||"true",kind:"infiniteLoop",loopBody:s.loopBody});break;case z.aussprung:a({path:o,text:l,kind:"jump"});break;case z.aufruf:l!==""&&l!=="ø"&&a({path:o,text:l,kind:"call"});break}}),n}function e3(i,e){const t=i.trim().replaceAll(",",".");switch(e){case"int":if(!/^[+-]?[0-9]+$/.test(t))throw new Be({kind:"wholeNumberExpected"});return xt(Number(t));case"double":if(!/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][+-]?[0-9]+)?$/.test(t))throw new Be({kind:"numberExpected"});return bt(Number(t));case"string":return{kind:"string",value:i};case"boolean":switch(t.toLowerCase()){case"true":case"wahr":return{kind:"boolean",value:!0};case"false":case"falsch":return{kind:"boolean",value:!1};default:throw new Be({kind:"booleanExpected"})}}}function nu(){return{stepIndex:0,variables:new Map,outputLines:[],isHalted:!1,files:new Map,robotActions:[]}}function t3(i,e){for(let t=0;tt===e.path[n])}function pt(i){const e=/^(void|int|double|String|boolean)\s+([A-Za-z_]\w*)\s*\((.*)\)$/u.exec(k1(i));if(!e)return;const t=[];if(e[3].trim()!=="")for(const n of e[3].split(",")){const a=/^(int|double|String|boolean|char)\s*((?:\[\s*\]){0,2})\s+([A-Za-z_]\w*)$/u.exec(n.trim());if(!a)return;const s=(a[2].match(/\[/gu)??[]).length;t.push({type:sn(a[1]),name:a[3],...s>0?{dims:s}:{}})}return{returnType:sn(e[1]),name:e[2],params:t}}function Rd(i){const e=/^(?:(?:(int|double|String|boolean)\s+)?([A-Za-z_]\w*)\s*=\s*)?([A-Za-z_]\w*)\s*\((.*)\)$/u.exec(k1(i));if(e)return{targetType:e[1]?sn(e[1]):void 0,target:e[2],name:e[3],args:e[4].trim()===""?[]:Ka(e[4],",")}}function es(i){var t,n;const e=k1(i);return((t=pt(e))==null?void 0:t.name)??((n=Rd(e))==null?void 0:n.name)??e.replace(/\(\s*\)$/u,"").trim()}class fi{constructor(e,t=()=>{}){y(this,"steps");y(this,"state",nu());y(this,"nextFrame",1);y(this,"callDepth",0);y(this,"frames",new Map);y(this,"peeking",!1);y(this,"robotSensors",{});y(this,"afterOutput",!1);this.resolveSubprogram=t,this.steps=Ht(e.elements)}get currentStepPath(){const e=this.steps[this.state.stepIndex];return(e==null?void 0:e.callPath)??(e==null?void 0:e.path)}get canStep(){return!this.state.isHalted&&!this.state.inputRequest&&this.state.stepIndex ${ke(n)}`}catch(n){this.state.inputErrorNotice=q0(n);return}this.state.inputRequest=void 0,this.state.inputErrorNotice=void 0,this.state.stepIndex+=1,this.state.notice=this.finishedIfAtEnd()}}finishedIfAtEnd(){return this.state.stepIndex>=this.steps.length?{kind:"finished"}:void 0}splice(e){this.steps.splice(this.state.stepIndex,1,...e)}noticeAfterEntering(e){return e.length>0?void 0:this.finishedIfAtEnd()}executeBranch(e){const t=e.cases;if(!t||t.length<2)throw Ge(e.text);const n=qi(e.text),a=this.evaluateBool(n),s=a?0:1,r=Ht(t[s].elements,[...e.path,s],nt(e));this.splice(r),this.state.lastTrace=`${n} -> ${a}`,this.state.notice=this.noticeAfterEntering(r)}executeSwitchSelection(e){const t=e.cases;if(!t||t.length===0)throw Ge(e.text);const n=qi(e.text),a=this.evaluateSwitchSelector(n),s=t3(a,t)??t.length-1,r=Ht(t[s].elements,[...e.path,s],nt(e));this.splice(r),this.state.lastTrace=`${n} -> ${t[s].name}`,this.state.notice=this.noticeAfterEntering(r)}executeForLoopStart(e){const t=so(e.forParts??[e.text]);t[0]!==""&&this.executeStatement(t[0]),this.splice([{...nt(e),path:e.path,text:t[1],kind:"forLoopCondition",loopBody:e.loopBody,forParts:t}])}executeForLoopCondition(e){const t=so(e.forParts??[e.text]),n=t[1]===""?"true":t[1],a=this.evaluateBool(n);if(this.state.lastTrace=`${n} -> ${a}`,a){const s=Ht(e.loopBody??[],[...e.path,0],nt(e));this.splice([...s,{...nt(e),path:e.path,text:t[2],kind:"forLoopIncrement",loopBody:e.loopBody,forParts:t},{...nt(e),path:e.path,text:t[1],kind:"forLoopCondition",loopBody:e.loopBody,forParts:t}])}else this.splice([]),this.state.notice=this.finishedIfAtEnd()}executeForLoopIncrement(e){const t=e.text.trim();t!==""&&this.executeIncrement(t),this.splice([])}executeWhileLoop(e){const t=qi(e.text),n=this.evaluateBool(t);if(this.state.lastTrace=`${t} -> ${n}`,n){const a=Ht(e.loopBody??[],[...e.path,0],nt(e));this.splice([...a,{...nt(e),path:e.path,text:e.text,kind:"whileLoop",loopBody:e.loopBody}]),this.state.notice=this.noticeAfterEntering(a)}else this.splice([]),this.state.notice=this.finishedIfAtEnd()}enterDoUntilLoop(e){const t=Ht(e.loopBody??[],[...e.path,0],nt(e));this.splice([...t,{...nt(e),path:e.path,text:e.text,kind:"doUntilCondition",loopBody:e.loopBody}]),this.state.notice=this.noticeAfterEntering(t)}executeDoUntilCondition(e){const t=qi(e.text),n=this.evaluateBool(t);if(this.state.lastTrace=`${t} -> ${n}`,n){const a=Ht(e.loopBody??[],[...e.path,0],nt(e));this.splice([...a,{...nt(e),path:e.path,text:e.text,kind:"doUntilCondition",loopBody:e.loopBody}])}else this.splice([]),this.state.notice=this.finishedIfAtEnd()}enterInfiniteLoop(e){const t=Ht(e.loopBody??[],[...e.path,0],nt(e));this.splice([...t,{...nt(e),path:e.path,text:e.text,kind:"infiniteLoop",loopBody:e.loopBody}]),this.state.lastTrace="true -> true",this.state.notice=t.length>0?void 0:{kind:"infiniteLoopWithoutBody"}}executeJump(e){const t=e.frame??0,n=o=>o.lengthl===e.path[u]);let a=this.steps.length,s="end";for(let o=this.state.stepIndex+1;o ${s}`,s==="return"&&this.finishFrame(r),this.state.notice=this.finishedIfAtEnd()}executeCall(e){const t=e.text,n=this.resolveSubprogram(es(t));if(!n){this.splice([]),this.state.lastTrace=`${t} -> ?`,this.state.notice={kind:"subprogramNotFound",text:t},this.state.stepIndex>=this.steps.length&&(this.state.notice={kind:"finished"});return}const a=Rd(t),s=pt(n.caption);if(s?((a==null?void 0:a.args.length)??0)!==s.params.length||(a==null?void 0:a.target)!==void 0&&!s.returnType:a!==void 0&&(a.args.length>0||a.target!==void 0))throw new Be({kind:"callArguments",text:(s==null?void 0:s.name)??es(t)});if(this.callDepth>=J2)throw new Be({kind:"callTooDeep"});const o=new Map,l=[];s==null||s.params.forEach((d,h)=>{const g=a.args[h].trim();if(!d.dims){o.set(d.name,this.evaluateExpression(g,d.type));return}const f=this.state.variables.get(g);if(!f)throw/^[A-Za-z_]\w*$/u.test(g)?new Be({kind:"unknownVariable",text:g}):N(g);if(!(d.dims===1?f.kind===`${d.type}Array`:f.kind==="grid"&&f.elementType===d.type))throw N(g);o.set(d.name,f),l.push({param:d.name,callerName:g})}),this.callDepth+=1;const u={frame:this.nextFrame++,callPath:e.callPath??e.path};s&&(this.frames.set(u.frame,{saved:this.state.variables,header:s,call:a,references:l}),this.state.variables=o);const m=Ht(n.elements,[],u);this.splice([...m,{...u,path:e.path,text:t,kind:"callEnd"}]);const c=s==null?void 0:s.params.map((d,h)=>`${d.name} = ${d.dims?a.args[h].trim():ke(o.get(d.name))}`).join(", ");this.state.lastTrace=c?`${t} -> ${c}`:`${t} -> call`}executeCallEnd(e){this.callDepth-=1,this.splice([]),this.state.lastTrace=`${e.text} -> return`,this.finishFrame(e),this.state.notice=this.finishedIfAtEnd()}executeReturn(e){const t=e.frame??0,n=k1(e.text).slice(6).trim(),a=this.frames.get(t);if(a&&n!==""){if(!a.header.returnType)throw N(e.text);a.returnValue=this.evaluateExpression(n,a.header.returnType)}const s=a!=null&&a.returnValue?`${e.text} -> ${ke(a.returnValue)}`:`${e.text} -> return`;if(t===0){this.steps.splice(this.state.stepIndex),this.state.lastTrace=s,this.state.notice={kind:"finished"};return}let r=this.state.stepIndex+1;for(;r0?new Map(t.saved):t.saved;for(const m of t.references){const c=this.state.variables.get(m.param);c&&n.set(m.callerName,c)}this.state.variables=n;const a=t.returnValue;if(t.header.returnType&&!a)throw new Be({kind:"missingReturn",text:t.header.name});const s=(l=t.call)==null?void 0:l.target;if(!s||!a)return;let r=(u=t.call)==null?void 0:u.targetType;if(!r)try{r=this.inferTargetValueType(s)}catch{r=t.header.returnType}const o=r==="double"&&a.kind==="int"?bt(a.value):r==="string"?{kind:"string",value:ke(a)}:a;if($0(o)!==r)throw N(e.text);this.assignValue(o,s),this.state.lastTrace=`${s} = ${e.text.slice(e.text.indexOf("=")+1).trim()} -> ${ke(o)}`}executeStatement(e){const t=this.state,n=e.trim(),a=n.toLowerCase(),s=this.afterOutput;if(this.afterOutput=!1,a.startsWith("input:")){t.inputRequest=this.parseInputRequest(n,s),t.outputLineOpen=!1,t.inputErrorNotice=void 0;return}const r=/^System\s*\.\s*out\s*\.\s*(println|print)\s*\(([\s\S]*)\)\s*;?$/u.exec(n);if(a.startsWith("output:")||a.startsWith("print:")||r){const x=r?r[2]:n.slice(a.startsWith("output:")?7:6),b=this.peek(()=>this.renderOutputExpression(x)),v=x.trim()===""?"":this.evaluateOutputExpression(x);t.outputLineOpen&&t.outputLines.length?t.outputLines[t.outputLines.length-1]+=v:t.outputLines.push(v),t.outputLineOpen=(r==null?void 0:r[1])==="print",this.afterOutput=!0,t.lastTrace=`${b} -> ${v}`;return}const o=L2(n);if(o){this.executeMBotCommand(o.method,o.args,n);return}if(this.executeFileStatement(n))return;if(n.endsWith("++")||n.endsWith("--")||n.includes("+=")||n.includes("-=")){this.executeIncrement(n);return}const l=n.indexOf("=");if(l<0)throw Ge(n);const u=n.slice(0,l).trim(),m=n.slice(l+1),c=this.parseArrayDeclaration(u,m);if(c){t.variables.set(c.name,c.value),t.lastTrace=`${c.name} = new ${c.typeName}[${c.count}]`;return}const d=this.parseAssignmentTarget(u);let h;try{h=this.peek(()=>this.renderNumericExpression(m))}catch{h=m.trim()}let g=d.valueType;if(!g)try{g=this.inferTargetValueType(d.variableName)}catch{g="int"}const f=this.evaluateExpression(m,g);this.assignValue(f,d.variableName),t.lastTrace=`${d.variableName} = ${h} -> ${ke(f)}`}executeMBotCommand(e,t,n){var r;if((r=pi[e])!=null&&r.text){const o=pi[e];if(t.length!==o.args+1)throw N(n);const l=Ua(e,t.slice(0,-1).map(c=>this.evaluateDouble(c)));if(!l)throw N(n);const u=Q0(e,l,this.evaluateOutputExpression(t[t.length-1])),m=o.choices;if(m&&!m.includes(u.text??""))throw N(`${n} (${m.join(", ")})`);this.state.robotActions.push(u),this.state.lastTrace=`${n} -> ${u.label}`;return}const a=Ua(e,t.map(o=>this.evaluateDouble(o)));if(!a)throw N(n);const s=Q0(e,a);this.state.robotActions.push(s),this.state.lastTrace=`${n} -> ${s.label}`}executeFileStatement(e){const t=this.state,n=k1(e).trim(),a=/^(?:(Scanner|BufferedReader|PrintWriter)\s+)?([A-Za-z_]\w*)\s*=\s*new\s+(Scanner|BufferedReader|PrintWriter)\s*\(([\s\S]*)\)$/u.exec(n);if(a){const[,m,c,d,h]=a;if(m&&m!==d)throw N(n);const g=d==="Scanner"?/^new\s+File\s*\(([\s\S]+)\)$/u.exec(h.trim()):d==="BufferedReader"?/^new\s+FileReader\s*\(([\s\S]+)\)$/u.exec(h.trim()):/^(?:new\s+(?:File|FileWriter)\s*\(([\s\S]+)\)|([\s\S]+))$/u.exec(h.trim());if(!g)throw Ge(n);const f=this.fileNameValue(g[1]??g[2]);if(d==="PrintWriter")t.variables.set(c,{kind:"writer",file:f,text:""});else{const b=this.fileContent(f).split(/\r?\n/u);b[b.length-1]===""&&b.pop(),t.variables.set(c,{kind:"reader",className:d,file:f,lines:b,next:0})}return t.lastTrace=`${c} = new ${d}(${f})`,!0}const s=/^Files\s*\.\s*writeString\s*\(\s*(?:Path\s*\.\s*of|Paths\s*\.\s*get)\s*\(([^()]+)\)\s*,([\s\S]+)\)$/u.exec(n);if(s){const m=this.fileNameValue(s[1]),c=this.evaluateOutputExpression(s[2]);return t.files.set(m,c),t.lastTrace=`${m} ← ${JSON.stringify(c)}`,!0}const r=/^([A-Za-z_]\w*)\s*\.\s*(println|print|close)\s*\(([\s\S]*)\)$/u.exec(n),o=r&&t.variables.get(r[1]);if(!r||!o)return!1;if(o.kind==="null")throw new Be({kind:"nullValue",text:r[1]});if(o.kind==="reader"&&r[2]==="close")return t.lastTrace=`${r[1]}.close()`,!0;if(o.kind!=="writer")return!1;if(r[2]==="close")return t.files.set(o.file,o.text),t.lastTrace=`${o.file} ← ${JSON.stringify(o.text)}`,!0;const l=r[3].trim()===""?"":this.evaluateOutputExpression(r[3]),u=r[2]==="println"?l+` +`:l;return t.variables.set(r[1],{...o,text:o.text+u}),t.lastTrace=`${r[1]}.${r[2]}(${JSON.stringify(l)})`,!0}fileNameValue(e){const t=e.trim(),n=st(t);if(n!==void 0)return n;const a=this.evaluateReference(t);if((a==null?void 0:a.kind)==="string")return a.value;throw N(t)}fileContent(e){const t=this.state.files.get(e)??Ya.get(e);if(t===void 0)throw new Be({kind:"fileNotFound",text:e});return t}readerMethod(e,t,n,a){if(n.args.length)throw N(a);const s=t.next0?"+":"-";if(r.kind==="int"){t.set(s,xt(r.value+a)),this.state.lastTrace=`${s} = ${r.value} ${o} 1 -> ${r.value+a}`;return}if(r.kind==="double"){const l=r.value+a;t.set(s,bt(l)),this.state.lastTrace=`${s} = ${ke(r)} ${o} 1 -> ${ke(bt(l))}`;return}throw Ge(e)}for(const[n,a]of[["+=",1],["-=",-1]]){const s=e.indexOf(n);if(s<0)continue;const r=e.slice(0,s).trim(),o=e.slice(s+2),l=t.get(r);if(!ti(r)||!l)throw Ge(e);const u=a>0?"+":"-";if(l.kind==="int"){const m=this.evaluateInt(o),c=l.value+a*m;t.set(r,xt(c)),this.state.lastTrace=`${r} = ${l.value} ${u} ${m} -> ${c}`;return}if(l.kind==="double"){const m=this.evaluateDouble(o),c=l.value+a*m;t.set(r,bt(c)),this.state.lastTrace=`${r} = ${ke(l)} ${u} ${ke(bt(m))} -> ${ke(bt(c))}`;return}throw Ge(e)}this.executeStatement(e)}parseAssignmentTarget(e){if(o1(e))return{variableName:e.trim()};const t=e.split(/\s+/u).filter(Boolean);let n,a;if(t.length===1)n=t[0];else if(t.length===2&&sn(t[0]))n=t[1],a=sn(t[0]);else if(t.length===3&&t[0]==="const"&&sn(t[1]))n=t[2],a=sn(t[1]);else throw Ge(e);if(!X0(n))throw Ge(e);return{variableName:n,valueType:a}}parseInputRequest(e,t=!1){const n=e.slice(6).trim(),a=/^(\S+)(?:\s+(\S+))?(?:\s+([\s\S]*))?$/u.exec(n);if(!a)throw Ge(e);const s=[a[1],a[2],a[3]].filter(c=>c!==void 0);let r,o,l;const u=sn(s[0]);if(s.length>=2&&u?(r=s[1],o=u,l=(s[2]??"").trim()):(r=s[0],o=this.inferTargetValueType(r),l=(s[1]??"").trim()),!X0(r))throw Ge(e);const m=st(l)??l;return m===""&&t?this.state.outputLineOpen?{variableName:r,valueType:o,prompt:"",continuesLine:!0}:{variableName:r,valueType:o,prompt:""}:{variableName:r,valueType:o,prompt:m===""?`${r}:`:m}}parseArrayDeclaration(e,t){const n=e.split(/\s+/u).filter(Boolean);if(n.length!==2||!n[0].endsWith("[]"))return;const a=n[0].endsWith("[][]"),s=n[0].slice(0,a?-4:-2),r=sn(s),o=n[1];if(!r||!ti(o))throw Ge(e);if(a)return this.parseGridDeclaration(o,s,r,t);const l=t.trim();if(l.startsWith("{")&&l.endsWith("}")){const h=l.slice(1,-1).split(",").map(f=>f.trim());let g;switch(r){case"int":g={kind:"intArray",value:h.map(f=>this.evaluateInt(f))};break;case"double":g={kind:"doubleArray",value:h.map(f=>this.evaluateDouble(f))};break;case"string":g={kind:"stringArray",value:h.map(f=>st(f)??this.evaluateOutputExpression(f))};break;case"boolean":g={kind:"booleanArray",value:h.map(f=>this.evaluateBool(f))};break}return{name:o,typeName:s,count:h.length,value:g}}const u=`new ${s}[`;if(!l.startsWith(u)){const h=this.evaluateStringMethod(l);if((h==null?void 0:h.kind)==="stringArray"&&r==="string")return{name:o,typeName:s,count:h.value.length,value:h}}if(!l.startsWith(u)||!l.endsWith("]"))throw Ge(t);const m=l.slice(u.length,-1),c=this.evaluateInt(m);if(c<0)throw N(m);const d=r==="int"?{kind:"intArray",value:new Array(c).fill(0)}:r==="double"?{kind:"doubleArray",value:new Array(c).fill(0)}:r==="boolean"?{kind:"booleanArray",value:new Array(c).fill(!1)}:{kind:"stringArray",value:new Array(c).fill("")};return{name:o,typeName:s,count:c,value:d}}parseGridDeclaration(e,t,n,a){var c;const s=a.trim(),r=d=>{switch(n){case"int":return this.evaluateInt(d);case"double":return this.evaluateDouble(d);case"boolean":return this.evaluateBool(d);case"string":return st(d.trim())??this.evaluateOutputExpression(d)}};if(s.startsWith("{")&&s.endsWith("}")){const d=X2(s.slice(1,-1)).map(h=>{const g=h.trim();if(!g.startsWith("{")||!g.endsWith("}"))throw N(g);return g.slice(1,-1).trim()===""?[]:g.slice(1,-1).split(",").map(f=>r(f.trim()))});return{name:e,typeName:t,count:`${d.length}][${((c=d[0])==null?void 0:c.length)??0}`,value:{kind:"grid",elementType:n,value:d}}}const o=new RegExp(String.raw`^new\s+${t}\s*\[(.+)\]\s*\[(.+)\]$`,"u").exec(s);if(!o)throw Ge(a);const l=this.evaluateInt(o[1]),u=this.evaluateInt(o[2]);if(l<0)throw N(o[1]);if(u<0)throw N(o[2]);const m={kind:"grid",elementType:n,value:Array.from({length:l},()=>new Array(u).fill(Q2(n)))};return{name:e,typeName:t,count:`${l}][${u}`,value:m}}arrayIndex(e){const t=this.evaluateInt(e);if(t<0)throw N(e);return t}evaluateReference(e){const t=e.trim(),n=this.state.variables.get(t);if(n)return n;const a=this.evaluateStringMethod(t);if(a)return a;const s=/^\(\s*char\s*\)\s*(.+)$/su.exec(t);if(s){const o=this.evaluateInt(s[1]);if(!(o>=0&&o<=1114111))throw N(t);return{kind:"string",value:String.fromCodePoint(o)}}const r=o1(t);if(r)return this.valueInArray(r.arrayName,r.indexExpressions.map(o=>this.arrayIndex(o)))}evaluateStringMethod(e){const t=Y2(e);if(!t)return;const n=this.evaluateStaticCall(e,t);if(n)return n;const a=this.state.variables.get(t.target.trim());if((a==null?void 0:a.kind)==="reader")return this.readerMethod(t.target.trim(),a,t,e);if((a==null?void 0:a.kind)==="null")throw new Be({kind:"nullValue",text:t.target.trim()});const s=st(t.target)??this.stringValueOf(t.target);if(s===void 0)return;const r=t.args,o=d=>{const h=r[d];if(h===void 0)throw N(e);const g=st(h.trim());if(g!==void 0)return g;const f=this.evaluateReference(h);if((f==null?void 0:f.kind)==="string")return f.value;throw N(h)},l=d=>{if(r[d]===void 0)throw N(e);return this.evaluateInt(r[d])},u=d=>{if(r.length!==d)throw N(e)},m=Array.from(s),c=(d,h)=>{if(d<0||d>h)throw N(e);return d};switch(t.method){case"length":return u(0),xt(m.length);case"charAt":return u(1),{kind:"string",value:m[c(l(0),m.length-1)]};case"substring":{if(r.length!==1&&r.length!==2)throw N(e);const d=c(l(0),m.length),h=r.length===2?c(l(1),m.length):m.length;if(h0&&h[h.length-1]==="";)h.pop();return{kind:"stringArray",value:h}}default:return}}evaluateStaticCall(e,t){const n=()=>{if(t.args.length!==1)throw N(e);return t.args[0]},a=s=>{const r=st(s.trim());if(r!==void 0)return r;const o=this.evaluateReference(s);if((o==null?void 0:o.kind)==="string")return o.value;throw N(s)};switch(`${t.target}.${t.method}`){case"Integer.parseInt":{const s=a(n()).trim();if(!/^[+-]?\d+$/u.test(s))throw new Be({kind:"wholeNumberExpected"});return xt(Number(s))}case"Double.parseDouble":{const s=Number(a(n()).trim());if(!Number.isFinite(s))throw new Be({kind:"numberExpected"});return bt(s)}case"String.valueOf":return{kind:"string",value:this.evaluateOutputExpression(n())};case"Files.readString":{const s=/^(?:Path\s*\.\s*of|Paths\s*\.\s*get)\s*\(\s*("(?:[^"\\]|\\.)*")\s*\)$/u.exec(n().trim());if(!s)throw N(e);const r=st(s[1]),o=Ya.get(r);if(o===void 0)throw new Be({kind:"fileNotFound",text:r});return{kind:"string",value:o}}default:return}}stringValueOf(e){const t=e.trim(),n=this.state.variables.get(t);if(n)return n.kind==="string"?n.value:void 0;const a=o1(t);if(!a)return;const s=this.valueInArray(a.arrayName,a.indexExpressions.map(r=>this.arrayIndex(r)));return s.kind==="string"?s.value:void 0}substituteStringCalls(e){if(!e.includes("("))return e;let t="",n=e;const a=/([A-Za-z_]\w*(?:\[[^\[\]]*\])*|"(?:[^"\\]|\\.)*")\s*\.\s*(length|indexOf|lastIndexOf|compareTo|charAt|parseInt|parseDouble)\s*\(/u;for(let s=a.exec(n);s;s=a.exec(n)){const r=s.index+s[0].length-1,o=Ds(Array.from(n),Array.from(n.slice(0,r)).length);if(o===void 0)break;const l=Array.from(n),u=l.slice(Array.from(n.slice(0,s.index)).length,o+1).join(""),m=this.evaluateStringMethod(u),c=l.slice(0,Array.from(n.slice(0,s.index)).length).join(""),d=(m==null?void 0:m.kind)==="string"?ao(m.value):void 0;(m==null?void 0:m.kind)==="int"?t+=c+String(m.value):(m==null?void 0:m.kind)==="double"?t+=c+(Number.isInteger(m.value)?m.value.toFixed(1):String(m.value)):d!==void 0?t+=c+String(d):t+=c+u,n=l.slice(o+1).join("")}return t+n}valueInArray(e,t){const n=this.state.variables.get(e);if(!n)throw Q1(e);const a=`${e}[${t.join("][")}]`;if(n.kind==="grid"){if(t.length!==2)throw N(a);const r=n.value[t[0]];if(!r||t[1]>=r.length)throw N(a);return Fd(n.elementType,r[t[1]])}if(t.length!==1)throw N(a);const s=t[0];if(!io(n))throw N(e);if(s>=n.value.length)throw N(a);switch(n.kind){case"intArray":return xt(n.value[s]);case"doubleArray":return bt(n.value[s]);case"stringArray":return{kind:"string",value:n.value[s]};case"booleanArray":return{kind:"boolean",value:n.value[s]};default:throw N(e)}}inferTargetValueType(e){const t=e.trim(),n=this.state.variables.get(t);if(n)return $0(n);const a=o1(t);if(a){const s=this.state.variables.get(a.arrayName);if(!s)throw Q1(a.arrayName);if(s.kind==="intArray")return"int";if(s.kind==="doubleArray")return"double";if(s.kind==="stringArray")return"string";if(s.kind==="booleanArray")return"boolean";if(s.kind==="grid")return s.elementType;throw N(a.arrayName)}throw Ge(e)}assignValue(e,t){const n=t.trim(),a=o1(n);if(!a){this.state.variables.set(n,e);return}const s=a.indexExpressions.map(u=>this.arrayIndex(u)),r=this.state.variables.get(a.arrayName);if(!r)throw Q1(a.arrayName);if(r.kind==="grid"){if(s.length!==2||s[0]>=r.value.length||s[1]>=r.value[s[0]].length)throw N(n);const u=r.elementType==="double"&&e.kind==="int"||e.kind===r.elementType?e.value:void 0;if(u===void 0||io(e))throw N(n);const m=r.value.map(c=>[...c]);m[s[0]][s[1]]=u,this.state.variables.set(a.arrayName,{...r,value:m});return}if(s.length!==1)throw N(n);const o=s[0];let l;if(r.kind==="intArray"&&e.kind==="int")l={kind:"intArray",value:[...r.value]};else if(r.kind==="doubleArray"&&(e.kind==="double"||e.kind==="int"))l={kind:"doubleArray",value:[...r.value]};else if(r.kind==="stringArray"&&e.kind==="string")l={kind:"stringArray",value:[...r.value]};else if(r.kind==="booleanArray"&&e.kind==="boolean")l={kind:"booleanArray",value:[...r.value]};else throw N(n);if(o>=l.value.length)throw N(n);l.value[o]=e.value,this.state.variables.set(a.arrayName,l)}evaluateOutputExpression(e){let t,n;for(const a of K0(this.withSensors(e))){const s=a.trim(),r=st(s),o=r!==void 0?{kind:"string",value:r}:this.evaluateReference(s)??this.evaluateNumeric(s),l=o.kind==="int"||o.kind==="double";if(n===void 0&&l){t?t=t.kind==="int"&&o.kind==="int"?xt(t.value+o.value):bt(t.value+o.value):t=o;continue}n=(n??(t?ke(t):""))+ke(o),t=void 0}return n??(t?ke(t):"")}renderOutputExpression(e){return K0(e).map(t=>{const n=t.trim();if(st(n)!==void 0)return n;const a=this.evaluateReference(n);if(a)return ke(a);try{return this.renderNumericExpression(n)}catch{return n}}).join(" + ")}evaluateExpression(e,t){switch(t){case"int":return xt(this.evaluateInt(e));case"double":return bt(this.evaluateDouble(e));case"string":{const n=e.trim(),a=st(n);if(a!==void 0)return{kind:"string",value:a};if(n==="null")return{kind:"null"};const s=this.evaluateReference(n);return(s==null?void 0:s.kind)==="null"?s:s?{kind:"string",value:ke(s)}:{kind:"string",value:this.evaluateOutputExpression(e)}}case"boolean":return{kind:"boolean",value:this.evaluateBool(e)}}}evaluateNumeric(e){const{v:t,int:n}=this.parser(e).parseNumber();return n||Number.isFinite(t)&&Math.round(t)===t?xt(t):bt(t)}parser(e){const t=this.withSensors(e);return new K2(eu(Y0(this.substituteStringCalls(t))),this.state.variables)}withSensors(e){return E2(e,t=>this.robotSensors[t]??wt[t].simulated)}evaluateInt(e){return this.parser(e).parseInt()}evaluateDouble(e){return this.parser(e).parseDouble()}evaluateBool(e){const t=this.withSensors(e).trim();if(t==="true")return!0;if(t==="false")return!1;const n=this.evaluateReference(t);if((n==null?void 0:n.kind)==="boolean")return n.value;const a=Ka(t,"||");if(a.length>1)return a.some(u=>this.evaluateBool(u));const s=Ka(t,"&&");if(s.length>1)return s.every(u=>this.evaluateBool(u));if(t.startsWith("!")&&!t.startsWith("!="))return!this.evaluateBool(t.slice(1));const r=Jd(t);if(r!==void 0)return this.evaluateBool(r);const o=$2(t);if(o)return this.evaluateComparison(o.lhs,"==",o.rhs);const l=U2(t);if(l)return this.evaluateComparison(l.lhs,l.op,l.rhs);if(this.stringOperand(t)!==void 0)throw N(t);return this.evaluateDouble(t)!==0}evaluateComparison(e,t,n){if((e.trim()==="null"||n.trim()==="null")&&(t==="=="||t==="!=")){const m=d=>{var h;return d.trim()==="null"||((h=this.evaluateReference(d))==null?void 0:h.kind)==="null"},c=m(e)===m(n);return t==="=="?c:!c}const a=this.booleanOperand(e),s=this.booleanOperand(n);if((a!==void 0||s!==void 0)&&(t==="=="||t==="!=")){const m=a??this.evaluateBool(e),c=s??this.evaluateBool(n);return t==="=="?m===c:m!==c}const r=this.stringOperand(e),o=this.stringOperand(n);let l,u;if(r!==void 0||o!==void 0){if(r===void 0||o===void 0)throw N(`${e} ${t} ${n}`);l=r,u=o}else l=this.evaluateDouble(e),u=this.evaluateDouble(n);switch(t){case"==":return l===u;case"!=":return l!==u;case"<":return l":return l>u;case">=":return l>=u;default:throw N(`${e} ${t} ${n}`)}}booleanOperand(e){const t=e.trim();if(t==="true")return!0;if(t==="false")return!1;const n=this.evaluateReference(t);return(n==null?void 0:n.kind)==="boolean"?n.value:void 0}stringOperand(e){const t=e.trim(),n=st(t);if(n!==void 0)return n;const a=this.evaluateReference(t);return(a==null?void 0:a.kind)==="string"?a.value:void 0}evaluateSwitchSelector(e){const t=this.withSensors(e).trim(),n=st(t);if(n!==void 0)return{kind:"text",value:n};const a=this.state.variables.get(t);if(a)switch(a.kind){case"int":return{kind:"int",value:a.value};case"double":return{kind:"int",value:Math.trunc(a.value)};case"string":return{kind:"text",value:a.value};default:throw N(t)}return/^[+-]?[0-9]+$/.test(t)?{kind:"int",value:Number(t)}:{kind:"int",value:this.evaluateInt(t)}}renderNumericExpression(e){return eu(Y0(e)).map(t=>{if(t.t==="number")return t.literal;if(t.t==="identifier"){const n=this.state.variables.get(t.name);if(!n)throw Q1(t.name);return ke(n)}return t.t}).join(" ").replaceAll("( ","(").replaceAll(" )",")").replaceAll(" . ",".").replaceAll("[ ","[").replaceAll(" ]","]")}}const Gd={baseIndent:0,indentPerLevel:4,includeDiagramTextAsComments:!1,includeEmptyElseBranch:!0,pseudocodeNote:"Pseudocode – not a runnable program"};function ts(i,e,t={},n=[]){const a=Pl(i,e,t);let s="";e==="javascript"&&(s+=`"use strict"; `);const r=[i,...e==="java"?[]:n];if(e==="python"&&r.some(sh)&&(s+=`import random @@ -29,46 +29,46 @@ except: `),e!=="java")for(const u of n){if(u===i)continue;const m=pt(u.caption);m&&(s+=ro(u,m,e,t,0)+` `)}const o=pt(i.caption),l={out:""};if(o)l.out=ro(i,o,e,t,a.baseIndent);else for(const u of i.elements)Ws(u,e,a,a.baseIndent,l);if(s+=l.out,s.trim()===""){const u=a3(e);return e==="javascript"?`"use strict"; -`+u:u}return uh(s.replace(/^[\n\r]+|[\n\r]+$/g,""),e)}function Pl(i,e,t){const n={...Gd,...t,jsIntVariables:new Set,arrayElementTypes:h3(i),stringVariables:d3(i)};return e!=="java"&&(n.jsIntVariables=D3(i)),n}const iu=i=>i==="string"?"String":i===void 0?"void":i;function Hd(i){const e=i.params.map(t=>`${iu(t.type)}${"[]".repeat(t.dims??0)} ${t.name}`).join(", ");return`public static ${iu(i.returnType)} ${i.name}(${e}) {`}function ro(i,e,t,n,a){const s=Pl(i,t,n);for(const l of e.params)l.dims||(l.type==="int"&&s.jsIntVariables.add(l.name),l.type==="string"&&s.stringVariables.add(l.name));const r=e.params.map(l=>l.name).join(", "),o={out:""};for(const l of i.elements)Ws(l,t,s,a+s.indentPerLevel,o);switch(o.out.trim()===""&&(o.out=Z(a+s.indentPerLevel)+(t==="python"?`pass +`+u:u}return uh(s.replace(/^[\n\r]+|[\n\r]+$/g,""),e)}function Pl(i,e,t){const n={...Gd,...t,jsIntVariables:new Set,arrayElementTypes:h3(i),stringVariables:d3(i)};return e!=="java"&&(n.jsIntVariables=D3(i)),n}const iu=i=>i==="string"?"String":i===void 0?"void":i;function Hd(i){const e=i.params.map(t=>`${iu(t.type)}${"[]".repeat(t.dims??0)} ${t.name}`).join(", ");return`public static ${iu(i.returnType)} ${i.name}(${e}) {`}function ro(i,e,t,n,a){const s=Pl(i,t,n);for(const l of e.params)l.dims||(l.type==="int"&&s.jsIntVariables.add(l.name),l.type==="string"&&s.stringVariables.add(l.name));const r=e.params.map(l=>l.name).join(", "),o={out:""};for(const l of i.elements)Ws(l,t,s,a+s.indentPerLevel,o);switch(o.out.trim()===""&&(o.out=D(a+s.indentPerLevel)+(t==="python"?`pass `:` -`)),t){case"java":return`${Z(a)}${Hd(e)} -${o.out}${Z(a)}} -`;case"python":return`${Z(a)}def ${e.name}(${r}): -${o.out}`;case"javascript":return`${Z(a)}function ${e.name}(${r}) { -${o.out}${Z(a)}} -`}}const Z=i=>i>0?" ".repeat(i):"";function me(i,e){const t=i.exec(e);return t?Array.from(t,n=>n??""):void 0}function a3(i,e){return i==="python"?"# empty element":"// empty element"}const oo=i=>i.trim()==="ø";function Vd(i,e){return Z(i)+(e==="python"?`# empty element +`)),t){case"java":return`${D(a)}${Hd(e)} +${o.out}${D(a)}} +`;case"python":return`${D(a)}def ${e.name}(${r}): +${o.out}`;case"javascript":return`${D(a)}function ${e.name}(${r}) { +${o.out}${D(a)}} +`}}const D=i=>i>0?" ".repeat(i):"";function me(i,e){const t=i.exec(e);return t?Array.from(t,n=>n??""):void 0}function a3(i,e){return i==="python"?"# empty element":"// empty element"}const oo=i=>i.trim()==="ø";function Vd(i,e){return D(i)+(e==="python"?`# empty element `:`// empty element -`)}function s3(i){switch(i.type){case z.leerElement:return!0;case z.anweisung:case z.aufruf:return i.textLines.map(e=>e.trim()).every(e=>e===""||oo(e));default:return!1}}function r3(i){return i.every(s3)}function jl(i,e,t){const n=i.map(a=>a.replace(/^[ \t]+|[ \t]+$/g,"")).filter(a=>a!=="");return n.length===0?"":e==="python"?Z(t)+`""" -`+n.map(a=>Z(t)+a+` -`).join("")+Z(t)+`""" -`:n.length===1?Z(t)+"/* "+n[0]+` */ -`:Z(t)+`/* -`+n.map(a=>Z(t)+" * "+a+` -`).join("")+Z(t)+` */ -`}const o3=i=>i==="java"||i==="javascript";function ns(i){const e=i.trim();if(e==="")return"";if(e.startsWith("//")||e.startsWith("/*")||e.startsWith("*")||e.startsWith("#")||e.startsWith("{")||e.startsWith("}")||e.endsWith("{")||e.endsWith(";"))return e;const t=e.toLowerCase();for(const n of["if ","else","for ","while ","do ","switch ","case ","default"])if(t.startsWith(n))return e;return e+";"}function ja(i){const e=i.map(t=>t.trim()).filter(t=>t!=="");return l3(e.length===0?"true":e.join(" "))}function l3(i){const e=i.trim();for(const t of["if","while","until","switch"]){const n=Qd(t,e);if(n!==void 0)return n===""?"true":n}return e}function Qd(i,e){if(!e.toLowerCase().startsWith(i))return;const t=e.slice(i.length);if(!(t===""||/^\s/.test(t)||t[0]==="("))return;let n=t.trim();return n.startsWith("(")&&n.endsWith(")")&&n.length>=2&&(n=n.slice(1,-1).trim()),n}function nn(i){let e=i.trim();for(;e.endsWith(";");)e=e.slice(0,-1).trim();return e}function u3(i){const e=i.trim(),t=e.toLowerCase();let n;if(t.startsWith("output:"))n=e.slice(7).trim();else if(t.startsWith("print:"))n=e.slice(6).trim();else return;return n===""?void 0:n}const Zs=i=>i.name.includes("[")&&i.name.includes("]");function Cl(i){const e=i.trim();if(e==="")return;const t=me(/^\s*(integer|int|long|float|double|string|boolean|char|bool)\s+([a-zA-Z_]\w*(?:\s*\[[^\]]+\])?)(?:\s+"([^"]*)")?\s*$/i,e);if(t){const s=t[2].replaceAll(" ","");if(s==="")return;const r=(t[3]??"").trim();return{type:is(t[1]),name:s,customPrompt:r===""?void 0:r}}const n=me(/^\s*([a-zA-Z_]\w*(?:\s*\[[^\]]+\])?)\s+"([^"]*)"\s*$/i,e);if(n){const s=n[1].replaceAll(" ","");return["int","integer","long","float","double","string","boolean","char","bool","void"].includes(s.toLowerCase())?void 0:{type:s.includes("[")?"String":"int",name:s,customPrompt:n[2].trim()}}const a=m3(e);if(a)return{type:is(a[0]),name:a[1]}}function is(i){switch(i.trim().toLowerCase()){case"integer":case"int":return"int";case"long":return"long";case"float":return"float";case"double":return"double";case"string":return"String";case"boolean":case"bool":return"boolean";case"char":return"char";default:return i}}function m3(i){const e=i.split(/[ \t]+/).filter(Boolean);if(e.length===0)return;if(e.length>=2)return[e[0],e[1]];if(!["int","double","string","boolean","char","long","float","short","byte","void","bool","integer"].includes(e[0].toLowerCase()))return["int",e[0]]}function c3(i,e,t,n,a){const s=nn(i).trim();if(s.startsWith('"'))switch(e){case"java":return Z(t)+"System.out.println("+s+`); -`;case"javascript":return Z(t)+"console.log("+s+`); -`;case"python":return Z(t)+"print("+Xn(s,n,a)+`) +`)}function s3(i){switch(i.type){case z.leerElement:return!0;case z.anweisung:case z.aufruf:return i.textLines.map(e=>e.trim()).every(e=>e===""||oo(e));default:return!1}}function r3(i){return i.every(s3)}function jl(i,e,t){const n=i.map(a=>a.replace(/^[ \t]+|[ \t]+$/g,"")).filter(a=>a!=="");return n.length===0?"":e==="python"?D(t)+`""" +`+n.map(a=>D(t)+a+` +`).join("")+D(t)+`""" +`:n.length===1?D(t)+"/* "+n[0]+` */ +`:D(t)+`/* +`+n.map(a=>D(t)+" * "+a+` +`).join("")+D(t)+` */ +`}const o3=i=>i==="java"||i==="javascript";function ns(i){const e=i.trim();if(e==="")return"";if(e.startsWith("//")||e.startsWith("/*")||e.startsWith("*")||e.startsWith("#")||e.startsWith("{")||e.startsWith("}")||e.endsWith("{")||e.endsWith(";"))return e;const t=e.toLowerCase();for(const n of["if ","else","for ","while ","do ","switch ","case ","default"])if(t.startsWith(n))return e;return e+";"}function ja(i){const e=i.map(t=>t.trim()).filter(t=>t!=="");return l3(e.length===0?"true":e.join(" "))}function l3(i){const e=i.trim();for(const t of["if","while","until","switch"]){const n=Qd(t,e);if(n!==void 0)return n===""?"true":n}return e}function Qd(i,e){if(!e.toLowerCase().startsWith(i))return;const t=e.slice(i.length);if(!(t===""||/^\s/.test(t)||t[0]==="("))return;let n=t.trim();return n.startsWith("(")&&n.endsWith(")")&&n.length>=2&&(n=n.slice(1,-1).trim()),n}function Ft(i){let e=i.trim();for(;e.endsWith(";");)e=e.slice(0,-1).trim();return e}function u3(i){const e=i.trim(),t=e.toLowerCase();let n;if(t.startsWith("output:"))n=e.slice(7).trim();else if(t.startsWith("print:"))n=e.slice(6).trim();else return;return n===""?void 0:n}const Zs=i=>i.name.includes("[")&&i.name.includes("]");function Cl(i){const e=i.trim();if(e==="")return;const t=me(/^\s*(integer|int|long|float|double|string|boolean|char|bool)\s+([a-zA-Z_]\w*(?:\s*\[[^\]]+\])?)(?:\s+"([^"]*)")?\s*$/i,e);if(t){const s=t[2].replaceAll(" ","");if(s==="")return;const r=(t[3]??"").trim();return{type:is(t[1]),name:s,customPrompt:r===""?void 0:r}}const n=me(/^\s*([a-zA-Z_]\w*(?:\s*\[[^\]]+\])?)\s+"([^"]*)"\s*$/i,e);if(n){const s=n[1].replaceAll(" ","");return["int","integer","long","float","double","string","boolean","char","bool","void"].includes(s.toLowerCase())?void 0:{type:s.includes("[")?"String":"int",name:s,customPrompt:n[2].trim()}}const a=m3(e);if(a)return{type:is(a[0]),name:a[1]}}function is(i){switch(i.trim().toLowerCase()){case"integer":case"int":return"int";case"long":return"long";case"float":return"float";case"double":return"double";case"string":return"String";case"boolean":case"bool":return"boolean";case"char":return"char";default:return i}}function m3(i){const e=i.split(/[ \t]+/).filter(Boolean);if(e.length===0)return;if(e.length>=2)return[e[0],e[1]];if(!["int","double","string","boolean","char","long","float","short","byte","void","bool","integer"].includes(e[0].toLowerCase()))return["int",e[0]]}function c3(i,e,t,n,a){const s=Ft(i).trim();if(s.startsWith('"'))switch(e){case"java":return D(t)+"System.out.println("+s+`); +`;case"javascript":return D(t)+"console.log("+s+`); +`;case"python":return D(t)+"print("+On(s,n,a)+`) `}}function xi(i){return i.replaceAll("\\","\\\\").replaceAll('"','\\"').replaceAll(` -`,"\\n").replaceAll("\r","\\r")}function Bl(i,e){const t=i.trim();if(!t.toLowerCase().startsWith("input:"))return;const n=t.slice(6).trim();if(n==="")return;const a=Cl(n);if(a&&Zs(a)&&!/^\s*(integer|int|long|float|double|string|boolean|char|bool)\s/i.test(n)){const s=e.get(a.name.slice(0,a.name.indexOf("[")).trim());if(s)return{...a,type:s}}return a}function d3(i){const e=new Set;return dn(i.elements,t=>{for(const n of t.textLines){const a=n.trim();if(a.toLowerCase().startsWith("input:")){const o=Cl(a.slice(6).trim());(o==null?void 0:o.type)==="String"&&!Zs(o)&&e.add(o.name);continue}const s=me(/^\s*(?:const\s+)?string\s+([a-zA-Z_]\w*)\s*=/i,a);s&&e.add(s[1]);const r=me(/^\s*string\s*\[\s*\]\s*([a-zA-Z_]\w*)\s*=/i,a);r&&e.add(r[1]+"[]")}}),e}function h3(i){const e=new Map;return dn(i.elements,t=>{for(const n of t.textLines){const a=me(/^\s*(integer|int|long|float|double|string|boolean|char|bool)\s*\[\s*\]\s*([a-zA-Z_]\w*)/i,n)??me(/^\s*(integer|int|long|float|double|string|boolean|char|bool)\s+([a-zA-Z_]\w*)\s*\[\s*\]/i,n);a&&e.set(a[2],is(a[1]))}}),e}function g3(i,e,t){const n=Bl(i,t);if(!n)return;const a=n.customPrompt?n.customPrompt:n.name+": ",s=Z(e)+'System.out.println("'+xi(a)+`"); -`,r=o=>Zs(n)?n.name:`${o} ${n.name}`;switch(n.type){case"int":return s+Z(e)+`${r("int")} = scanner.nextInt(); -`;case"double":return s+Z(e)+`${r("double")} = scanner.nextDouble(); -`;case"String":return s+Z(e)+`${r("String")} = scanner.next(); -`;case"boolean":return s+Z(e)+`${r("boolean")} = scanner.nextBoolean(); -`;default:return}}function p3(i,e,t){const n=Bl(i,t);if(!n)return;const a=!!n.customPrompt,s=a?"":Z(e)+'console.log("'+xi(n.name+": ")+`"); -`,r=l=>{const u=a?n.customPrompt:n.name+": ";return`(prompt("${xi(u)}") ?? "${l}")`},o=Zs(n)?n.name:`let ${n.name}`;switch(n.type){case"int":return s+Z(e)+`${o} = parseInt(${r("0")}, 10); -`;case"double":return s+Z(e)+`${o} = Number(${r("0")}); -`;case"String":return s+Z(e)+`${o} = ${r("")}; -`;case"boolean":return s+Z(e)+`${o} = ${r("")}.trim().toLowerCase() === "true"; -`;default:return}}function f3(i,e,t){const n=Bl(i,t);if(!n)return;const a=!!n.customPrompt,s=a?"":Z(e)+'print("'+xi(n.name+": ")+`") -`,r=`input("${xi(a?n.customPrompt:n.name+": ")}")`;switch(n.type){case"int":return s+Z(e)+`${n.name} = int(${r}) -`;case"double":return s+Z(e)+`${n.name} = float(${r}) -`;case"String":return s+Z(e)+`${n.name} = ${r} -`;case"boolean":return s+Z(e)+`${n.name} = ${r}.strip().lower() in ("true", "wahr") -`;default:return}}const rr=String.raw`("(?:[^"\\]|\\.)*"|[A-Za-z_]\w*)`,x3=[[new RegExp(String.raw`^new\s+Scanner\s*\(\s*new\s+File\s*\(\s*${rr}\s*\)\s*\)$`),"Scanner"],[new RegExp(String.raw`^new\s+BufferedReader\s*\(\s*new\s+FileReader\s*\(\s*${rr}\s*\)\s*\)$`),"BufferedReader"],[new RegExp(String.raw`^new\s+PrintWriter\s*\(\s*(?:new\s+(?:File|FileWriter)\s*\(\s*)?${rr}\s*\)?\s*\)$`),"PrintWriter"]];function qd(i){const e=i.trim();for(const[t,n]of x3){const a=t.exec(e);if(a)return{kind:n,name:a[1]}}}function b3(i,e,t,n,a){if(e==="java")return;const s=nn(i).trim(),r=/^(?:(?:Scanner|BufferedReader|PrintWriter)\s+)?([A-Za-z_]\w*)\s*=\s*(new\s[\s\S]+)$/.exec(s),o=r&&qd(r[2]);if(r&&o){const m=/^(?:Scanner|BufferedReader|PrintWriter)\s/.test(s);return e==="python"?Z(t)+`${r[1]} = ${o.kind}(${o.name}) -`:Z(t)+`${m?"let ":""}${r[1]} = new ${o.kind}(${o.name}); -`}const l=/^([A-Za-z_]\w*)\.(println|print)\s*\(([\s\S]*)\)$/.exec(s);if(l&&l[1]!=="System"){const m=l[3].trim(),c=e==="python"&&m!==""?Xn(m,n,a):m;return Z(t)+`${l[1]}.${l[2]}(${c})${e==="javascript"?";":""} -`}const u=/^Files\.writeString\s*\(\s*(?:Path\.of|Paths\.get)\s*\(\s*("(?:[^"\\]|\\.)*")\s*\)\s*,\s*([\s\S]+)\)$/.exec(s);if(u){const m=u[2].trim();return e==="python"?Z(t)+`open(${u[1]}, "w", encoding="utf-8").write(${Xn(m,n,a)}) -`:Z(t)+`require("fs").writeFileSync(${u[1]}, ${m}); +`,"\\n").replaceAll("\r","\\r")}function Bl(i,e){const t=i.trim();if(!t.toLowerCase().startsWith("input:"))return;const n=t.slice(6).trim();if(n==="")return;const a=Cl(n);if(a&&Zs(a)&&!/^\s*(integer|int|long|float|double|string|boolean|char|bool)\s/i.test(n)){const s=e.get(a.name.slice(0,a.name.indexOf("[")).trim());if(s)return{...a,type:s}}return a}function d3(i){const e=new Set;return dn(i.elements,t=>{for(const n of t.textLines){const a=n.trim();if(a.toLowerCase().startsWith("input:")){const o=Cl(a.slice(6).trim());(o==null?void 0:o.type)==="String"&&!Zs(o)&&e.add(o.name);continue}const s=me(/^\s*(?:const\s+)?string\s+([a-zA-Z_]\w*)\s*=/i,a);s&&e.add(s[1]);const r=me(/^\s*string\s*\[\s*\]\s*([a-zA-Z_]\w*)\s*=/i,a);r&&e.add(r[1]+"[]")}}),e}function h3(i){const e=new Map;return dn(i.elements,t=>{for(const n of t.textLines){const a=me(/^\s*(integer|int|long|float|double|string|boolean|char|bool)\s*\[\s*\]\s*([a-zA-Z_]\w*)/i,n)??me(/^\s*(integer|int|long|float|double|string|boolean|char|bool)\s+([a-zA-Z_]\w*)\s*\[\s*\]/i,n);a&&e.set(a[2],is(a[1]))}}),e}function g3(i,e,t){const n=Bl(i,t);if(!n)return;const a=n.customPrompt?n.customPrompt:n.name+": ",s=D(e)+'System.out.println("'+xi(a)+`"); +`,r=o=>Zs(n)?n.name:`${o} ${n.name}`;switch(n.type){case"int":return s+D(e)+`${r("int")} = scanner.nextInt(); +`;case"double":return s+D(e)+`${r("double")} = scanner.nextDouble(); +`;case"String":return s+D(e)+`${r("String")} = scanner.next(); +`;case"boolean":return s+D(e)+`${r("boolean")} = scanner.nextBoolean(); +`;default:return}}function p3(i,e,t){const n=Bl(i,t);if(!n)return;const a=!!n.customPrompt,s=a?"":D(e)+'console.log("'+xi(n.name+": ")+`"); +`,r=l=>{const u=a?n.customPrompt:n.name+": ";return`(prompt("${xi(u)}") ?? "${l}")`},o=Zs(n)?n.name:`let ${n.name}`;switch(n.type){case"int":return s+D(e)+`${o} = parseInt(${r("0")}, 10); +`;case"double":return s+D(e)+`${o} = Number(${r("0")}); +`;case"String":return s+D(e)+`${o} = ${r("")}; +`;case"boolean":return s+D(e)+`${o} = ${r("")}.trim().toLowerCase() === "true"; +`;default:return}}function f3(i,e,t){const n=Bl(i,t);if(!n)return;const a=!!n.customPrompt,s=a?"":D(e)+'print("'+xi(n.name+": ")+`") +`,r=`input("${xi(a?n.customPrompt:n.name+": ")}")`;switch(n.type){case"int":return s+D(e)+`${n.name} = int(${r}) +`;case"double":return s+D(e)+`${n.name} = float(${r}) +`;case"String":return s+D(e)+`${n.name} = ${r} +`;case"boolean":return s+D(e)+`${n.name} = ${r}.strip().lower() in ("true", "wahr") +`;default:return}}const rr=String.raw`("(?:[^"\\]|\\.)*"|[A-Za-z_]\w*)`,x3=[[new RegExp(String.raw`^new\s+Scanner\s*\(\s*new\s+File\s*\(\s*${rr}\s*\)\s*\)$`),"Scanner"],[new RegExp(String.raw`^new\s+BufferedReader\s*\(\s*new\s+FileReader\s*\(\s*${rr}\s*\)\s*\)$`),"BufferedReader"],[new RegExp(String.raw`^new\s+PrintWriter\s*\(\s*(?:new\s+(?:File|FileWriter)\s*\(\s*)?${rr}\s*\)?\s*\)$`),"PrintWriter"]];function qd(i){const e=i.trim();for(const[t,n]of x3){const a=t.exec(e);if(a)return{kind:n,name:a[1]}}}function b3(i,e,t,n,a){if(e==="java")return;const s=Ft(i).trim(),r=/^(?:(?:Scanner|BufferedReader|PrintWriter)\s+)?([A-Za-z_]\w*)\s*=\s*(new\s[\s\S]+)$/.exec(s),o=r&&qd(r[2]);if(r&&o){const m=/^(?:Scanner|BufferedReader|PrintWriter)\s/.test(s);return e==="python"?D(t)+`${r[1]} = ${o.kind}(${o.name}) +`:D(t)+`${m?"let ":""}${r[1]} = new ${o.kind}(${o.name}); +`}const l=/^([A-Za-z_]\w*)\.(println|print)\s*\(([\s\S]*)\)$/.exec(s);if(l&&l[1]!=="System"){const m=l[3].trim(),c=e==="python"&&m!==""?On(m,n,a):m;return D(t)+`${l[1]}.${l[2]}(${c})${e==="javascript"?";":""} +`}const u=/^Files\.writeString\s*\(\s*(?:Path\.of|Paths\.get)\s*\(\s*("(?:[^"\\]|\\.)*")\s*\)\s*,\s*([\s\S]+)\)$/.exec(s);if(u){const m=u[2].trim();return e==="python"?D(t)+`open(${u[1]}, "w", encoding="utf-8").write(${On(m,n,a)}) +`:D(t)+`require("fs").writeFileSync(${u[1]}, ${m}); `}}function v3(i){const e=new Set;for(const t of i)dn(t.elements,n=>{for(const a of n.textLines){const s=/=\s*(new\s.+?);?\s*$/.exec(a),r=s&&qd(s[1]);r&&e.add(r.kind)}});return e}const y3={Scanner:`class Scanner: def __init__(self, name): self.lines = open(name, encoding="utf-8").read().splitlines() @@ -113,69 +113,72 @@ ${o.out}${Z(a)}} } `};function lo(i,e){const t=v3(i);if(t.size===0)return"";const n=e==="python"?y3:w3;return[...t].map(a=>n[a]).join(` `)+` -`}function z3(i,e,t,n,a){const s=u3(i);if(s===void 0)return/^\s*(?:output|print):\s*$/i.test(i)?Z(t)+{java:"System.out.println();",javascript:"console.log();",python:"print()"}[e]+` -`:void 0;switch(e){case"java":return Z(t)+"System.out.println("+s+`); -`;case"javascript":return Z(t)+"console.log("+s+`); -`;case"python":return Z(t)+"print("+Xn(s,n,a)+`) -`}}function Dl(i){const e=i.map(nn).filter(t=>t!=="");return e.length===0?";;":e.join("; ")}function I3(i){const t=Dl(i).split(";"),n=Ud(t[0]);return n!==void 0&&(t[0]=n),t.join(";")}function Ud(i){const e=me(/^(\s*)(?:integer|int|long|float|double|string|boolean|char|bool)\s+(\w+)(?:\s*=\s*(.*))?\s*$/i,i);if(!e)return;const t=e[2].trim();if(t==="")return;const n=(e[3]??"").trim();return i.includes("=")&&n!==""?e[1]+`let ${t} = ${n}`:e[1]+`let ${t}`}function k3(i){const e=i.map(n=>nn(n).trim()).filter(n=>n!=="");let t=e;if(e.length===1){let n=e[0];const a=Qd("for",n);a!==void 0&&(n=a),t=n.split(";").map(s=>s.trim())}if(!(t.length!==3||t.some(n=>n==="")))return[t[0],t[1],t[2]]}function $d(i,e){let t=me(/^\s*(\w+)\s*(\+\+|--)\s*$/,i)??me(/^\s*(\+\+|--)\s*(\w+)\s*$/,i);if(t){const[n,a]=t[1]==="++"||t[1]==="--"?[t[2],t[1]]:[t[1],t[2]];return n===e?a==="++"?1:-1:void 0}if(t=me(/^\s*(\w+)\s*(\+|-)=\s*(\d+)\s*$/,i),t)return t[1]===e?(t[2]==="+"?1:-1)*Number(t[3]):void 0;if(t=me(/^\s*(\w+)\s*=\s*(\w+)\s*(\+|-)\s*(\d+)\s*$/,i),t)return t[1]===e&&t[2]===e?(t[3]==="+"?1:-1)*Number(t[4]):void 0}function uo(i,e){if(/^-?\d+$/.test(i))return String(Number(i)+e);const t=/^[\w.()[\]]+$/.test(i)?i:`(${i})`;return e>0?`${t} + ${e}`:`${t} - ${-e}`}function S3(i,e){const t=k3(i);if(!t)return;const[n,a,s]=t,r=me(/^\s*(?:integer|int|long|short|byte|double|float)?\s*([a-zA-Z_]\w*)\s*=\s*(.+)$/i,n);if(!r)return;const o=r[1],l={variable:o,init:`${o} = ${Oe(r[2],e)}`,condition:a,increment:s},u=me(/^\s*(\w+)\s*(<=|<|>=|>)\s*(.+)$/,a),m=$d(s,o);if(!u||u[1]!==o||m===void 0||m===0)return l;const c=Oe(r[2],e);let d=Oe(u[3],e);const h=u[2];if(m>0&&h==="<=")d=uo(d,1);else if(m<0&&h===">=")d=uo(d,-1);else if(!(m>0&&h==="<")&&!(m<0&&h===">"))return l;const g=m===1?c==="0"?[d]:[c,d]:[c,d,String(m)];return l.rangeLine=`for ${o} in range(${g.join(", ")}):`,l}function Yd(i){const e=nn(i).trim();if(e==="")return;const t=me(/^\s*const\s+(integer|int|long|float|double|string|boolean|char|bool)\s+(\w+)(?:\s*=\s*(.*))?$/i,e);if(!t)return;const n=t[2].trim();if(n==="")return;if(!e.includes("="))return{rawType:t[1].trim(),name:n};const a=(t[3]??"").trim();if(a!=="")return{rawType:t[1].trim(),name:n,rhs:a}}function _3(i,e,t,n){var o;const a=Yd(i);if(!a)return;const s=is(a.rawType),r=(o=a.rhs)==null?void 0:o.trim();switch(e){case"java":return Z(t)+ns(r?`final ${s} ${a.name} = ${r}`:`final ${s} ${a.name}`)+` -`;case"javascript":return r?Z(t)+ns(`const ${a.name} = ${r}`)+` -`:Z(t)+`let ${a.name}; // from diagram: const ${s} ${a.name} -`;case"python":return r?Z(t)+`${a.name} = ${Ls(r,n)} # const ${s} -`:Z(t)+`${a.name} = None # const ${s}, uninitialized -`}}function T3(i){const e=nn(i).trim();if(e===""||ih(e))return;const t=me(/^\s*(?:integer|int|long|float|double|string|boolean|char|bool)(?:\s*\[\s*\]\s+(\w+)|\s+(\w+)(\s*\[\s*\])?)\s*=\s*(.*)$/i,e);if(!t)return;const n=t[1]===""?t[2]:t[1],a=t[4].trim();if(a!=="")return{name:n,rhs:a,isArray:t[1]!==""||t[3]!==""}}function Ms(i){const e=me(/^\s*\(\s*int(?:eger)?\s*\)\s*(.+?)\s*$/i,i),t=e==null?void 0:e[1].trim();if(!(!t||Xd(t)))return t.startsWith("(")&&mo(t,0)===t.length-1?t.slice(1,-1).trim():t}function mo(i,e){let t=0;for(let n=e;n/^'.'$/u.test(i)||/\.charAt\(.*\)$/.test(i);function O3(i,e){if(i[e]==="("){const a=mo(i,e);return a<0?-1:a+1}if(i[e]==="'")return i[e+2]==="'"?e+3:-1;const t=/^(?:[A-Za-z_]\w*|\d+)/.exec(i.slice(e));if(!t)return-1;let n=e+t[0].length;for(;;){const a=/^\.[A-Za-z_]\w*/.exec(i.slice(n));if(a)n+=a[0].length;else if(i[n]==="("||i[n]==="["){const s=mo(i,n);if(s<0)return-1;n=s+1}else return n}}function co(i,e){return Zl(i,t=>{const n=/\(\s*(int|char)\s*\)\s*/g;let a="",s=0;for(let r=n.exec(t);r;r=n.exec(t)){const o=r.index+r[0].length,l=O3(t,o);if(l<0)continue;const u=t.slice(o,l);if(r[1]==="int"&&!Xd(u))continue;const m=co(u.startsWith("(")?u.slice(1,-1).trim():u,e),c=r[1]==="int"?e==="python"?`ord(${m})`:`${m}.charCodeAt(0)`:e==="python"?`chr(${m})`:`String.fromCharCode(${m})`;a+=t.slice(s,r.index)+c,s=l,n.lastIndex=l}return a+t.slice(s)})}function Ls(i,e=new Set){const t=i.trim();if(t==="null")return"None";const n=Ms(t);return n!==void 0?`int(${Ls(n,e)})`:Oe(t,e)}function Zl(i,e){let t="",n="",a=0;for(;a/^\d+$/.test(a)||e.has(a);return Zl(t,a=>a.replace(/\bMath\.random\s*\(\s*\)/gi,"random.random()").replace(/===/g,"==").replace(/!==/g,"!=").replace(/\s*&&\s*/g," and ").replace(/\s*\|\|\s*/g," or ").replace(/!(?!=)\s*/g,"not ").replace(/\btrue\b/g,"True").replace(/\bfalse\b/g,"False").replace(/\bnull\b/g,"None").replace(new RegExp("(?n(r)&&n(o)?`${r} // ${o}`:s))}function Kd(i){const e=[];let t=0,n="",a=!1;for(let s=0;s/^"(?:[^"\\]|\\.)*"$/.test(i);function Xn(i,e,t){const n=Kd(i),a=s=>Ml(s)||t.has(s)||t.has(s.replace(/^([A-Za-z_]\w*)\[[^[\]]*\]$/u,"$1[]"));return n.length<2||!n.some(a)||n.some(s=>s==="")?Oe(i,e):n.map(s=>a(s)?s:`str(${Oe(s,e)})`).join(" + ")}function eh(i,e,t=new Set){const n=nn(i).trim(),a=me(/^(\w+(?:\[[^\]]*\])?)\s*(\+\+|--)$/,n)??me(/^(\+\+|--)\s*(\w+(?:\[[^\]]*\])?)$/,n);if(a){const[o,l]=a[1]==="++"||a[1]==="--"?[a[2],a[1]]:[a[1],a[2]];return`${Oe(o,e)} ${l==="++"?"+=":"-="} 1`}const s=me(/^(\w+)\s*\/=\s*(.+)$/,n);if(s&&e.has(s[1]))return`${s[1]} //= ${Oe(s[2],e)}`;const r=me(/^([\w[\]. ]+?)\s*(=|\+=|-=|\*=|\/=|%=)\s*(.+)$/,n);if(r&&!r[3].startsWith("=")){const[,o,l,u]=r;let m;if(l==="+="&&t.has(o.trim())){const c=Kd(u);m=Xn(`"" + ${u}`,e,t).replace(/^"" \+ /,""),c.length===1&&!Ml(u.trim())&&!t.has(u.trim())&&(m=`str(${Oe(u,e)})`)}else l==="="&&Ms(u)===void 0&&u.trim()!=="null"?m=Xn(u,e,t):m=l==="="?Ls(u,e):Oe(u,e);return`${o} ${l} ${m}`}return Oe(n,e)}const A3=i=>i.replace(/\bMath\.random\b(?!\s*\()/gi,"Math.random()");function th(i){const e=i.trim();return e.startsWith("{")&&e.endsWith("}")?"["+e.slice(1,-1)+"]":i}function nh(i){const e=me(/^\s*new\s+(?:byte|short|int|long|float|double|boolean|char|string)\s*\[\s*(.+)\s*\]\s*$/i,i),t=e==null?void 0:e[1].trim();return t||void 0}function ih(i){const e=me(/^\s*(int|double|string|boolean)\s*\[\s*\]\s*\[\s*\]\s*([a-zA-Z_]\w*)\s*=\s*(.+)$/i,nn(i).trim());return e?{elementType:e[1].toLowerCase(),name:e[2],rhs:e[3].trim()}:void 0}function P3(i){const e=me(/^\s*new\s+(?:int|double|string|boolean)\s*\[\s*(.+?)\s*\]\s*\[\s*(.+?)\s*\]\s*$/i,i);return e?[e[1],e[2]]:void 0}const au=i=>i.replaceAll("{","[").replaceAll("}","]");function su(i,e){return i==="boolean"?e==="python"?"False":"false":i==="string"?'""':i==="double"?"0.0":"0"}function j3(i,e,t){const n=P3(i.rhs);return e==="javascript"?n?`Array.from({ length: ${n[0]} }, () => new Array(${n[1]}).fill(${su(i.elementType,e)}))`:au(i.rhs):n?`[[${su(i.elementType,e)}] * ${Oe(n[1],t)} for _ in range(${Oe(n[0],t)})]`:Oe(au(i.rhs),t)}function ah(i,e){const t=i.trim();if(e){const a=nh(t);return a!==void 0?`new Array(${a})`:th(t)}const n=Ms(t);return n!==void 0?`Math.floor(${ah(n,!1)})`:A3(t)}function C3(i,e,t){const n=i.trim();if(e){const a=nh(n);return a!==void 0?`[None] * ${a}`:Oe(th(n),t)}return Ls(n,t)}function B3(i,e,t,n,a){if(e==="java")return;const s=ih(i);if(s){const u=j3(s,e,n);return e==="javascript"?Z(t)+`let ${s.name} = ${u}; -`:Z(t)+`${s.name} = ${u} -`}const r=T3(i);if(!r)return;if(e==="javascript")return Z(t)+ns(`let ${r.name} = ${ah(r.rhs,r.isArray)}`)+` -`;const l=!r.isArray&&Ms(r.rhs)===void 0&&r.rhs.trim()!=="null"?Xn(r.rhs,n,a):C3(r.rhs,r.isArray,n);return Z(t)+`${r.name} = ${l} -`}function dn(i,e){for(const t of i){e(t),t.loopBody&&dn(t.loopBody,e);for(const n of t.cases??[])dn(n.elements,e)}}function D3(i){const e=n=>["int","integer","long","short","byte"].includes(n.trim().toLowerCase()),t=new Set;return dn(i.elements,n=>{for(const a of n.textLines){const s=a.trim();if(s==="")continue;if(s.toLowerCase().startsWith("input:")){const l=Cl(s.slice(6).trim());l&&e(l.type)&&!l.name.includes("[")&&t.add(l.name);continue}const r=Yd(s);if(r&&e(r.rawType)){t.add(r.name);continue}const o=me(/^\s*(integer|int|long|short|byte)\s+([a-zA-Z_]\w*)\s*=/i,s);o&&t.add(o[2].trim())}}),t}function ho(i,e){const t=r=>/^\d+$/.test(r)||e.has(r),n=String.raw`(?:[a-zA-Z_]\w*|\d+(?:\.\d+)?)`,a=new RegExp(String.raw`(?{const o=r.split(/\s*([*/%])\s*/);if(!o.some(m=>m==="/"))return r;let l=o[0],u=t(o[0]);for(let m=1;mr.replace(a,s).replace(new RegExp("(?t(l)&&t(u)?`${l} = Math.trunc(${l} / ${u})`:o))}function as(i){let e=!1;return dn(i.elements,t=>{t.type===z.anweisung&&t.textLines.some(n=>n.trim().toLowerCase().startsWith("input:"))&&(e=!0)}),e}function Ll(i){let e=!1,t=!1,n=!1;return dn(i.elements,a=>{for(const s of a.textLines)/\bFiles\s*\./.test(s)&&(e=!0),/\bnew\s+(?:File|PrintWriter|FileReader|FileWriter|BufferedReader)\s*\(/.test(s)&&(t=!0),/\bnew\s+Scanner\s*\(\s*new\s+File\b/.test(s)&&(n=!0)}),[...t?["import java.io.*;"]:[],...e?["import java.nio.file.*;"]:[],...n?["import java.util.Scanner;"]:[]]}function Z3(i){return Ll(i).length>0}function sh(i){let e=!1;return dn(i.elements,t=>{t.textLines.some(n=>/\bMath\.random\s*\(/i.test(n))&&(e=!0)}),e}function Ui(i,e){const t=i.trim();return t===""?e==="python"?'""':"0":e==="java"||new RegExp("^\\p{N}+$","u").test(t)||Ml(t)?t:'"'+t.replaceAll('"','\\"')+'"'}function M1(i,e){const t=i.trim();if(t==="")return"";switch(e){case"java":return"/* "+t+" */";case"python":return" # "+t;case"javascript":return" /* "+t+" */"}}function M3(i,e,t,n,a){const s=i.map(r=>r.trim());if(s.every(r=>r==="")){t.live&&(a.out+=Z(n)+(e==="python"?"pass":";")+` -`);return}if(t.includeDiagramTextAsComments){const r=s.filter(o=>o!==""&&!oo(o));r.length>0&&(a.out+=jl(r,e,n))}for(const r of s){if(r==="")continue;if(oo(r)){a.out+=t.live?El(n,t.live):Vd(n,e);continue}const o=t.jsIntVariables??new Set,l=t.arrayElementTypes??new Map,u=t.stringVariables??new Set,m=(e==="java"?g3(r,n,l):void 0)??(e==="javascript"?p3(r,n,l):void 0)??(e==="python"?f3(r,n,l):void 0)??b3(r,e,n,o,u)??z3(r,e,n,o,u)??_3(r,e,n,o)??B3(r,e,n,o,u)??c3(r,e,n,o,u);if(m!==void 0){a.out+=e==="javascript"?ho(m,o):m;continue}let c=r;o3(e)?c=ns(e==="javascript"?ho(r,o):r):e==="python"&&(c=eh(r,o,u)),c!==""&&(a.out+=Z(n)+c+` -`)}}function ni(i,e,t,n,a,s,r,o=(l=>(l=a.live)==null?void 0:l.labels.condition)()){if(a.includeDiagramTextAsComments&&(r.out+=jl(t,n,s)),o!==void 0&&Nl(t)){r.out+=Z(s)+i+Vn(o)+e;return}const u=ja(t),m=a.jsIntVariables??new Set,c=n==="python"?Oe(u,m):n==="javascript"?ho(u,m):u;r.out+=Z(s)+i+c+e}function m1(i,e,t,n,a){const s=a.out.length;for(const o of i)Ws(o,e,t,n,a);if(t.live&&a.out.length===s&&(a.out+=El(n,t.live)),e!=="python")return;a.out.slice(s).split(` -`).map(o=>o.trim()).every(o=>o===""||o.startsWith("#"))&&(a.out+=Z(n)+`pass +`}function z3(i,e,t,n,a){const s=/^System\s*\.\s*out\s*\.\s*print\s*\(([\s\S]*)\)$/.exec(Ft(i).trim());if(s){const o=s[1].trim();switch(e){case"java":return D(t)+"System.out.print("+o+`); +`;case"javascript":return D(t)+"process.stdout.write(String("+o+`)); +`;case"python":return D(t)+"print("+(o===""?"":On(o,n,a)+", ")+`end="") +`}}const r=u3(i);if(r===void 0)return/^\s*(?:output|print):\s*$/i.test(i)?D(t)+{java:"System.out.println();",javascript:"console.log();",python:"print()"}[e]+` +`:void 0;switch(e){case"java":return D(t)+"System.out.println("+r+`); +`;case"javascript":return D(t)+"console.log("+r+`); +`;case"python":return D(t)+"print("+On(r,n,a)+`) +`}}function Dl(i){const e=i.map(Ft).filter(t=>t!=="");return e.length===0?";;":e.join("; ")}function I3(i){const t=Dl(i).split(";"),n=Ud(t[0]);return n!==void 0&&(t[0]=n),t.join(";")}function Ud(i){const e=me(/^(\s*)(?:integer|int|long|float|double|string|boolean|char|bool)\s+(\w+)(?:\s*=\s*(.*))?\s*$/i,i);if(!e)return;const t=e[2].trim();if(t==="")return;const n=(e[3]??"").trim();return i.includes("=")&&n!==""?e[1]+`let ${t} = ${n}`:e[1]+`let ${t}`}function k3(i){const e=i.map(n=>Ft(n).trim()).filter(n=>n!=="");let t=e;if(e.length===1){let n=e[0];const a=Qd("for",n);a!==void 0&&(n=a),t=n.split(";").map(s=>s.trim())}if(!(t.length!==3||t.some(n=>n==="")))return[t[0],t[1],t[2]]}function $d(i,e){let t=me(/^\s*(\w+)\s*(\+\+|--)\s*$/,i)??me(/^\s*(\+\+|--)\s*(\w+)\s*$/,i);if(t){const[n,a]=t[1]==="++"||t[1]==="--"?[t[2],t[1]]:[t[1],t[2]];return n===e?a==="++"?1:-1:void 0}if(t=me(/^\s*(\w+)\s*(\+|-)=\s*(\d+)\s*$/,i),t)return t[1]===e?(t[2]==="+"?1:-1)*Number(t[3]):void 0;if(t=me(/^\s*(\w+)\s*=\s*(\w+)\s*(\+|-)\s*(\d+)\s*$/,i),t)return t[1]===e&&t[2]===e?(t[3]==="+"?1:-1)*Number(t[4]):void 0}function uo(i,e){if(/^-?\d+$/.test(i))return String(Number(i)+e);const t=/^[\w.()[\]]+$/.test(i)?i:`(${i})`;return e>0?`${t} + ${e}`:`${t} - ${-e}`}function S3(i,e){const t=k3(i);if(!t)return;const[n,a,s]=t,r=me(/^\s*(?:integer|int|long|short|byte|double|float)?\s*([a-zA-Z_]\w*)\s*=\s*(.+)$/i,n);if(!r)return;const o=r[1],l={variable:o,init:`${o} = ${Oe(r[2],e)}`,condition:a,increment:s},u=me(/^\s*(\w+)\s*(<=|<|>=|>)\s*(.+)$/,a),m=$d(s,o);if(!u||u[1]!==o||m===void 0||m===0)return l;const c=Oe(r[2],e);let d=Oe(u[3],e);const h=u[2];if(m>0&&h==="<=")d=uo(d,1);else if(m<0&&h===">=")d=uo(d,-1);else if(!(m>0&&h==="<")&&!(m<0&&h===">"))return l;const g=m===1?c==="0"?[d]:[c,d]:[c,d,String(m)];return l.rangeLine=`for ${o} in range(${g.join(", ")}):`,l}function Yd(i){const e=Ft(i).trim();if(e==="")return;const t=me(/^\s*const\s+(integer|int|long|float|double|string|boolean|char|bool)\s+(\w+)(?:\s*=\s*(.*))?$/i,e);if(!t)return;const n=t[2].trim();if(n==="")return;if(!e.includes("="))return{rawType:t[1].trim(),name:n};const a=(t[3]??"").trim();if(a!=="")return{rawType:t[1].trim(),name:n,rhs:a}}function _3(i,e,t,n){var o;const a=Yd(i);if(!a)return;const s=is(a.rawType),r=(o=a.rhs)==null?void 0:o.trim();switch(e){case"java":return D(t)+ns(r?`final ${s} ${a.name} = ${r}`:`final ${s} ${a.name}`)+` +`;case"javascript":return r?D(t)+ns(`const ${a.name} = ${r}`)+` +`:D(t)+`let ${a.name}; // from diagram: const ${s} ${a.name} +`;case"python":return r?D(t)+`${a.name} = ${Ls(r,n)} # const ${s} +`:D(t)+`${a.name} = None # const ${s}, uninitialized +`}}function T3(i){const e=Ft(i).trim();if(e===""||ih(e))return;const t=me(/^\s*(?:integer|int|long|float|double|string|boolean|char|bool)(?:\s*\[\s*\]\s+(\w+)|\s+(\w+)(\s*\[\s*\])?)\s*=\s*(.*)$/i,e);if(!t)return;const n=t[1]===""?t[2]:t[1],a=t[4].trim();if(a!=="")return{name:n,rhs:a,isArray:t[1]!==""||t[3]!==""}}function Ms(i){const e=me(/^\s*\(\s*int(?:eger)?\s*\)\s*(.+?)\s*$/i,i),t=e==null?void 0:e[1].trim();if(!(!t||Xd(t)))return t.startsWith("(")&&mo(t,0)===t.length-1?t.slice(1,-1).trim():t}function mo(i,e){let t=0;for(let n=e;n/^'.'$/u.test(i)||/\.charAt\(.*\)$/.test(i);function O3(i,e){if(i[e]==="("){const a=mo(i,e);return a<0?-1:a+1}if(i[e]==="'")return i[e+2]==="'"?e+3:-1;const t=/^(?:[A-Za-z_]\w*|\d+)/.exec(i.slice(e));if(!t)return-1;let n=e+t[0].length;for(;;){const a=/^\.[A-Za-z_]\w*/.exec(i.slice(n));if(a)n+=a[0].length;else if(i[n]==="("||i[n]==="["){const s=mo(i,n);if(s<0)return-1;n=s+1}else return n}}function co(i,e){return Zl(i,t=>{const n=/\(\s*(int|char)\s*\)\s*/g;let a="",s=0;for(let r=n.exec(t);r;r=n.exec(t)){const o=r.index+r[0].length,l=O3(t,o);if(l<0)continue;const u=t.slice(o,l);if(r[1]==="int"&&!Xd(u))continue;const m=co(u.startsWith("(")?u.slice(1,-1).trim():u,e),c=r[1]==="int"?e==="python"?`ord(${m})`:`${m}.charCodeAt(0)`:e==="python"?`chr(${m})`:`String.fromCharCode(${m})`;a+=t.slice(s,r.index)+c,s=l,n.lastIndex=l}return a+t.slice(s)})}function Ls(i,e=new Set){const t=i.trim();if(t==="null")return"None";const n=Ms(t);return n!==void 0?`int(${Ls(n,e)})`:Oe(t,e)}function Zl(i,e){let t="",n="",a=0;for(;a/^\d+$/.test(a)||e.has(a);return Zl(t,a=>a.replace(/\bMath\.random\s*\(\s*\)/gi,"random.random()").replace(/===/g,"==").replace(/!==/g,"!=").replace(/\s*&&\s*/g," and ").replace(/\s*\|\|\s*/g," or ").replace(/!(?!=)\s*/g,"not ").replace(/\btrue\b/g,"True").replace(/\bfalse\b/g,"False").replace(/\bnull\b/g,"None").replace(new RegExp("(?n(r)&&n(o)?`${r} // ${o}`:s))}function Kd(i){const e=[];let t=0,n="",a=!1;for(let s=0;s/^"(?:[^"\\]|\\.)*"$/.test(i);function On(i,e,t){const n=Kd(i),a=s=>Ml(s)||t.has(s)||t.has(s.replace(/^([A-Za-z_]\w*)\[[^[\]]*\]$/u,"$1[]"));return n.length<2||!n.some(a)||n.some(s=>s==="")?Oe(i,e):n.map(s=>a(s)?s:`str(${Oe(s,e)})`).join(" + ")}function eh(i,e,t=new Set){const n=Ft(i).trim(),a=me(/^(\w+(?:\[[^\]]*\])?)\s*(\+\+|--)$/,n)??me(/^(\+\+|--)\s*(\w+(?:\[[^\]]*\])?)$/,n);if(a){const[o,l]=a[1]==="++"||a[1]==="--"?[a[2],a[1]]:[a[1],a[2]];return`${Oe(o,e)} ${l==="++"?"+=":"-="} 1`}const s=me(/^(\w+)\s*\/=\s*(.+)$/,n);if(s&&e.has(s[1]))return`${s[1]} //= ${Oe(s[2],e)}`;const r=me(/^([\w[\]. ]+?)\s*(=|\+=|-=|\*=|\/=|%=)\s*(.+)$/,n);if(r&&!r[3].startsWith("=")){const[,o,l,u]=r;let m;if(l==="+="&&t.has(o.trim())){const c=Kd(u);m=On(`"" + ${u}`,e,t).replace(/^"" \+ /,""),c.length===1&&!Ml(u.trim())&&!t.has(u.trim())&&(m=`str(${Oe(u,e)})`)}else l==="="&&Ms(u)===void 0&&u.trim()!=="null"?m=On(u,e,t):m=l==="="?Ls(u,e):Oe(u,e);return`${o} ${l} ${m}`}return Oe(n,e)}const A3=i=>i.replace(/\bMath\.random\b(?!\s*\()/gi,"Math.random()");function th(i){const e=i.trim();return e.startsWith("{")&&e.endsWith("}")?"["+e.slice(1,-1)+"]":i}function nh(i){const e=me(/^\s*new\s+(?:byte|short|int|long|float|double|boolean|char|string)\s*\[\s*(.+)\s*\]\s*$/i,i),t=e==null?void 0:e[1].trim();return t||void 0}function ih(i){const e=me(/^\s*(int|double|string|boolean)\s*\[\s*\]\s*\[\s*\]\s*([a-zA-Z_]\w*)\s*=\s*(.+)$/i,Ft(i).trim());return e?{elementType:e[1].toLowerCase(),name:e[2],rhs:e[3].trim()}:void 0}function P3(i){const e=me(/^\s*new\s+(?:int|double|string|boolean)\s*\[\s*(.+?)\s*\]\s*\[\s*(.+?)\s*\]\s*$/i,i);return e?[e[1],e[2]]:void 0}const au=i=>i.replaceAll("{","[").replaceAll("}","]");function su(i,e){return i==="boolean"?e==="python"?"False":"false":i==="string"?'""':i==="double"?"0.0":"0"}function j3(i,e,t){const n=P3(i.rhs);return e==="javascript"?n?`Array.from({ length: ${n[0]} }, () => new Array(${n[1]}).fill(${su(i.elementType,e)}))`:au(i.rhs):n?`[[${su(i.elementType,e)}] * ${Oe(n[1],t)} for _ in range(${Oe(n[0],t)})]`:Oe(au(i.rhs),t)}function ah(i,e){const t=i.trim();if(e){const a=nh(t);return a!==void 0?`new Array(${a})`:th(t)}const n=Ms(t);return n!==void 0?`Math.floor(${ah(n,!1)})`:A3(t)}function C3(i,e,t){const n=i.trim();if(e){const a=nh(n);return a!==void 0?`[None] * ${a}`:Oe(th(n),t)}return Ls(n,t)}function B3(i,e,t,n,a){if(e==="java")return;const s=ih(i);if(s){const u=j3(s,e,n);return e==="javascript"?D(t)+`let ${s.name} = ${u}; +`:D(t)+`${s.name} = ${u} +`}const r=T3(i);if(!r)return;if(e==="javascript")return D(t)+ns(`let ${r.name} = ${ah(r.rhs,r.isArray)}`)+` +`;const l=!r.isArray&&Ms(r.rhs)===void 0&&r.rhs.trim()!=="null"?On(r.rhs,n,a):C3(r.rhs,r.isArray,n);return D(t)+`${r.name} = ${l} +`}function dn(i,e){for(const t of i){e(t),t.loopBody&&dn(t.loopBody,e);for(const n of t.cases??[])dn(n.elements,e)}}function D3(i){const e=n=>["int","integer","long","short","byte"].includes(n.trim().toLowerCase()),t=new Set;return dn(i.elements,n=>{for(const a of n.textLines){const s=a.trim();if(s==="")continue;if(s.toLowerCase().startsWith("input:")){const l=Cl(s.slice(6).trim());l&&e(l.type)&&!l.name.includes("[")&&t.add(l.name);continue}const r=Yd(s);if(r&&e(r.rawType)){t.add(r.name);continue}const o=me(/^\s*(integer|int|long|short|byte)\s+([a-zA-Z_]\w*)\s*=/i,s);o&&t.add(o[2].trim())}}),t}function ho(i,e){const t=r=>/^\d+$/.test(r)||e.has(r),n=String.raw`(?:[a-zA-Z_]\w*|\d+(?:\.\d+)?)`,a=new RegExp(String.raw`(?{const o=r.split(/\s*([*/%])\s*/);if(!o.some(m=>m==="/"))return r;let l=o[0],u=t(o[0]);for(let m=1;mr.replace(a,s).replace(new RegExp("(?t(l)&&t(u)?`${l} = Math.trunc(${l} / ${u})`:o))}function as(i){let e=!1;return dn(i.elements,t=>{t.type===z.anweisung&&t.textLines.some(n=>n.trim().toLowerCase().startsWith("input:"))&&(e=!0)}),e}function Ll(i){let e=!1,t=!1,n=!1;return dn(i.elements,a=>{for(const s of a.textLines)/\bFiles\s*\./.test(s)&&(e=!0),/\bnew\s+(?:File|PrintWriter|FileReader|FileWriter|BufferedReader)\s*\(/.test(s)&&(t=!0),/\bnew\s+Scanner\s*\(\s*new\s+File\b/.test(s)&&(n=!0)}),[...t?["import java.io.*;"]:[],...e?["import java.nio.file.*;"]:[],...n?["import java.util.Scanner;"]:[]]}function Z3(i){return Ll(i).length>0}function sh(i){let e=!1;return dn(i.elements,t=>{t.textLines.some(n=>/\bMath\.random\s*\(/i.test(n))&&(e=!0)}),e}function Ui(i,e){const t=i.trim();return t===""?e==="python"?'""':"0":e==="java"||new RegExp("^\\p{N}+$","u").test(t)||Ml(t)?t:'"'+t.replaceAll('"','\\"')+'"'}function M1(i,e){const t=i.trim();if(t==="")return"";switch(e){case"java":return"/* "+t+" */";case"python":return" # "+t;case"javascript":return" /* "+t+" */"}}function M3(i,e,t,n,a){const s=i.map(r=>r.trim());if(s.every(r=>r==="")){t.live&&(a.out+=D(n)+(e==="python"?"pass":";")+` +`);return}if(t.includeDiagramTextAsComments){const r=s.filter(o=>o!==""&&!oo(o));r.length>0&&(a.out+=jl(r,e,n))}for(const r of s){if(r==="")continue;if(oo(r)){a.out+=t.live?El(n,t.live):Vd(n,e);continue}const o=t.jsIntVariables??new Set,l=t.arrayElementTypes??new Map,u=t.stringVariables??new Set,m=(e==="java"?g3(r,n,l):void 0)??(e==="javascript"?p3(r,n,l):void 0)??(e==="python"?f3(r,n,l):void 0)??b3(r,e,n,o,u)??z3(r,e,n,o,u)??_3(r,e,n,o)??B3(r,e,n,o,u)??c3(r,e,n,o,u);if(m!==void 0){a.out+=e==="javascript"?ho(m,o):m;continue}let c=r;o3(e)?c=ns(e==="javascript"?ho(r,o):r):e==="python"&&(c=eh(r,o,u)),c!==""&&(a.out+=D(n)+c+` +`)}}function ni(i,e,t,n,a,s,r,o=(l=>(l=a.live)==null?void 0:l.labels.condition)()){if(a.includeDiagramTextAsComments&&(r.out+=jl(t,n,s)),o!==void 0&&Nl(t)){r.out+=D(s)+i+Qn(o)+e;return}const u=ja(t),m=a.jsIntVariables??new Set,c=n==="python"?Oe(u,m):n==="javascript"?ho(u,m):u;r.out+=D(s)+i+c+e}function m1(i,e,t,n,a){const s=a.out.length;for(const o of i)Ws(o,e,t,n,a);if(t.live&&a.out.length===s&&(a.out+=El(n,t.live)),e!=="python")return;a.out.slice(s).split(` +`).map(o=>o.trim()).every(o=>o===""||o.startsWith("#"))&&(a.out+=D(n)+`pass `)}function L3(i,e){var n;if(e.includeDiagramTextAsComments||i.length!==1)return;const t=i[0];return t.type===z.verzweigung&&(((n=t.cases)==null?void 0:n.length)??0)>=2?t:void 0}function go(i,e,t,n,a,s){const r=i.cases;if(!r||r.length<2)return;const o=e==="python",l=n+t.indentPerLevel,u=!t.includeEmptyElseBranch&&r3(r[1].elements),m=u?void 0:L3(r[1].elements,t);if(o){ni(s?"elif ":"if ",`: -`,i.textLines,e,t,n,a),m1(r[0].elements,e,t,l,a),m?go(m,e,t,n,a,!0):u||(a.out+=Z(n)+`else: +`,i.textLines,e,t,n,a),m1(r[0].elements,e,t,l,a),m?go(m,e,t,n,a,!0):u||(a.out+=D(n)+`else: `,m1(r[1].elements,e,t,l,a));return}if(ni(s?"} else if (":"if (",`) { -`,i.textLines,e,t,n,a),m1(r[0].elements,e,t,l,a),m){const c=a.out.length;go(m,e,t,n,a,!0),oh(t,m,a,c)}else u||(a.out+=Z(n)+`} else { -`,m1(r[1].elements,e,t,l,a)),a.out+=Z(n)+`} -`}function Ws(i,e,t,n,a){const s=a.out.length;W3(i,e,t,n,a),oh(t,i,a,s)}function W3(i,e,t,n,a){var m;const s=t.indentPerLevel,r=e==="python",o=(c,d)=>m1(c,e,t,d,a),l=(c,d)=>ni(c,d,i.textLines,e,t,n,a),u=(c=n)=>{t.includeDiagramTextAsComments&&(a.out+=jl(i.textLines,e,c))};switch(i.type){case z.leerElement:a.out+=t.live?El(n,t.live):Vd(n,e);return;case z.anweisung:case z.aufruf:M3(i.textLines,e,t,n,a);return;case z.aussprung:{const c=ja(i.textLines);i.textLines.some(d=>d.trim()!=="")&&u(),r?a.out+=Z(n)+(c===""?`break +`,i.textLines,e,t,n,a),m1(r[0].elements,e,t,l,a),m){const c=a.out.length;go(m,e,t,n,a,!0),oh(t,m,a,c)}else u||(a.out+=D(n)+`} else { +`,m1(r[1].elements,e,t,l,a)),a.out+=D(n)+`} +`}function Ws(i,e,t,n,a){const s=a.out.length;W3(i,e,t,n,a),oh(t,i,a,s)}function W3(i,e,t,n,a){var m;const s=t.indentPerLevel,r=e==="python",o=(c,d)=>m1(c,e,t,d,a),l=(c,d)=>ni(c,d,i.textLines,e,t,n,a),u=(c=n)=>{t.includeDiagramTextAsComments&&(a.out+=jl(i.textLines,e,c))};switch(i.type){case z.leerElement:a.out+=t.live?El(n,t.live):Vd(n,e);return;case z.anweisung:case z.aufruf:M3(i.textLines,e,t,n,a);return;case z.aussprung:{const c=ja(i.textLines);i.textLines.some(d=>d.trim()!=="")&&u(),r?a.out+=D(n)+(c===""?`break `:`break # ${c} -`):a.out+=Z(n)+(c===""?`break; +`):a.out+=D(n)+(c===""?`break; `:`break; // ${c} `);return}case z.verzweigung:go(i,e,t,n,a,!1);return;case z.fallauswahl:{const c=i.cases;if(!c||c.length===0)return;if(r&&t.pythonWithoutMatch){const d=`wahl${n/s+1}`;ni(d+" = ",` -`,i.textLines,e,t,n,a),c.forEach((h,g)=>{const f=g===c.length-1;f&&g===0?a.out+=Z(n)+"if True:"+M1(h.name,e)+` -`:f?a.out+=Z(n)+"else:"+M1(h.name,e)+` -`:a.out+=Z(n)+(g===0?"if ":"elif ")+d+" == "+Ui(h.name,e)+`: +`,i.textLines,e,t,n,a),c.forEach((h,g)=>{const f=g===c.length-1;f&&g===0?a.out+=D(n)+"if True:"+M1(h.name,e)+` +`:f?a.out+=D(n)+"else:"+M1(h.name,e)+` +`:a.out+=D(n)+(g===0?"if ":"elif ")+d+" == "+Ui(h.name,e)+`: `,o(h.elements,n+s)});return}ni(r?"match ":"switch (",r?`: `:`) { `,i.textLines,e,t,n,a,(m=t.live)==null?void 0:m.labels.selector),c.forEach((d,h)=>{const g=h===c.length-1;if(e==="java"){const f=g?"default -> { "+M1(d.name,e)+` `:"case "+Ui(d.name,e)+` -> { -`;a.out+=Z(n+s)+f,o(d.elements,n+s*2),a.out+=Z(n+s)+`} -`}else if(r){const f=g?"case _:"+M1(d.name,e):"case "+Ui(d.name,e)+":";a.out+=Z(n+s)+f+` -`,o(d.elements,n+s*2)}else{const f=g?"default:"+M1(d.name,e):"case "+Ui(d.name,e)+":";a.out+=Z(n+s)+f+` -`,o(d.elements,n+s*2),a.out+=Z(n+s*2)+`break; -`}}),r||(a.out+=Z(n)+`} -`);return}case z.forSchleife:if(e==="java"){u();const c=t.live?rh(i.textLines,t.live.labels):Dl(i.textLines);a.out+=Z(n)+"for ("+c+`) { -`}else if(r){const c=t.jsIntVariables??new Set,d=S3(i.textLines,c);if((d==null?void 0:d.rangeLine)!==void 0)u(),a.out+=Z(n)+d.rangeLine+` -`;else if(d){u(),a.out+=Z(n)+d.init+` -`,a.out+=Z(n)+"while "+Oe(d.condition,c)+`: -`;for(const h of i.loopBody??[])Ws(h,e,t,n+s,a);a.out+=Z(n+s)+eh(d.increment,c)+` -`;return}else t.live?a.out+=Z(n)+N3(i.textLines,t.live.labels,c)+` +`;a.out+=D(n+s)+f,o(d.elements,n+s*2),a.out+=D(n+s)+`} +`}else if(r){const f=g?"case _:"+M1(d.name,e):"case "+Ui(d.name,e)+":";a.out+=D(n+s)+f+` +`,o(d.elements,n+s*2)}else{const f=g?"default:"+M1(d.name,e):"case "+Ui(d.name,e)+":";a.out+=D(n+s)+f+` +`,o(d.elements,n+s*2),a.out+=D(n+s*2)+`break; +`}}),r||(a.out+=D(n)+`} +`);return}case z.forSchleife:if(e==="java"){u();const c=t.live?rh(i.textLines,t.live.labels):Dl(i.textLines);a.out+=D(n)+"for ("+c+`) { +`}else if(r){const c=t.jsIntVariables??new Set,d=S3(i.textLines,c);if((d==null?void 0:d.rangeLine)!==void 0)u(),a.out+=D(n)+d.rangeLine+` +`;else if(d){u(),a.out+=D(n)+d.init+` +`,a.out+=D(n)+"while "+Oe(d.condition,c)+`: +`;for(const h of i.loopBody??[])Ws(h,e,t,n+s,a);a.out+=D(n+s)+eh(d.increment,c)+` +`;return}else t.live?a.out+=D(n)+N3(i.textLines,t.live.labels,c)+` `:l("for ",`: -`)}else{u();const c=t.live?E3(i.textLines,t.live.labels):I3(i.textLines);a.out+=Z(n)+"for ("+c+`) { -`}o(i.loopBody??[],n+s),r||(a.out+=Z(n)+`} +`)}else{u();const c=t.live?E3(i.textLines,t.live.labels):I3(i.textLines);a.out+=D(n)+"for ("+c+`) { +`}o(i.loopBody??[],n+s),r||(a.out+=D(n)+`} `);return;case z.whileSchleife:l(r?"while ":"while (",r?`: `:`) { -`),o(i.loopBody??[],n+s),r||(a.out+=Z(n)+`} -`);return;case z.doUntilSchleife:{const c=t.live&&Nl(i.textLines)?Vn(t.live.labels.condition):ja(i.textLines);if(r){a.out+=Z(n)+`while True: -`;const d=n+s;o(i.loopBody??[],d),u(d);const h=c.includes(Di)?c:Oe(c,t.jsIntVariables??new Set);a.out+=Z(d)+"if not ("+h+`): -`,a.out+=Z(d+s)+`break -`}else a.out+=Z(n)+`do { -`,o(i.loopBody??[],n+s),u(),a.out+=Z(n)+"} while ("+c+`); -`;return}case z.endlosschleife:{const c=ja(i.textLines),d=c===""||c==="true";d||u(),r?a.out+=Z(n)+(d?`while True: +`),o(i.loopBody??[],n+s),r||(a.out+=D(n)+`} +`);return;case z.doUntilSchleife:{const c=t.live&&Nl(i.textLines)?Qn(t.live.labels.condition):ja(i.textLines);if(r){a.out+=D(n)+`while True: +`;const d=n+s;o(i.loopBody??[],d),u(d);const h=c.includes(Di)?c:Oe(c,t.jsIntVariables??new Set);a.out+=D(d)+"if not ("+h+`): +`,a.out+=D(d+s)+`break +`}else a.out+=D(n)+`do { +`,o(i.loopBody??[],n+s),u(),a.out+=D(n)+"} while ("+c+`); +`;return}case z.endlosschleife:{const c=ja(i.textLines),d=c===""||c==="true";d||u(),r?a.out+=D(n)+(d?`while True: `:`while True: # ${c} -`):a.out+=Z(n)+(d?`while (true) { +`):a.out+=D(n)+(d?`while (true) { `:`while (true) /* ${c} */ { -`),o(i.loopBody??[],n+s),r||(a.out+=Z(n)+`} -`);return}}}const Di="",Wl="",Vn=i=>Di+i+Wl,El=(i,e)=>Z(i)+Vn(e.target==="python"?`pass # ${e.labels.code}`:`// ${e.labels.code}`)+` -`,Nl=i=>i.every(e=>e.trim()==="");function rh(i,e){return Nl(i)||i.length===3?[e.start,e.condition,e.step].map((n,a)=>{const s=nn(i[a]??"");return s===""?Vn(n):s}).join("; "):Dl(i)}function E3(i,e){const t=rh(i,e).split(";"),n=t[0].includes(Di)?void 0:Ud(t[0]);return n!==void 0&&(t[0]=n),t.join(";")}function N3(i,e,t){var h;const[n="",a="",s=""]=i.length===3?i.map(g=>nn(g)):[],r=me(/^\s*(?:integer|int|long|short|byte|double|float)?\s*([a-zA-Z_]\w*)\s*=\s*(.+)$/i,n),o=(r==null?void 0:r[1])??((h=me(/^\s*([a-zA-Z_]\w*)\s*(?:<=|<|>=|>)/,a))==null?void 0:h[1]),l=r?Oe(r[2],t):Vn(e.start),u=me(/^\s*(\w+)\s*(<=|<)\s*(.+)$/,a);let m=Vn(e.end);u&&(o===void 0||u[1]===o)&&(m=Oe(u[3],t),u[2]==="<="&&(m=uo(m,1)));const c=o===void 0?void 0:$d(s,o),d=[l,m,...c!==void 0&&c!==1?[String(c)]:[]];return`for ${o??Vn(e.selector)} in range(${d.join(", ")}):`}function po(i,e=[],t=new Map){return i.forEach((n,a)=>{var r;const s=[...e,a];t.has(n)||t.set(n,s),n.loopBody&&po(n.loopBody,[...s,0],t),(r=n.cases)==null||r.forEach((o,l)=>po(o.elements,[...s,l],t))}),t}function oh(i,e,t,n){const a=i.live,s=a==null?void 0:a.paths.get(e);if(!a||!s||t.out.length===n)return;const r=o=>t.out.slice(0,o).split(` +`),o(i.loopBody??[],n+s),r||(a.out+=D(n)+`} +`);return}}}const Di="",Wl="",Qn=i=>Di+i+Wl,El=(i,e)=>D(i)+Qn(e.target==="python"?`pass # ${e.labels.code}`:`// ${e.labels.code}`)+` +`,Nl=i=>i.every(e=>e.trim()==="");function rh(i,e){return Nl(i)||i.length===3?[e.start,e.condition,e.step].map((n,a)=>{const s=Ft(i[a]??"");return s===""?Qn(n):s}).join("; "):Dl(i)}function E3(i,e){const t=rh(i,e).split(";"),n=t[0].includes(Di)?void 0:Ud(t[0]);return n!==void 0&&(t[0]=n),t.join(";")}function N3(i,e,t){var h;const[n="",a="",s=""]=i.length===3?i.map(g=>Ft(g)):[],r=me(/^\s*(?:integer|int|long|short|byte|double|float)?\s*([a-zA-Z_]\w*)\s*=\s*(.+)$/i,n),o=(r==null?void 0:r[1])??((h=me(/^\s*([a-zA-Z_]\w*)\s*(?:<=|<|>=|>)/,a))==null?void 0:h[1]),l=r?Oe(r[2],t):Qn(e.start),u=me(/^\s*(\w+)\s*(<=|<)\s*(.+)$/,a);let m=Qn(e.end);u&&(o===void 0||u[1]===o)&&(m=Oe(u[3],t),u[2]==="<="&&(m=uo(m,1)));const c=o===void 0?void 0:$d(s,o),d=[l,m,...c!==void 0&&c!==1?[String(c)]:[]];return`for ${o??Qn(e.selector)} in range(${d.join(", ")}):`}function po(i,e=[],t=new Map){return i.forEach((n,a)=>{var r;const s=[...e,a];t.has(n)||t.set(n,s),n.loopBody&&po(n.loopBody,[...s,0],t),(r=n.cases)==null||r.forEach((o,l)=>po(o.elements,[...s,l],t))}),t}function oh(i,e,t,n){const a=i.live,s=a==null?void 0:a.paths.get(e);if(!a||!s||t.out.length===n)return;const r=o=>t.out.slice(0,o).split(` `).length-1;a.spans.push({path:s,from:r(n),to:r(t.out.length-1)})}function lh(i,e,t){const n={target:e,labels:t,paths:po(i.elements),spans:[]},a=Pl(i,e,{includeEmptyElseBranch:!0,live:n}),s=pt(i.caption);let r="";if(e==="java"){const u=Ll(i);for(const m of u)r+=m+` `;as(i)?(u.includes("import java.util.Scanner;")||(r+=`import java.util.Scanner; `),r+=`Scanner scanner = new Scanner(System.in); @@ -190,19 +193,19 @@ ${o.out}${Z(a)}} `),r+=lo([i],"python"),s&&(r+=`def ${s.name}(${u}): `))}const o={out:""};m1(i.elements,e,a,s?a.indentPerLevel:0,o),s&&e!=="python"&&(o.out+=`} `);const l=r.split(` -`).length-1;return{text:uh((r+o.out).replace(/\n+$/,""),e),spans:n.spans.map(u=>({...u,from:u.from+l,to:u.to+l}))}}function uh(i,e){switch(e){case"javascript":return R3(co(i,"javascript")).replace(/\.length\(\)/g,".length").replace(/\.contains\(/g,".includes(");case"python":return F3(co(i,"python")).replace(/\b([a-zA-Z_]\w*(?:\[[^[\]]*\])?)\.length(?:\(\)|\b)/g,"len($1)");case"java":return V3(i)}}function F3(i){for(let e=0;e<5;e++){const t=mh(J3(i),"python");if(t===i)break;i=t}return i}const ru={indexOf:"find",lastIndexOf:"rfind",toUpperCase:"upper",toLowerCase:"lower",trim:"strip",startsWith:"startswith",endsWith:"endswith"};function J3(i){return Fl(i,["charAt","substring","contains","isEmpty","equalsIgnoreCase","compareTo","repeat","concat",...Object.keys(ru)],(e,t,n)=>{switch(t){case"charAt":return`${e}[${n}]`;case"substring":{const a=G3(n);return a.length===2?`${e}[${a[0].trim()}:${a[1].trim()}]`:`${e}[${n.trim()}:]`}case"contains":return`(${n.trim()} in ${e})`;case"isEmpty":return`(len(${e}) == 0)`;case"equalsIgnoreCase":return`(${e}.lower() == ${n.trim()}.lower())`;case"compareTo":return`((${e} > ${n.trim()}) - (${e} < ${n.trim()}))`;case"repeat":return`(${e} * ${n.trim()})`;case"concat":return`(${e} + ${n.trim()})`;default:return`${e}.${ru[t]}(${n})`}})}function R3(i){for(let e=0;e<5;e++){const t=mh(Fl(i,["isEmpty","equalsIgnoreCase","compareTo","replace"],(n,a,s)=>{switch(a){case"isEmpty":return`(${n}.length === 0)`;case"equalsIgnoreCase":return`(${n}.toLowerCase() === ${s.trim()}.toLowerCase())`;case"compareTo":return`${n}.localeCompare(${s.trim()})`;default:return`${n}.replaceAll(${s})`}}),"javascript");if(t===i)break;i=t}return i}function mh(i,e){const t=/\bFiles\.readString\(\s*(?:Path\.of|Paths\.get)\(\s*("(?:[^"\\]|\\.)*")\s*\)\s*\)/g;return e==="python"?i.replace(t,'open($1, encoding="utf-8").read()').replace(/\bInteger\.parseInt\(/g,"int(").replace(/\bDouble\.parseDouble\(/g,"float(").replace(/\bString\.valueOf\(/g,"str("):i.replace(t,'require("fs").readFileSync($1, "utf8")').replace(/\bInteger\.parseInt\(/g,"parseInt(").replace(/\bDouble\.parseDouble\(/g,"parseFloat(").replace(/\bString\.valueOf\(/g,"String(")}function G3(i){let e=0;const t=[...i].findIndex(n=>n==="("?(e+=1,!1):n===")"?(e-=1,!1):n===","&&e===0);return t<0?[i]:[i.slice(0,t),i.slice(t+1)]}function Fl(i,e,t){const n=new RegExp(`([A-Za-z_]\\w*(?:\\[[^[\\]]*\\]|\\.\\w+\\(\\))*|"(?:[^"\\\\]|\\\\.)*")\\.(${e.join("|")})\\(`,"g");let a="",s=0;for(let r=n.exec(i);r;r=n.exec(i)){const o=r.index+r[0].length-1;let l=0,u=-1;for(let c=o;ce.has(n.toLowerCase())?t:`${n}.length()`)}const Q3=new Set("abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while true false null var record sealed permits yield module open opens requires exports to uses provides with transitive".split(" "));function Es(i){const e=i.trim();if(e==="")return"Main";let t="";return Array.from(e).forEach((n,a)=>{a===0?new RegExp("\\p{L}","u").test(n)||n==="_"||n==="$"?t+=n:new RegExp("\\p{Nd}","u").test(n)?t+="_"+n:t+="_":/[\p{L}\p{M}\p{N}]/u.test(n)||n==="_"||n==="$"?t+=n:t+="_"}),t=t.replace(/_{2,}/g,"_").replace(/^_+|_+$/g,""),t===""?"Main":(new RegExp("^\\p{Nd}","u").test(t)&&(t="_"+t),Q3.has(t.toLowerCase())&&(t="_"+t),t)}function ou(i,e,t={},n=[]){const a={...Gd,...t},s=Es(e),r=[i,...n].filter((k,I,T)=>T.indexOf(k)===I).map(k=>({d:k,header:pt(k.caption)})).filter(k=>k.header!==void 0),o=r.map(k=>ro(k.d,k.header,"java",t,a.indentPerLevel)),l=pt(i.caption),u=r.some(k=>as(k.d)),m=ts(i,"java",a),c=a.indentPerLevel*2,d=as(i),h=d?q3(m):m,g=Z(c),f=h.trim()===""?"":h.split(` +`).length-1;return{text:uh((r+o.out).replace(/\n+$/,""),e),spans:n.spans.map(u=>({...u,from:u.from+l,to:u.to+l}))}}function uh(i,e){switch(e){case"javascript":return R3(co(i,"javascript")).replace(/\.length\(\)/g,".length").replace(/\.contains\(/g,".includes(");case"python":return F3(co(i,"python")).replace(/\b([a-zA-Z_]\w*(?:\[[^[\]]*\])?)\.length(?:\(\)|\b)/g,"len($1)");case"java":return V3(i)}}function F3(i){for(let e=0;e<5;e++){const t=mh(J3(i),"python");if(t===i)break;i=t}return i}const ru={indexOf:"find",lastIndexOf:"rfind",toUpperCase:"upper",toLowerCase:"lower",trim:"strip",startsWith:"startswith",endsWith:"endswith"};function J3(i){return Fl(i,["charAt","substring","contains","isEmpty","equalsIgnoreCase","compareTo","repeat","concat",...Object.keys(ru)],(e,t,n)=>{switch(t){case"charAt":return`${e}[${n}]`;case"substring":{const a=G3(n);return a.length===2?`${e}[${a[0].trim()}:${a[1].trim()}]`:`${e}[${n.trim()}:]`}case"contains":return`(${n.trim()} in ${e})`;case"isEmpty":return`(len(${e}) == 0)`;case"equalsIgnoreCase":return`(${e}.lower() == ${n.trim()}.lower())`;case"compareTo":return`((${e} > ${n.trim()}) - (${e} < ${n.trim()}))`;case"repeat":return`(${e} * ${n.trim()})`;case"concat":return`(${e} + ${n.trim()})`;default:return`${e}.${ru[t]}(${n})`}})}function R3(i){for(let e=0;e<5;e++){const t=mh(Fl(i,["isEmpty","equalsIgnoreCase","compareTo","replace"],(n,a,s)=>{switch(a){case"isEmpty":return`(${n}.length === 0)`;case"equalsIgnoreCase":return`(${n}.toLowerCase() === ${s.trim()}.toLowerCase())`;case"compareTo":return`${n}.localeCompare(${s.trim()})`;default:return`${n}.replaceAll(${s})`}}),"javascript");if(t===i)break;i=t}return i}function mh(i,e){const t=/\bFiles\.readString\(\s*(?:Path\.of|Paths\.get)\(\s*("(?:[^"\\]|\\.)*")\s*\)\s*\)/g;return e==="python"?i.replace(t,'open($1, encoding="utf-8").read()').replace(/\bInteger\.parseInt\(/g,"int(").replace(/\bDouble\.parseDouble\(/g,"float(").replace(/\bString\.valueOf\(/g,"str("):i.replace(t,'require("fs").readFileSync($1, "utf8")').replace(/\bInteger\.parseInt\(/g,"parseInt(").replace(/\bDouble\.parseDouble\(/g,"parseFloat(").replace(/\bString\.valueOf\(/g,"String(")}function G3(i){let e=0;const t=[...i].findIndex(n=>n==="("?(e+=1,!1):n===")"?(e-=1,!1):n===","&&e===0);return t<0?[i]:[i.slice(0,t),i.slice(t+1)]}function Fl(i,e,t){const n=new RegExp(`([A-Za-z_]\\w*(?:\\[[^[\\]]*\\]|\\.\\w+\\(\\))*|"(?:[^"\\\\]|\\\\.)*")\\.(${e.join("|")})\\(`,"g");let a="",s=0;for(let r=n.exec(i);r;r=n.exec(i)){const o=r.index+r[0].length-1;let l=0,u=-1;for(let c=o;ce.has(n.toLowerCase())?t:`${n}.length()`)}const Q3=new Set("abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while true false null var record sealed permits yield module open opens requires exports to uses provides with transitive".split(" "));function Es(i){const e=i.trim();if(e==="")return"Main";let t="";return Array.from(e).forEach((n,a)=>{a===0?new RegExp("\\p{L}","u").test(n)||n==="_"||n==="$"?t+=n:new RegExp("\\p{Nd}","u").test(n)?t+="_"+n:t+="_":/[\p{L}\p{M}\p{N}]/u.test(n)||n==="_"||n==="$"?t+=n:t+="_"}),t=t.replace(/_{2,}/g,"_").replace(/^_+|_+$/g,""),t===""?"Main":(new RegExp("^\\p{Nd}","u").test(t)&&(t="_"+t),Q3.has(t.toLowerCase())&&(t="_"+t),t)}function ou(i,e,t={},n=[]){const a={...Gd,...t},s=Es(e),r=[i,...n].filter((k,I,T)=>T.indexOf(k)===I).map(k=>({d:k,header:pt(k.caption)})).filter(k=>k.header!==void 0),o=r.map(k=>ro(k.d,k.header,"java",t,a.indentPerLevel)),l=pt(i.caption),u=r.some(k=>as(k.d)),m=ts(i,"java",a),c=a.indentPerLevel*2,d=as(i),h=d?q3(m):m,g=D(c),f=h.trim()===""?"":h.split(` `).map(k=>k.trim()===""?g:g+k).join(` `);let x="";const b=o.length>0&&(d||u),v=[...new Set([i,...r.map(k=>k.d)].flatMap(Ll))],w=v.length>0;(d||u)&&!v.includes("import java.util.Scanner;")&&v.push("import java.util.Scanner;");for(const k of v)x+=k+` `;v.length&&(x+=` `),x+=`public class ${s} { -`,b&&(x+=Z(a.indentPerLevel)+`static Scanner scanner = new Scanner(System.in); +`,b&&(x+=D(a.indentPerLevel)+`static Scanner scanner = new Scanner(System.in); -`),l||(x+=Z(a.indentPerLevel)+`public static void main(String[] args)${w?" throws Exception":""} { -`,d&&!b&&(x+=Z(c)+`Scanner scanner = new Scanner(System.in); +`),l||(x+=D(a.indentPerLevel)+`public static void main(String[] args)${w?" throws Exception":""} { +`,d&&!b&&(x+=D(c)+`Scanner scanner = new Scanner(System.in); `,f!==""&&(x+=` `)),x+=f,f!==""&&!f.endsWith(` `)&&(x+=` -`),x+=Z(a.indentPerLevel)+`} +`),x+=D(a.indentPerLevel)+`} `);for(const[k,I]of o.entries())x+=(k>0||!l?` `:"")+I;return x+=`} `,x}function q3(i){const e=i.split(` @@ -210,20 +213,33 @@ ${o.out}${Z(a)}} `)}const pn={target:"visustruct.codegen.target",javaMode:"visustruct.codegen.javaOutputMode",comments:"visustruct.codegen.includeDiagramComments",emptyElse:"visustruct.codegen.includeEmptyElse"};function $i(i){try{return localStorage.getItem(i)}catch{return null}}function Yi(i,e){try{localStorage.setItem(i,e)}catch{}}const U3=()=>p("web_run_stopped_loop"),ch=()=>p("web_run_cancelled"),Ce=i=>i.replace(/&/g,"&").replace(//g,">").replace(/"/g,""");function $3(i){let e=0;return i.replace(/^(\s*)while\s*\(\s*true\s*\)(?:\s*\/\*.*?\*\/)?\s*\{/gm,(t,n)=>{const a=`__visuStructLoopGuard${e++}`;return`${n}for (let ${a} = 0; ${a} < 100000 || (() => { throw new Error(${JSON.stringify(U3())}); })(); ${a}++) {`})}function Y3(i){return $3(i).replace(/\bprompt\s*\(/g,"await __visuStructPrompt(")}const X3=` let answer let lines = [] -const flush = () => { +// Text von \`process.stdout.write\` ohne neue Zeile (wie \`System.out.print\`). +let partial = '' +const flush = (all) => { + if (all && partial) { + lines.push(partial) + partial = '' + } if (lines.length) postMessage({ type: 'log', lines }) lines = [] } const send = (type, text) => { - flush() + flush(true) postMessage({ type, text }) } const fmt = (a) => (typeof a === 'string' ? a : JSON.stringify(a)) // Ausgaben gesammelt senden, sonst bremsen viele kleine Nachrichten (z. B. in Endlosschleifen) die Seite aus. console.log = (...args) => { - lines.push(args.map(fmt).join(' ')) + lines.push(partial + args.map(fmt).join(' ')) + partial = '' if (lines.length >= 500) flush() } +const process = { stdout: { write: (text) => { + const parts = (partial + String(text)).split('\\n') + partial = parts.pop() + lines.push(...parts) + if (lines.length >= 500) flush() +} } } setInterval(flush, 50) const __visuStructPrompt = (label) => new Promise((resolve, reject) => { answer = (value) => (value === null ? reject(new Error(${JSON.stringify(ch())})) : resolve(value)) @@ -272,8 +288,8 @@ onmessage = async (e) => { `;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,Yi(pn.target,this.target),this.refresh()});for(const a of this.element.querySelectorAll("[data-java-mode]"))a.addEventListener("click",()=>{this.javaMode=a.dataset.javaMode,Yi(pn.javaMode,this.javaMode),this.refresh()});const t=e("[data-opt=comments]");t.checked=this.comments,t.addEventListener("change",()=>{this.comments=t.checked,Yi(pn.comments,String(this.comments)),this.refresh()});const n=e("[data-opt=emptyElse]");n.checked=this.emptyElse,n.addEventListener("change",()=>{this.emptyElse=n.checked,Yi(pn.emptyElse,String(this.emptyElse)),this.refresh()}),this.copyButton.addEventListener("click",()=>this.copy()),this.saveButton.addEventListener("click",()=>{const a=Es(this.classStem()),s=ou(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=Y3(this.code),t=n=>this.onRunnerMessage(n);try{const n=URL.createObjectURL(new Blob([X3],{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(ch())):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 _e=(i,e=!1)=>``,ee={newFile:_e(''),open:_e(''),save:_e(''),undo:_e(''),redo:_e(''),cut:_e(''),copy:_e(''),paste:_e(''),trash:_e(''),share:_e(''),book:_e(''),code:_e(''),play:_e('',!0),step:_e(''),indent:_e(''),stop:_e('',!0),folder:_e(''),newFolder:_e(''),diagram:_e(''),fileText:_e('')},ex="visustruct.learn.progress",lr={"04-sequenz":"05-sequenz","05-variablen-und-datentypen":"04-variablen-und-datentypen","07-verzweigung":"08-verzweigung","08-bedingungen-verknuepfen":"09-bedingungen-verknuepfen","09-fallauswahl":"10-fallauswahl","10-while-schleife":"11-while-schleife","11-do-while-schleife":"12-do-while-schleife","12-for-schleife":"13-for-schleife","13-verschachteln":"14-verschachteln","14-arrays":"15-arrays","15-aufruf-und-aussprung":"18-aufruf-und-aussprung","16-aufruf-und-aussprung":"18-aufruf-und-aussprung","17-aufruf-und-aussprung":"18-aufruf-und-aussprung","17-suchen-und-sortieren":"19-suchen-und-sortieren","18-suchen-und-sortieren":"19-suchen-und-sortieren","16-simulation-und-schreibtischtest":"07-simulation-und-schreibtischtest","17-java":"20-java","18-java":"20-java","19-java":"20-java","18-python-und-javascript":"21-python-und-javascript","19-python-und-javascript":"21-python-und-javascript","20-python-und-javascript":"21-python-und-javascript","22-erstes-fenster":"28-erstes-fenster","23-knopf-im-fenster":"29-knopf-im-fenster","24-der-knopf-reagiert":"30-der-knopf-reagiert","23-erstes-fenster":"28-erstes-fenster","24-knopf-im-fenster":"29-knopf-im-fenster","25-der-knopf-reagiert":"30-der-knopf-reagiert","26-zahl-verdoppeln":"31-zahl-verdoppeln","27-klickzaehler":"32-klickzaehler","28-ampel":"33-ampel","29-notenrechner":"34-notenrechner","30-taschenrechner":"35-taschenrechner","31-zahlenraten":"36-zahlenraten","13-lautsprecher":"16-lautsprecher","14-bildschirm":"18-bildschirm","15-motoren":"20-motoren","16-stoppuhr-akku":"21-stoppuhr-akku","03-sensoren":"04-sensoren","04-bis-zur-wand":"05-bis-zur-wand","05-abstand":"06-abstand","06-linie":"07-linie","07-farben":"08-farben","08-tasten-joystick":"10-tasten-joystick","09-licht":"11-licht","10-lautstaerke":"12-lautstaerke","11-neigung":"13-neigung","12-leds":"14-leds","13-einzelne-leds":"15-einzelne-leds","14-lautsprecher":"16-lautsprecher","15-bildschirm":"18-bildschirm","16-motoren":"20-motoren","17-stoppuhr-akku":"21-stoppuhr-akku"};function tx(i){var n;const e={...i.lessons};for(const[a,s]of Object.entries(lr))i.lessons[a]&&!i.lessons[s]&&(e[s]=i.lessons[a]),i.lessons[a]&&delete e[a];const t=(n=i.view)!=null&&n.lesson&&lr[i.view.lesson]?{...i.view,lesson:lr[i.view.lesson]}:i.view;return{...i,lessons:e,view:t}}function nx(){try{localStorage.removeItem(ex)}catch{}}const dh=()=>({lessons:{},exercises:{}});nx();let He=dh();const fo=new Set;function Xi(){for(const i of fo)i()}const lu="visustruct-lernstand";function hh(i,e){return i||e||void 0}function ix(i,e){if(!i)return e;const t={...e.checks};for(const[n,a]of Object.entries(i.checks??{}))t[n]=a||!!t[n];return{step:Math.max(i.step??0,e.step??0),done:hh(i.done,e.done),checks:Object.keys(t).length?t:void 0,quiz:i.quiz||e.quiz?{...e.quiz,...i.quiz}:void 0}}function ax(i,e){const t={...i.lessons};for(const[a,s]of Object.entries(e.lessons))t[a]=ix(i.lessons[a],s);const n={...i.exercises};for(const[a,s]of Object.entries(e.exercises)){const r=i.exercises[a];n[a]=r?{done:hh(r.done,s.done),xml:r.xml??s.xml}:s}return{lessons:t,exercises:n}}const ce={lesson(i){return He.lessons[i]??{step:0}},updateLesson(i,e){He.lessons[i]={...ce.lesson(i),...e},Xi()},exercise(i){return He.exercises[i]??{}},updateExercise(i,e){He.exercises[i]={...ce.exercise(i),...e},Xi()},resetExercise(i){delete He.exercises[i],Xi()},view(){return He.view},hasContent(){return Object.values(He.lessons).some(i=>i.step>0||i.done||i.checks||i.quiz)||Object.keys(He.exercises).length>0},setView(i){He.view=i,Xi()},onChange(i){return fo.add(i),()=>fo.delete(i)},toFile(){return JSON.stringify({format:lu,version:1,saved:new Date().toISOString(),lessons:He.lessons,exercises:He.exercises,view:He.view},null,2)},loadFile(i,e=!1){let t;try{t=JSON.parse(i)}catch{return!1}if((t==null?void 0:t.format)!==lu)return!1;const n=tx({lessons:t.lessons??{},exercises:t.exercises??{},view:t.view});return He=e?{...ax(He,n),view:n.view??He.view}:n,!0},clear(){He=dh()}};function uu(i=new Date){const e=t=>String(t).padStart(2,"0");return`${i.getFullYear()}-${e(i.getMonth()+1)}-${e(i.getDate())}`}const mu=i=>/^\d{4}-\d{2}-\d{2}$/.test(i);function sx(i,e){return i.kind!==e.kind?i.kind==="directory"?-1:1:mu(i.name)&&mu(e.name)?e.name.localeCompare(i.name):i.name.localeCompare(e.name,void 0,{numeric:!0,sensitivity:"base"})}function rx(i,e){return i.replace(/\.(visustruct|strk|java)$/i,"").replace(/[\\/:*?"<>|\u0000-\u001f]/g,"-").replace(/\s+/g," ").trim().replace(/^\.+/,"")||e}function ox(i,e){const t=new Set([...e].map(a=>a.toLowerCase())),n=a=>!t.has(`${a}.visustruct`.toLowerCase())&&!t.has(`${a}.java`.toLowerCase());if(n(i))return i;for(let a=2;;a++)if(n(`${i} ${a}`))return`${i} ${a}`}function lx(i){const e=i.replace(/[\\/:*?"<>|\u0000-\u001f]/g,"").trim();return e&&e!=="."&&e!==".."?e:void 0}const Fn=10;function ux(i){let e=i.replace(/\r/g,"").split(` -`).filter(m=>!m.startsWith("//"));const t=e.filter(m=>/^linie:/.test(m)).map(m=>m.slice(6).trim());e=e.filter(m=>!/^linie:/.test(m));const n=e.findIndex(m=>/^raster:\s*\d+\s*$/.test(m));if(n>=0){const m=Number(e[n].split(":")[1]);e.splice(n,1),e=e.flatMap(c=>Array.from({length:m},(d,h)=>Array.from(c).map(g=>Array.from({length:m},(f,x)=>"^>v<".includes(g)?h===m>>1&&x===m>>1?g:".":g).join("")).join("")))}for(;e.length&&e[e.length-1].trim()==="";)e.pop();for(;e.length&&e[0].trim()==="";)e.shift();const s=Math.max(...e.map(m=>m.length))*Fn,r=e.length*Fn,o=(m,c)=>({x:-s/2+(m+.5)*Fn,y:r/2-(c+.5)*Fn}),l={width:s,depth:r,start:{x:0,y:0,heading:0},walls:[],lines:[],blocks:[],marks:[],goals:[],targets:[],colors:[]};let u=0;e.forEach((m,c)=>{Array.from(m).forEach((d,h)=>{const g=o(h,c);d==="#"?l.blocks.push(g):d==="="?l.marks.push(g):d==="Z"?l.goals.push(g):d==="o"?l.targets.push(g):d in cu?l.colors.push({at:g,color:cu[d]}):"^>v<".includes(d)&&(u++,l.start={...g,heading:{"^":0,">":90,v:180,"<":270}[d]})})});for(const m of t)l.lines.push(m.split(/\s+/).map(c=>{const[d,h]=c.split(",").map(Number);if(!Number.isFinite(d)||!Number.isFinite(h))throw new Error(`Linie: „${c}“ ist kein Feld (Spalte,Zeile).`);return o(d,h)}));if(u!==1)throw new Error(`Die Weltkarte braucht genau einen Start (^ > v <), gefunden: ${u}`);return l}const cu={r:"red",g:"green",b:"blue",y:"yellow"},L1=(i,e)=>Math.abs(i.x-e.x)<=Fn/2&&Math.abs(i.y-e.y)<=Fn/2,du=10,hu=9,mx=300,a1=8,cx=[-3.6,-1.2,1.2,3.6],dx=2.5,hx=20,gx=12,Jl=100,bi={width:200,depth:200,start:{x:0,y:0,heading:0},walls:[],lines:[]},gu=i=>i*Math.PI/180,s1=i=>({x:Math.sin(gu(i)),y:Math.cos(gu(i))}),Ki=()=>Array.from({length:Dd},()=>{}),pu=([i,e,t])=>i>0||e>0||t>0?[i,e,t]:void 0;class ss{constructor(e=bi){y(this,"pose");y(this,"trail");y(this,"bumps",0);y(this,"leds",Ki());y(this,"screen");y(this,"wheels",[0,0]);y(this,"time",0);y(this,"timerStart",0);y(this,"blocked",!1);y(this,"blockWallCache");this.setup=e,this.pose={...e.start},this.trail=[{x:e.start.x,y:e.start.y}]}reset(){this.pose={...this.setup.start},this.trail=[{x:this.pose.x,y:this.pose.y}],this.bumps=0,this.leds=Ki(),this.screen=void 0,this.wheels=[0,0],this.time=0,this.timerStart=0,this.blocked=!1}get allWalls(){const e=this.setup.width/2,t=this.setup.depth/2,n=[{x:-e,y:-t},{x:e,y:-t},{x:e,y:t},{x:-e,y:t}];return[...this.setup.walls,...n.map((a,s)=>({from:a,to:n[(s+1)%4]})),...this.blockWalls]}get blockWalls(){return this.blockWallCache??(this.blockWallCache=(this.setup.blocks??[]).flatMap(e=>{const t=Fn/2,n=[{x:e.x-t,y:e.y-t},{x:e.x+t,y:e.y-t},{x:e.x+t,y:e.y+t},{x:e.x-t,y:e.y+t}];return n.map((a,s)=>({from:a,to:n[(s+1)%4]}))})),this.blockWallCache}atGoal(){const e=s1(this.pose.heading),t={x:this.pose.x+e.x*a1,y:this.pose.y+e.y*a1};return(this.setup.goals??[]).some(n=>L1(this.pose,n)||L1(t,n))||(this.setup.targets??[]).some(n=>L1(this.pose,n))}apply(e){switch(e.method){case"forward":return this.wheels=[0,0],this.drive(e.args[0]);case"backward":return this.wheels=[0,0],this.drive(-e.args[0]);case"turnRight":return this.wheels=[0,0],this.turn(e.args[0]);case"turnLeft":return this.wheels=[0,0],this.turn(-e.args[0]);case"stop":this.wheels=[0,0];return;case"drive":this.wheels=[fu(e.args[0]),fu(e.args[1])];return;case"pause":return this.tick(e.args[0]);case"resetTimer":this.timerStart=this.time;return;case"setLed":this.leds=Ki().map(()=>pu(e.args));return;case"ledOff":this.leds=Ki();return;case"ledColor":this.leds[e.args[0]]=pu(qa[e.text??""]??[0,0,0]);return;case"showText":this.screen=e.text;return}}tick(e){if(e<=0)return;this.time+=e;const[t,n]=this.wheels.map(o=>o/100*hx);if(t===0&&n===0)return;const a=Math.ceil(e/10),s=e/1e3/a;let r=!1;for(let o=0;o{const r={x:this.pose.x+e.x*a1+t.x*a,y:this.pose.y+e.y*a1+t.y*a};([...this.setup.marks??[],...this.setup.goals??[]].some(l=>L1(r,l))||this.setup.lines.some(l=>fx(r,l)<=dx/2))&&(n|=1<<3-s)}),n}colorUnder(){var n;const e=s1(this.pose.heading),t={x:this.pose.x+e.x*a1,y:this.pose.y+e.y*a1};return(n=(this.setup.colors??[]).find(a=>L1(t,a.at)))==null?void 0:n.color}sensors(){const e=this.lineState();return{getDistance:this.distance(),getLine:e,getColor:this.colorUnder()??(e&6?"black":"white"),isLineLeft:(e&4)!==0,isLineRight:(e&2)!==0,getTimer:this.timer}}freeDistance(e,t){let n=1/0;for(const a of this.allWalls){const s=px(e,t,a.from,a.to);s!==void 0&&sMath.max(-100,Math.min(100,i));function xu(i){const e=(i%360+360)%360;return Math.abs(e-360)<1e-9?0:e}function px(i,e,t,n){const a={x:n.x-t.x,y:n.y-t.y},s=e.x*a.y-e.y*a.x;if(Math.abs(s)<1e-12)return;const r={x:t.x-i.x,y:t.y-i.y},o=(r.x*a.y-r.y*a.x)/s,l=(r.x*e.y-r.y*e.x)/s;return o>=0&&l>=0&&l<=1?o:void 0}function fx(i,e){let t=1/0;for(let n=0;n+10&&o.tick(Jl),s.robotSensors={...o.sensors(),...zx(a,u)};const c=()=>({outputs:[...m.outputLines],files:new Map(m.files),drive:m.robotActions.length?$a(m.robotActions):void 0,...n?{atGoal:o.atGoal(),bumps:o.bumps}:{},led:o.leds.some(d=>d!==void 0),tone:m.robotActions.some(d=>d.method==="playTone"),screen:o.screen,actions:Md(m.robotActions.filter(d=>!yx.has(d.method)))});if(m.inputRequest){const d=r.shift();if(d===void 0)return{...c(),missingInput:!0};if(s.provideInput(d),m.inputErrorNotice)return{...c(),error:m.inputErrorNotice};continue}if(m.isHalted)return{...c(),error:m.notice};if(!s.canStep)return{...c(),unusedInputs:r.length||void 0};s.step()}return{outputs:[...s.state.outputLines],files:new Map(s.state.files),drive:$a(s.state.robotActions),tooManySteps:!0}}function zx(i,e){const t=Math.floor(e/bx);return Object.fromEntries(Object.entries(i??{}).map(([n,a])=>[n,a[Math.min(t,a.length-1)]]))}function gh(i){return i===void 0||i===""?[]:i.replace(/\n$/,"").split(` +`:""),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 _e=(i,e=!1)=>``,ee={newFile:_e(''),open:_e(''),save:_e(''),undo:_e(''),redo:_e(''),cut:_e(''),copy:_e(''),paste:_e(''),trash:_e(''),share:_e(''),book:_e(''),code:_e(''),play:_e('',!0),step:_e(''),indent:_e(''),stop:_e('',!0),folder:_e(''),newFolder:_e(''),diagram:_e(''),fileText:_e('')},ex="visustruct.learn.progress",lr={"04-sequenz":"05-sequenz","05-variablen-und-datentypen":"04-variablen-und-datentypen","07-verzweigung":"08-verzweigung","08-bedingungen-verknuepfen":"09-bedingungen-verknuepfen","09-fallauswahl":"10-fallauswahl","10-while-schleife":"11-while-schleife","11-do-while-schleife":"12-do-while-schleife","12-for-schleife":"13-for-schleife","13-verschachteln":"14-verschachteln","14-arrays":"15-arrays","15-aufruf-und-aussprung":"18-aufruf-und-aussprung","16-aufruf-und-aussprung":"18-aufruf-und-aussprung","17-aufruf-und-aussprung":"18-aufruf-und-aussprung","17-suchen-und-sortieren":"19-suchen-und-sortieren","18-suchen-und-sortieren":"19-suchen-und-sortieren","16-simulation-und-schreibtischtest":"07-simulation-und-schreibtischtest","17-java":"20-java","18-java":"20-java","19-java":"20-java","18-python-und-javascript":"21-python-und-javascript","19-python-und-javascript":"21-python-und-javascript","20-python-und-javascript":"21-python-und-javascript","22-erstes-fenster":"28-erstes-fenster","23-knopf-im-fenster":"29-knopf-im-fenster","24-der-knopf-reagiert":"30-der-knopf-reagiert","23-erstes-fenster":"28-erstes-fenster","24-knopf-im-fenster":"29-knopf-im-fenster","25-der-knopf-reagiert":"30-der-knopf-reagiert","26-zahl-verdoppeln":"31-zahl-verdoppeln","27-klickzaehler":"32-klickzaehler","28-ampel":"33-ampel","29-notenrechner":"34-notenrechner","30-taschenrechner":"35-taschenrechner","31-zahlenraten":"36-zahlenraten","13-lautsprecher":"16-lautsprecher","14-bildschirm":"18-bildschirm","15-motoren":"20-motoren","16-stoppuhr-akku":"21-stoppuhr-akku","03-sensoren":"04-sensoren","04-bis-zur-wand":"05-bis-zur-wand","05-abstand":"06-abstand","06-linie":"07-linie","07-farben":"08-farben","08-tasten-joystick":"10-tasten-joystick","09-licht":"11-licht","10-lautstaerke":"12-lautstaerke","11-neigung":"13-neigung","12-leds":"14-leds","13-einzelne-leds":"15-einzelne-leds","14-lautsprecher":"16-lautsprecher","15-bildschirm":"18-bildschirm","16-motoren":"20-motoren","17-stoppuhr-akku":"21-stoppuhr-akku"};function tx(i){var n;const e={...i.lessons};for(const[a,s]of Object.entries(lr))i.lessons[a]&&!i.lessons[s]&&(e[s]=i.lessons[a]),i.lessons[a]&&delete e[a];const t=(n=i.view)!=null&&n.lesson&&lr[i.view.lesson]?{...i.view,lesson:lr[i.view.lesson]}:i.view;return{...i,lessons:e,view:t}}function nx(){try{localStorage.removeItem(ex)}catch{}}const dh=()=>({lessons:{},exercises:{}});nx();let He=dh();const fo=new Set;function Xi(){for(const i of fo)i()}const lu="visustruct-lernstand";function hh(i,e){return i||e||void 0}function ix(i,e){if(!i)return e;const t={...e.checks};for(const[n,a]of Object.entries(i.checks??{}))t[n]=a||!!t[n];return{step:Math.max(i.step??0,e.step??0),done:hh(i.done,e.done),checks:Object.keys(t).length?t:void 0,quiz:i.quiz||e.quiz?{...e.quiz,...i.quiz}:void 0}}function ax(i,e){const t={...i.lessons};for(const[a,s]of Object.entries(e.lessons))t[a]=ix(i.lessons[a],s);const n={...i.exercises};for(const[a,s]of Object.entries(e.exercises)){const r=i.exercises[a];n[a]=r?{done:hh(r.done,s.done),xml:r.xml??s.xml}:s}return{lessons:t,exercises:n}}const ce={lesson(i){return He.lessons[i]??{step:0}},updateLesson(i,e){He.lessons[i]={...ce.lesson(i),...e},Xi()},exercise(i){return He.exercises[i]??{}},updateExercise(i,e){He.exercises[i]={...ce.exercise(i),...e},Xi()},resetExercise(i){delete He.exercises[i],Xi()},view(){return He.view},hasContent(){return Object.values(He.lessons).some(i=>i.step>0||i.done||i.checks||i.quiz)||Object.keys(He.exercises).length>0},setView(i){He.view=i,Xi()},onChange(i){return fo.add(i),()=>fo.delete(i)},toFile(){return JSON.stringify({format:lu,version:1,saved:new Date().toISOString(),lessons:He.lessons,exercises:He.exercises,view:He.view},null,2)},loadFile(i,e=!1){let t;try{t=JSON.parse(i)}catch{return!1}if((t==null?void 0:t.format)!==lu)return!1;const n=tx({lessons:t.lessons??{},exercises:t.exercises??{},view:t.view});return He=e?{...ax(He,n),view:n.view??He.view}:n,!0},clear(){He=dh()}};function uu(i=new Date){const e=t=>String(t).padStart(2,"0");return`${i.getFullYear()}-${e(i.getMonth()+1)}-${e(i.getDate())}`}const mu=i=>/^\d{4}-\d{2}-\d{2}$/.test(i);function sx(i,e){return i.kind!==e.kind?i.kind==="directory"?-1:1:mu(i.name)&&mu(e.name)?e.name.localeCompare(i.name):i.name.localeCompare(e.name,void 0,{numeric:!0,sensitivity:"base"})}function rx(i,e){return i.replace(/\.(visustruct|strk|java)$/i,"").replace(/[\\/:*?"<>|\u0000-\u001f]/g,"-").replace(/\s+/g," ").trim().replace(/^\.+/,"")||e}function ox(i,e){const t=new Set([...e].map(a=>a.toLowerCase())),n=a=>!t.has(`${a}.visustruct`.toLowerCase())&&!t.has(`${a}.java`.toLowerCase());if(n(i))return i;for(let a=2;;a++)if(n(`${i} ${a}`))return`${i} ${a}`}function lx(i){const e=i.replace(/[\\/:*?"<>|\u0000-\u001f]/g,"").trim();return e&&e!=="."&&e!==".."?e:void 0}const Jn=10;function ux(i){let e=i.replace(/\r/g,"").split(` +`).filter(m=>!m.startsWith("//"));const t=e.filter(m=>/^linie:/.test(m)).map(m=>m.slice(6).trim());e=e.filter(m=>!/^linie:/.test(m));const n=e.findIndex(m=>/^raster:\s*\d+\s*$/.test(m));if(n>=0){const m=Number(e[n].split(":")[1]);e.splice(n,1),e=e.flatMap(c=>Array.from({length:m},(d,h)=>Array.from(c).map(g=>Array.from({length:m},(f,x)=>"^>v<".includes(g)?h===m>>1&&x===m>>1?g:".":g).join("")).join("")))}for(;e.length&&e[e.length-1].trim()==="";)e.pop();for(;e.length&&e[0].trim()==="";)e.shift();const s=Math.max(...e.map(m=>m.length))*Jn,r=e.length*Jn,o=(m,c)=>({x:-s/2+(m+.5)*Jn,y:r/2-(c+.5)*Jn}),l={width:s,depth:r,start:{x:0,y:0,heading:0},walls:[],lines:[],blocks:[],marks:[],goals:[],targets:[],colors:[]};let u=0;e.forEach((m,c)=>{Array.from(m).forEach((d,h)=>{const g=o(h,c);d==="#"?l.blocks.push(g):d==="="?l.marks.push(g):d==="Z"?l.goals.push(g):d==="o"?l.targets.push(g):d in cu?l.colors.push({at:g,color:cu[d]}):"^>v<".includes(d)&&(u++,l.start={...g,heading:{"^":0,">":90,v:180,"<":270}[d]})})});for(const m of t)l.lines.push(m.split(/\s+/).map(c=>{const[d,h]=c.split(",").map(Number);if(!Number.isFinite(d)||!Number.isFinite(h))throw new Error(`Linie: „${c}“ ist kein Feld (Spalte,Zeile).`);return o(d,h)}));if(u!==1)throw new Error(`Die Weltkarte braucht genau einen Start (^ > v <), gefunden: ${u}`);return l}const cu={r:"red",g:"green",b:"blue",y:"yellow"},L1=(i,e)=>Math.abs(i.x-e.x)<=Jn/2&&Math.abs(i.y-e.y)<=Jn/2,du=10,hu=9,mx=300,a1=8,cx=[-3.6,-1.2,1.2,3.6],dx=2.5,hx=20,gx=12,Jl=100,bi={width:200,depth:200,start:{x:0,y:0,heading:0},walls:[],lines:[]},gu=i=>i*Math.PI/180,s1=i=>({x:Math.sin(gu(i)),y:Math.cos(gu(i))}),Ki=()=>Array.from({length:Dd},()=>{}),pu=([i,e,t])=>i>0||e>0||t>0?[i,e,t]:void 0;class ss{constructor(e=bi){y(this,"pose");y(this,"trail");y(this,"bumps",0);y(this,"leds",Ki());y(this,"screen");y(this,"wheels",[0,0]);y(this,"time",0);y(this,"timerStart",0);y(this,"blocked",!1);y(this,"blockWallCache");this.setup=e,this.pose={...e.start},this.trail=[{x:e.start.x,y:e.start.y}]}reset(){this.pose={...this.setup.start},this.trail=[{x:this.pose.x,y:this.pose.y}],this.bumps=0,this.leds=Ki(),this.screen=void 0,this.wheels=[0,0],this.time=0,this.timerStart=0,this.blocked=!1}get allWalls(){const e=this.setup.width/2,t=this.setup.depth/2,n=[{x:-e,y:-t},{x:e,y:-t},{x:e,y:t},{x:-e,y:t}];return[...this.setup.walls,...n.map((a,s)=>({from:a,to:n[(s+1)%4]})),...this.blockWalls]}get blockWalls(){return this.blockWallCache??(this.blockWallCache=(this.setup.blocks??[]).flatMap(e=>{const t=Jn/2,n=[{x:e.x-t,y:e.y-t},{x:e.x+t,y:e.y-t},{x:e.x+t,y:e.y+t},{x:e.x-t,y:e.y+t}];return n.map((a,s)=>({from:a,to:n[(s+1)%4]}))})),this.blockWallCache}atGoal(){const e=s1(this.pose.heading),t={x:this.pose.x+e.x*a1,y:this.pose.y+e.y*a1};return(this.setup.goals??[]).some(n=>L1(this.pose,n)||L1(t,n))||(this.setup.targets??[]).some(n=>L1(this.pose,n))}apply(e){switch(e.method){case"forward":return this.wheels=[0,0],this.drive(e.args[0]);case"backward":return this.wheels=[0,0],this.drive(-e.args[0]);case"turnRight":return this.wheels=[0,0],this.turn(e.args[0]);case"turnLeft":return this.wheels=[0,0],this.turn(-e.args[0]);case"stop":this.wheels=[0,0];return;case"drive":this.wheels=[fu(e.args[0]),fu(e.args[1])];return;case"pause":return this.tick(e.args[0]);case"resetTimer":this.timerStart=this.time;return;case"setLed":this.leds=Ki().map(()=>pu(e.args));return;case"ledOff":this.leds=Ki();return;case"ledColor":this.leds[e.args[0]]=pu(qa[e.text??""]??[0,0,0]);return;case"showText":this.screen=e.text;return}}tick(e){if(e<=0)return;this.time+=e;const[t,n]=this.wheels.map(o=>o/100*hx);if(t===0&&n===0)return;const a=Math.ceil(e/10),s=e/1e3/a;let r=!1;for(let o=0;o{const r={x:this.pose.x+e.x*a1+t.x*a,y:this.pose.y+e.y*a1+t.y*a};([...this.setup.marks??[],...this.setup.goals??[]].some(l=>L1(r,l))||this.setup.lines.some(l=>fx(r,l)<=dx/2))&&(n|=1<<3-s)}),n}colorUnder(){var n;const e=s1(this.pose.heading),t={x:this.pose.x+e.x*a1,y:this.pose.y+e.y*a1};return(n=(this.setup.colors??[]).find(a=>L1(t,a.at)))==null?void 0:n.color}sensors(){const e=this.lineState();return{getDistance:this.distance(),getLine:e,getColor:this.colorUnder()??(e&6?"black":"white"),isLineLeft:(e&4)!==0,isLineRight:(e&2)!==0,getTimer:this.timer}}freeDistance(e,t){let n=1/0;for(const a of this.allWalls){const s=px(e,t,a.from,a.to);s!==void 0&&sMath.max(-100,Math.min(100,i));function xu(i){const e=(i%360+360)%360;return Math.abs(e-360)<1e-9?0:e}function px(i,e,t,n){const a={x:n.x-t.x,y:n.y-t.y},s=e.x*a.y-e.y*a.x;if(Math.abs(s)<1e-12)return;const r={x:t.x-i.x,y:t.y-i.y},o=(r.x*a.y-r.y*a.x)/s,l=(r.x*e.y-r.y*e.x)/s;return o>=0&&l>=0&&l<=1?o:void 0}function fx(i,e){let t=1/0;for(let n=0;n+10&&o.tick(Jl),s.robotSensors={...o.sensors(),...zx(a,u)};const c=()=>({outputs:[...m.outputLines],files:new Map(m.files),drive:m.robotActions.length?$a(m.robotActions):void 0,...n?{atGoal:o.atGoal(),bumps:o.bumps}:{},led:o.leds.some(d=>d!==void 0),tone:m.robotActions.some(d=>d.method==="playTone"),screen:o.screen,actions:Md(m.robotActions.filter(d=>!yx.has(d.method)))});if(m.inputRequest){const d=r.shift();if(d===void 0)return{...c(),missingInput:!0};if(s.provideInput(d),m.inputErrorNotice)return{...c(),error:m.inputErrorNotice};continue}if(m.isHalted)return{...c(),error:m.notice};if(!s.canStep)return{...c(),unusedInputs:r.length||void 0};s.step()}return{outputs:[...s.state.outputLines],files:new Map(s.state.files),drive:$a(s.state.robotActions),tooManySteps:!0}}function zx(i,e){const t=Math.floor(e/bx);return Object.fromEntries(Object.entries(i??{}).map(([n,a])=>[n,a[Math.min(t,a.length-1)]]))}function gh(i){return i===void 0||i===""?[]:i.replace(/\n$/,"").split(` `)}function ea(i,e){return i.length!==e.length?!1:i.every((t,n)=>bu(t)===bu(e[n]))}function bu(i){const e=i.trim().replace(/\s+/g," ");return/^-?\d+\.0+$/.test(e)?e.replace(/\.0+$/,""):e}function Ix(i,e,t,n){return e.map(a=>{var d,h,g;const s=a.world?n==null?void 0:n(a.world):void 0;if(a.world&&!s)throw new Error(`Weltkarte „${a.world}“ fehlt.`);const r=wx(i,a.inputs,t,s,a.sensors),o=(a.files??[]).every(f=>{var x;return ea(gh((x=r.files)==null?void 0:x.get(f.name)),f.lines)}),l=!a.drive||ea(r.drive??[],a.drive),u=!a.world||r.bumps===0&&(!((d=s==null?void 0:s.goals)!=null&&d.length||(h=s==null?void 0:s.targets)!=null&&h.length)||r.atGoal===!0),m=(a.led===void 0||r.led===a.led)&&(a.tone===void 0||r.tone===a.tone)&&(a.screen===void 0||r.screen===a.screen)&&(a.drives===void 0||(((g=r.drive)==null?void 0:g.length)??0)>0===a.drives)&&(!a.actions||ea(r.actions??[],a.actions)),c=!r.error&&!r.missingInput&&!r.tooManySteps&&ea(r.outputs,a.expected)&&o&&l&&u&&m;return{test:a,result:r,passed:c}})}function kx(i){const e=new Set,t=n=>{for(const a of n){e.add(a.type),a.loopBody&&t(a.loopBody);for(const s of a.cases??[])t(s.elements)}};return t(i.elements),e}function xo(i){const e=[z.forSchleife,z.whileSchleife,z.doUntilSchleife,z.endlosschleife];let t=0;for(const n of i){const a=Math.max(xo(n.loopBody??[]),...(n.cases??[]).map(s=>xo(s.elements)));t=Math.max(t,a+(e.includes(n.type)?1:0))}return t}class vi extends Error{}function Sx(i,e){const t=[],n=[];for(const a of i){const s=a.trim();if(!s)continue;if(s.startsWith("?")){const o=s.slice(1).trim();rs(o,_x(t)),n.push(o);continue}const r=/^([A-Za-z_]\w*)\s*:\s*(?:(-?\d+)\s*\.\.\s*(-?\d+)|(boolean))$/.exec(s);if(!r)throw new vi(`${e}: Unbekannte Zeile im Spiel: „${s}“`);t.push(r[4]?{name:r[1],kind:"boolean"}:{name:r[1],kind:"int",min:Number(r[2]),max:Number(r[3])})}if(!n.length)throw new vi(`${e}: Das Spiel braucht mindestens eine Zeile „? bedingung“.`);return{vars:t,conditions:n}}function _x(i){return Object.fromEntries(i.map(e=>[e.name,e.kind==="boolean"?!0:e.min]))}function Tx(i){const e=[],t=/\s*(?:(\d+)|(true|false)\b|([A-Za-z_]\w*)|(&&|\|\||==|!=|<=|>=|<|>|!|\(|\)))/y;let n=0;for(;nt[n],s=d=>{var h;return((h=a())==null?void 0:h.kind)==="op"&&a().value===d},r=()=>{throw new vi(`Bedingung nicht lesbar: „${i}“`)},o=()=>{const d=t[n++]??r();if(d.kind==="num"||d.kind==="bool")return d.value;if(d.kind==="name"){if(!(d.value in e))throw new vi(`Unbekannte Variable „${d.value}“ in „${i}“`);return e[d.value]}if(d.value==="("){const h=m();return s(")")||r(),n++,h}if(d.value==="!"){const h=o();return typeof h!="boolean"&&r(),!h}return r()},l=()=>{const d=o(),h=a();if((h==null?void 0:h.kind)==="op"&&["==","!=","<","<=",">",">="].includes(h.value)){n++;const g=o();switch(h.value){case"==":return d===g;case"!=":return d!==g}(typeof d!="number"||typeof g!="number")&&r();const[f,x]=[d,g];return h.value==="<"?f"?f>x:f>=x}return d},u=()=>{let d=l();for(;s("&&");){n++;const h=l();d=d&&h}return d},m=()=>{let d=u();for(;s("||");){n++;const h=u();d=d||h}return d},c=m();return n!==t.length||typeof c!="boolean"?r():c}function Ox(i,e){const t=[i],n=i.replace(/\b[A-Za-z_]\w*\b/g,r=>r in e?String(e[r]):r);n!==i&&t.push(n);const a=n.replace(/(-?\d+|true|false)\s*(==|!=|<=|>=|<|>)\s*(-?\d+|true|false)/g,r=>String(rs(r,{})));a!==t[t.length-1]&&t.push(a);const s=String(rs(i,e));return s!==t[t.length-1]&&t.push(s),t}function Ax(i,e){const t=[],n=new RegExp(`\\b${e}\\s*(?:==|!=|<=|>=|<|>)\\s*(-?\\d+)|(-?\\d+)\\s*(?:==|!=|<=|>=|<|>)\\s*${e}\\b`,"g");for(const a of i.matchAll(n)){const s=Number(a[1]??a[2]);t.push(s-1,s,s+1)}return t}function Px(i,e,t,n=Math.random){const a=i.conditions.length,s=Math.floor(e*a/t),r=Math.min(a-1,s+(n()<.5?0:1)),o=i.conditions[r],l={};for(const u of i.vars){if(u.kind==="boolean"){l[u.name]=n()<.5;continue}const m=Ax(o,u.name).filter(c=>c>=u.min&&c<=u.max);l[u.name]=m.length&&n()<.6?m[Math.floor(n()*m.length)]:u.min+Math.floor(n()*(u.max-u.min+1))}return{condition:o,values:l,answer:rs(o,l)}}function jx(i){return Object.entries(i.values).filter(([e])=>new RegExp(`\\b${e}\\b`).test(i.condition))}const Cx=`--- titel: Was ist ein Struktogramm? bereich: Erste Schritte @@ -60246,7 +60262,7 @@ raster: 3 `:"")+h.replace(/^( {4}|\t)/,"");continue}if(d=!1,!g)continue;const f=/^(titel|intro|antworten|frage|runde|klicks|richtig|zeit|fehler|besser|daten):\s*(.*)$/.exec(g);if(f){const[,v,w]=f;v==="runde"?(c={code:"",question:r,options:[],explanation:"",clicks:[]},m.push(c),d=!0):c?v==="frage"?c.question=w:v==="fehler"?c.wrongLine=Number(w):v==="besser"?c.fix=w:v==="klicks"?c.clicks=w.split(",").map(k=>k.trim()).filter(Boolean):v==="richtig"?c.rightText=w:n(`„${v}:“ gehört vor die erste Runde.`):v==="titel"?a=w:v==="intro"?s=w:v==="antworten"?o=w.split("|").map(k=>k.trim()):v==="frage"?r=w:v==="zeit"?l=Number(w):v==="daten"?u=w==="csv"?w:n("„daten:“ kennt nur „csv“."):n(`„${v}:“ gehört in eine Runde.`);continue}c||n(`Unbekannte Zeile vor der ersten Runde: „${g}“`);const x=c,b=/^-\s+(\[x\]\s+)?(.+)$/.exec(g);b?x.options.push({text:b[2].trim().replaceAll("\\n",` `),right:!!b[1]}):g.startsWith(">")?x.explanation+=(x.explanation?" ":"")+g.slice(1).trim():n(`Unbekannte Zeile im Spiel: „${g}“`)}return a||n("Das Spiel braucht eine Zeile „titel:“."),m.length||n("Das Spiel braucht mindestens eine „runde:“."),m.forEach((h,g)=>{if(h.code=h.code.replace(/\n+$/,""),i==="bombe"){const f=h.code.split(` `),x=h.wrongLine;(!x||!Number.isInteger(x)||x<1||x>f.length||!f[x-1].trim())&&n(`Runde ${g+1}: „fehler:“ muss eine Zeile des Codes sein.`),h.fix||n(`Runde ${g+1}: „besser:“ fehlt.`),h.options.length&&n(`Runde ${g+1}: Bei „bombe“ gibt es keine Antworten, man tippt auf die Zeile.`),h.question||n(`Runde ${g+1}: keine Frage.`);return}if(i==="reihenfolge"){h.options.length<3&&n(`Runde ${g+1}: „reihenfolge“ braucht mindestens drei Schritte.`),h.options.some(f=>f.right)&&n(`Runde ${g+1}: Bei „reihenfolge“ gibt es kein [x], die Schritte stehen der Reihe nach da.`),new Set(h.options.map(f=>f.text)).size!==h.options.length&&n(`Runde ${g+1}: zwei Schritte sind gleich.`),h.question||n(`Runde ${g+1}: keine Frage.`);return}if(h.options.length||(o.length||n(`Runde ${g+1}: keine Antworten.`),(!h.rightText||!o.includes(h.rightText))&&n(`Runde ${g+1}: „richtig:“ muss eine der Antworten sein.`),h.options=o.map(f=>({text:f,right:f===h.rightText}))),h.options.filter(f=>f.right).length!==1&&n(`Runde ${g+1}: genau eine Antwort muss richtig sein.`),h.question||n(`Runde ${g+1}: keine Frage.`),i==="layout"&&h.options.forEach(f=>ph(f.text,`Runde ${g+1}`,n)),i==="zuhoerer")try{const f=fh(h.code);for(const x of h.clicks)f.buttons.some(b=>b.caption===x)||n(`Runde ${g+1}: Knopf „${x}“ gibt es nicht.`);uB(f,h.clicks)}catch(f){if(f instanceof bo)throw f;n(`Runde ${g+1}: ${f.message}`)}delete h.rightText}),i==="bombe"&&!(l&&l>0)&&n("„bombe“ braucht „zeit:“ mit den Sekunden je Runde."),{kind:i,title:a,intro:s,...i==="bombe"?{seconds:l,...u?{data:u}:{}}:{},rounds:m}}function ph(i,e="",t=n=>{throw new bo(n)}){const n=/^(grid|flow|border):\s*(.+)$/.exec(i);if(!n)return t(`${e}: Antwort „${i}“ ist kein Fensterbild (grid:, flow: oder border:).`);if(n[1]==="border"){const s={};for(const r of n[2].split(/\s+/)){const o=/^([NSWEC])=(.+)$/.exec(r);o||t(`${e}: „${r}“ im BorderLayout-Bild verstehe ich nicht (z. B. N=A).`),s[o[1]]=o[2]}return{kind:"border",areas:s}}const a=n[2].split("/").map(s=>s.trim().split(/\s+/).filter(Boolean));return{kind:n[1],rows:a}}const Ca='"((?:[^"\\\\]|\\\\.)*)"';function fh(i){const e=i.split(` -`),t={title:"",buttons:[],labels:[],ints:{},listeners:[]},n=new Map,a=(r,o,l)=>{if(o.startsWith("{")){let m=r+1;const c=[];for(;m=e.length)throw new Error(`Dem Zuhörer fehlt „${l}“.`);return{from:r,to:m,statements:vo(c.join(" "))}}const u=l==="});"?o.replace(/\)\s*;\s*$/,""):o.replace(/;\s*$/,"");return{from:r,to:r,statements:vo(u)}},s=r=>{if(!t.buttons.some(o=>o.name===r))throw new Error(`Knopf ${r} ist nicht angelegt.`);return r};for(let r=0;r\s*(.*)$/.exec(o)){const u=a(r,l[2],"};");n.set(l[1],u),r=u.to}else if(l=/^(\w+)\.addActionListener\(\s*(\w+)\s*\)\s*;$/.exec(o)){const u=n.get(l[2]);if(!u)throw new Error(`Zuhörer ${l[2]} ist nicht angelegt.`);t.listeners.push({button:s(l[1]),...u})}else if(l=/^(\w+)\.addActionListener\(\s*\w+\s*->\s*(.*)$/.exec(o)){const u=a(r,l[2],"});");t.listeners.push({button:s(l[1]),...u}),r=u.to}}return t}function vo(i){const e=[];let t=0;const n=()=>{for(;t{let u=0,m=!1;const c=t+1;for(;t{let o=0,l=!1;const u=t;for(;t{if(n(),i[t]==="{")return vo(a("{","}"));if(/^if\s*\(/.test(i.slice(t))){t=i.indexOf("(",t);const l=a("(",")").trim(),u=r();n();let m=[];return/^else\b/.test(i.slice(t))&&(t+=4,m=r()),[{condition:l,then:u,otherwise:m}]}const o=s();return o?[o]:[]};for(n();ta.caption===t)??i.buttons.find(a=>e.texts[a.name]===t);if(!n)throw new Error(`Knopf „${t}“ gibt es nicht.`);return vh(i,e,n.name)}function vh(i,e,t){const n=i.listeners.find(r=>r.button===t),a=[],s={source:t,command:e.texts[t]};for(const r of(n==null?void 0:n.statements)??[])yh(r,e,a,s);return{button:t,listener:n,texts:{...e.texts},console:a}}function uB(i,e){const t=xh(i);return e.map(n=>bh(i,t,n))}function yh(i,e,t,n){if(typeof i!="string"){for(const s of mB(i.condition,e,n)?i.then:i.otherwise)yh(s,e,t,n);return}let a;if(a=/^(\w+)\.setText\((.*)\)$/.exec(i)){if(!(a[1]in e.texts))throw new Error(`${a[1]} ist keine Beschriftung und kein Knopf.`);e.texts[a[1]]=String(Jn(a[2],e,n))}else if(a=/^System\.out\.println\((.*)\)$/.exec(i))t.push(String(Jn(a[1],e,n)));else if(a=/^(\w+)\s*(\+\+|--)$/.exec(i))e.ints[wu(a[1],e)]+=a[2]==="++"?1:-1;else if(a=/^(\w+)\s*([+-]?=)\s*(.+)$/.exec(i)){const s=wu(a[1],e),r=Number(Jn(a[3],e,n));e.ints[s]=a[2]==="="?r:a[2]==="+="?e.ints[s]+r:e.ints[s]-r}else throw new Error(`Diese Anweisung kann das Spiel nicht nachspielen: „${i}“`)}function mB(i,e,t){let n;if(n=/^e\.getSource\(\)\s*(==|!=)\s*(\w+)$/.exec(i)){if(!(n[2]in e.texts))throw new Error(`${n[2]} ist kein Knopf.`);return t.source===n[2]==(n[1]==="==")}if(n=/^(!?)(.+)\.equals\((.+)\)$/.exec(i))return String(Jn(n[2],e,t))===String(Jn(n[3],e,t))!=(n[1]==="!");if(n=/^(.+?)\s*(==|!=|<=|>=|<|>)\s*(.+)$/.exec(i)){const a=Number(Jn(n[1],e,t)),s=Number(Jn(n[3],e,t));return{"==":a===s,"!=":a!==s,"<=":a<=s,">=":a>=s,"<":a":a>s}[n[2]]}throw new Error(`Diese Bedingung kann das Spiel nicht nachspielen: „${i}“`)}function wu(i,e){if(!(i in e.ints))throw new Error(`Variable ${i} ist nicht angelegt.`);return i}function Jn(i,e,t){const n=i.match(new RegExp(`${Ca}|\\d+|e\\.getActionCommand\\(\\)|\\w+(?:\\.getText\\(\\))?|[-+*/()]`,"g"))??[];let a=0;const s=()=>{const l=n[a++];if(l===void 0)throw new Error(`Unvollständiger Ausdruck „${i}“`);if(l==="("){const u=o();return a++,u}if(l.startsWith('"'))return JSON.parse(l);if(/^\d+$/.test(l))return Number(l);if(l==="e.getActionCommand()"){if(!t)throw new Error("e.getActionCommand() gibt es nur im Zuhörer.");return t.command}if(l.endsWith(".getText()"))return e.texts[l.slice(0,-10)]??"";if(l in e.ints)return e.ints[l];throw new Error(`Unbekannt: „${l}“`)},r=()=>{let l=s();for(;n[a]==="*"||n[a]==="/";){const u=n[a++],m=Number(s());l=u==="*"?Number(l)*m:Math.trunc(Number(l)/m)}return l},o=()=>{let l=r();for(;n[a]==="+"||n[a]==="-";){const u=n[a++],m=r();u==="+"?l=typeof l=="string"||typeof m=="string"?`${l}${m}`:l+m:l=Number(l)-Number(m)}return l};return o()}class cB extends Error{}const os="___";function dB(i){const e=Array.from({length:i.rows},()=>Array(i.cols).fill(""));for(const t of i.words)[...t.word].forEach((n,a)=>e[t.row+(t.across?0:a)][t.col+(t.across?a:0)]=n);return e}function hB(i,e){const t=_=>{throw new cB(`${e}: ${_}`)},n=(_,C)=>{const B=/^(\d+)\s+(\d+)$/.exec(_.trim());return!B||Number(B[1])<1||Number(B[2])<1?t(`${C}: „${_}“ ist kein Feld (Zeile Spalte, ab 1).`):{row:Number(B[1])-1,col:Number(B[2])-1}};let a="",s="",r="ABCDEFGHIJKLMNOPQRSTUVWXYZ",o="",l="",u="",m="";const c=[],d=[];let h=[],g,f="start";for(const _ of i){const C=_.trim();if(g&&(/^( {4}|\t)/.test(_)||C==="")){const P=_.replace(/^( {4}|\t)/,"");if(g==="station"){const A=c[c.length-1];A.code+=(A.code?` +`),t={title:"",buttons:[],labels:[],ints:{},listeners:[]},n=new Map,a=(r,o,l)=>{if(o.startsWith("{")){let m=r+1;const c=[];for(;m=e.length)throw new Error(`Dem Zuhörer fehlt „${l}“.`);return{from:r,to:m,statements:vo(c.join(" "))}}const u=l==="});"?o.replace(/\)\s*;\s*$/,""):o.replace(/;\s*$/,"");return{from:r,to:r,statements:vo(u)}},s=r=>{if(!t.buttons.some(o=>o.name===r))throw new Error(`Knopf ${r} ist nicht angelegt.`);return r};for(let r=0;r\s*(.*)$/.exec(o)){const u=a(r,l[2],"};");n.set(l[1],u),r=u.to}else if(l=/^(\w+)\.addActionListener\(\s*(\w+)\s*\)\s*;$/.exec(o)){const u=n.get(l[2]);if(!u)throw new Error(`Zuhörer ${l[2]} ist nicht angelegt.`);t.listeners.push({button:s(l[1]),...u})}else if(l=/^(\w+)\.addActionListener\(\s*\w+\s*->\s*(.*)$/.exec(o)){const u=a(r,l[2],"});");t.listeners.push({button:s(l[1]),...u}),r=u.to}}return t}function vo(i){const e=[];let t=0;const n=()=>{for(;t{let u=0,m=!1;const c=t+1;for(;t{let o=0,l=!1;const u=t;for(;t{if(n(),i[t]==="{")return vo(a("{","}"));if(/^if\s*\(/.test(i.slice(t))){t=i.indexOf("(",t);const l=a("(",")").trim(),u=r();n();let m=[];return/^else\b/.test(i.slice(t))&&(t+=4,m=r()),[{condition:l,then:u,otherwise:m}]}const o=s();return o?[o]:[]};for(n();ta.caption===t)??i.buttons.find(a=>e.texts[a.name]===t);if(!n)throw new Error(`Knopf „${t}“ gibt es nicht.`);return vh(i,e,n.name)}function vh(i,e,t){const n=i.listeners.find(r=>r.button===t),a=[],s={source:t,command:e.texts[t]};for(const r of(n==null?void 0:n.statements)??[])yh(r,e,a,s);return{button:t,listener:n,texts:{...e.texts},console:a}}function uB(i,e){const t=xh(i);return e.map(n=>bh(i,t,n))}function yh(i,e,t,n){if(typeof i!="string"){for(const s of mB(i.condition,e,n)?i.then:i.otherwise)yh(s,e,t,n);return}let a;if(a=/^(\w+)\.setText\((.*)\)$/.exec(i)){if(!(a[1]in e.texts))throw new Error(`${a[1]} ist keine Beschriftung und kein Knopf.`);e.texts[a[1]]=String(Rn(a[2],e,n))}else if(a=/^System\.out\.println\((.*)\)$/.exec(i))t.push(String(Rn(a[1],e,n)));else if(a=/^(\w+)\s*(\+\+|--)$/.exec(i))e.ints[wu(a[1],e)]+=a[2]==="++"?1:-1;else if(a=/^(\w+)\s*([+-]?=)\s*(.+)$/.exec(i)){const s=wu(a[1],e),r=Number(Rn(a[3],e,n));e.ints[s]=a[2]==="="?r:a[2]==="+="?e.ints[s]+r:e.ints[s]-r}else throw new Error(`Diese Anweisung kann das Spiel nicht nachspielen: „${i}“`)}function mB(i,e,t){let n;if(n=/^e\.getSource\(\)\s*(==|!=)\s*(\w+)$/.exec(i)){if(!(n[2]in e.texts))throw new Error(`${n[2]} ist kein Knopf.`);return t.source===n[2]==(n[1]==="==")}if(n=/^(!?)(.+)\.equals\((.+)\)$/.exec(i))return String(Rn(n[2],e,t))===String(Rn(n[3],e,t))!=(n[1]==="!");if(n=/^(.+?)\s*(==|!=|<=|>=|<|>)\s*(.+)$/.exec(i)){const a=Number(Rn(n[1],e,t)),s=Number(Rn(n[3],e,t));return{"==":a===s,"!=":a!==s,"<=":a<=s,">=":a>=s,"<":a":a>s}[n[2]]}throw new Error(`Diese Bedingung kann das Spiel nicht nachspielen: „${i}“`)}function wu(i,e){if(!(i in e.ints))throw new Error(`Variable ${i} ist nicht angelegt.`);return i}function Rn(i,e,t){const n=i.match(new RegExp(`${Ca}|\\d+|e\\.getActionCommand\\(\\)|\\w+(?:\\.getText\\(\\))?|[-+*/()]`,"g"))??[];let a=0;const s=()=>{const l=n[a++];if(l===void 0)throw new Error(`Unvollständiger Ausdruck „${i}“`);if(l==="("){const u=o();return a++,u}if(l.startsWith('"'))return JSON.parse(l);if(/^\d+$/.test(l))return Number(l);if(l==="e.getActionCommand()"){if(!t)throw new Error("e.getActionCommand() gibt es nur im Zuhörer.");return t.command}if(l.endsWith(".getText()"))return e.texts[l.slice(0,-10)]??"";if(l in e.ints)return e.ints[l];throw new Error(`Unbekannt: „${l}“`)},r=()=>{let l=s();for(;n[a]==="*"||n[a]==="/";){const u=n[a++],m=Number(s());l=u==="*"?Number(l)*m:Math.trunc(Number(l)/m)}return l},o=()=>{let l=r();for(;n[a]==="+"||n[a]==="-";){const u=n[a++],m=r();u==="+"?l=typeof l=="string"||typeof m=="string"?`${l}${m}`:l+m:l=Number(l)-Number(m)}return l};return o()}class cB extends Error{}const os="___";function dB(i){const e=Array.from({length:i.rows},()=>Array(i.cols).fill(""));for(const t of i.words)[...t.word].forEach((n,a)=>e[t.row+(t.across?0:a)][t.col+(t.across?a:0)]=n);return e}function hB(i,e){const t=_=>{throw new cB(`${e}: ${_}`)},n=(_,C)=>{const B=/^(\d+)\s+(\d+)$/.exec(_.trim());return!B||Number(B[1])<1||Number(B[2])<1?t(`${C}: „${_}“ ist kein Feld (Zeile Spalte, ab 1).`):{row:Number(B[1])-1,col:Number(B[2])-1}};let a="",s="",r="ABCDEFGHIJKLMNOPQRSTUVWXYZ",o="",l="",u="",m="";const c=[],d=[];let h=[],g,f="start";for(const _ of i){const C=_.trim();if(g&&(/^( {4}|\t)/.test(_)||C==="")){const P=_.replace(/^( {4}|\t)/,"");if(g==="station"){const A=c[c.length-1];A.code+=(A.code?` `:"")+P}else u+=(u?` `:"")+P;continue}if(g=void 0,!C)continue;const B=/^(titel|intro|alphabet|station|frage|zahl|feld|tipp|kreuzwort|lösung|loesung|tor|ende):\s*(.*)$/.exec(C);if(B){const[,P,A]=B;if(P==="station")c.push({name:A,code:"",question:"",hint:"",explanation:""}),f="station",g="station";else if(P==="kreuzwort")o=A,f="crossword";else if(P==="tor")l=A,f="gate",g="gate";else if(P==="titel")a=A;else if(P==="intro")s=A;else if(P==="alphabet")r=A;else if(P==="ende")m=A;else if(P==="lösung"||P==="loesung")f!=="crossword"&&t("„lösung:“ gehört zum Kreuzworträtsel."),h=A.split(",").map(W=>n(W,"lösung"));else{f!=="station"&&t(`„${P}:“ gehört in eine Station.`);const W=c[c.length-1];P==="frage"?W.question=A:P==="tipp"?W.hint=A:P==="zahl"?W.answer=/^-?\d+$/.test(A)?Number(A):t(`Station „${W.name}“: „zahl:“ muss eine ganze Zahl sein.`):Object.assign(W,n(A,`Station „${W.name}“`))}continue}if(f==="crossword"){const P=/^-\s+([→↓])\s+(\d+)\s+(\d+)\s+([A-ZÄÖÜ]+):\s*(.+)$/u.exec(C);P||t(`Kreuzworträtsel: „${C}“ verstehe ich nicht (z. B. „- → 1 3 STRING: Hinweis“).`),d.push({across:P[1]==="→",row:Number(P[2])-1,col:Number(P[3])-1,word:P[4],clue:P[5]});continue}if(f==="station"&&C.startsWith(">")){const P=c[c.length-1];P.explanation+=(P.explanation?" ":"")+C.slice(1).trim();continue}t(`Unbekannte Zeile im Spiel: „${C}“`)}a||t("Das Spiel braucht eine Zeile „titel:“."),c.length||t("Das Spiel braucht mindestens eine „station:“."),d.length||t("Das Spiel braucht ein „kreuzwort:“ mit Wörtern."),h.length||t("Das Kreuzworträtsel braucht eine Zeile „lösung:“."),u.includes(os)||t(`Der Code bei „tor:“ braucht ${os} für das Eingabefeld.`),new Set(r).size!==r.length&&t("Im Alphabet kommt ein Zeichen doppelt vor.");const x=Math.max(...d.map(_=>_.row+(_.across?1:_.word.length))),b=Math.max(...d.map(_=>_.col+(_.across?_.word.length:1))),v=Array.from({length:x},()=>Array(b).fill(""));for(const _ of d)[..._.word].forEach((C,B)=>{const P=_.row+(_.across?0:B),A=_.col+(_.across?B:0);v[P][A]&&v[P][A]!==C&&t(`Kreuzworträtsel: ${_.word} passt in Zeile ${P+1}, Spalte ${A+1} nicht (dort steht ${v[P][A]}).`),v[P][A]=C});const w=[...new Set(d.map(_=>_.row*b+_.col))].sort((_,C)=>_-C),k=d.map(_=>({..._,number:w.indexOf(_.row*b+_.col)+1})),I=(_,C)=>{var B;return((B=v[_])==null?void 0:B[C])??""},T=h.map(({row:_,col:C})=>I(_,C)||t(`lösung: In Zeile ${_+1}, Spalte ${C+1} ist kein Feld.`)).join(""),S=c.map(_=>{_.code||t(`Station „${_.name}“: Code fehlt.`),_.question||t(`Station „${_.name}“: „frage:“ fehlt.`),_.answer===void 0&&t(`Station „${_.name}“: „zahl:“ fehlt.`),_.row===void 0&&t(`Station „${_.name}“: „feld:“ fehlt.`);const C=r.charAt(_.answer);C||t(`Station „${_.name}“: alphabet.charAt(${_.answer}) gibt es nicht.`);const B=I(_.row,_.col);return B!==C&&t(`Station „${_.name}“: alphabet.charAt(${_.answer}) ist ${C}, im Feld ${_.row+1} ${_.col+1} steht aber „${B}“.`),_.code=_.code.replace(/\n+$/,""),_});return{title:a,intro:s,alphabet:r,stations:S,crosswordText:o,rows:x,cols:b,words:k,solution:h,keyword:T,gateText:l,gateCode:u.replace(/\n+$/,""),end:m}}const gB=/\[\[(.+?)\]\]/g;function pB(i,e){const t={title:"",task:"",blocks:[]},n=[];let a=!1;for(const s of i){if(/^\s*```/.test(s)){a||n.push([]),a=!a;continue}if(a){n[n.length-1].push(s.replace(/\s+$/,""));continue}const r=s.trim();if(!r)continue;const o=/^([a-zäöü]+):\s*(.*)$/i.exec(r);if(!o)throw new Error(`${e}: Unbekannte Zeile im Lückentext: „${r}“.`);const l=o[2].trim();switch(o[1].toLowerCase()){case"titel":t.title=l;break;case"auftrag":t.task=l;break;case"erklärung":case"erklaerung":t.explanation=l;break;default:throw new Error(`${e}: Unbekannter Schlüssel „${o[1]}“ im Lückentext.`)}}if(a)throw new Error(`${e}: Der Codeblock im Lückentext wird nicht mit \`\`\` geschlossen.`);if(!t.title)throw new Error(`${e}: Ein Lückentext braucht einen Titel.`);if(!n.some(s=>s.some(r=>r.trim())))throw new Error(`${e}: Lückentext „${t.title}“ braucht einen Codeblock.`);if(t.blocks=n.map(s=>{const r=Math.min(...s.filter(o=>o.trim()).map(o=>/^ */.exec(o)[0].length));return s.map(o=>fB(o.slice(r),e,t.title))}),!xB(t).length)throw new Error(`${e}: Lückentext „${t.title}“ braucht mindestens eine Lücke [[…]].`);return t}function fB(i,e,t){const n=[];let a=0;for(const s of i.matchAll(gB)){s.index>a&&n.push(i.slice(a,s.index));const r=s[1].split(/\s+\|\s+/).map(o=>o.trim()).filter(Boolean);if(!r.length)throw new Error(`${e}: Leere Lücke im Lückentext „${t}“.`);n.push({answers:r}),a=s.index+s[0].length}if(atypeof s=="string"&&(s.includes("[[")||s.includes("]]"))))throw new Error(`${e}: Unvollständige Lücke im Lückentext „${t}“: „${i}“.`);return n}function xB(i){return i.blocks.flat().flatMap(e=>e.flatMap(t=>typeof t=="string"?[]:[t.answers]))}function bB(i,e){const t=n=>n.replace(/\s+/g,"");return t(e)!==""&&i.some(n=>t(n)===t(e))}class K extends Error{}function wh(i,e){const t=/^---\n([\s\S]*?)\n---\n?/.exec(i.replace(/\r\n/g,` `));if(!t)throw new K(`${e}: Kopfzeilen (--- … ---) fehlen.`);const n=new Map;for(const a of t[1].split(` @@ -60270,7 +60286,7 @@ ${l}`)}Da=sB(((o=e.find(([l])=>l==="begriffe.md"))==null?void 0:o[1])??"")}ls("e `))}`);continue}const r=[];for(;n|\||\s*([-*]|\d+\.)\s+)/.test(t[n]);)r.push(t[n++].trim());e.push(`

${Fe(r.join(" "))}

`)}return e.join(` `)}const ta=""+new URL("ludwig-Cus1i402.webp",import.meta.url).href,yo="f4ecc8e489ae7865308288c7d0fa313333cf2be3ff529b23bc214bee010310e0",Rl="visustruct.learn.teacher";let Gl=!1;function Au(){if(Gl)return!0;try{return localStorage.getItem(Rl)===yo}catch{return!1}}async function ZB(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 MB(i){let e=!1;try{e=await ZB(i.trim())===yo}catch{return!1}if(e){Gl=!0;try{localStorage.setItem(Rl,yo)}catch{}}return e}function LB(){Gl=!1;try{localStorage.removeItem(Rl)}catch{}}function Oh(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 Ah(i){return[...i].map(([e,t])=>Oh(e,t,!0))}function Qn(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 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 Te=i=>i.replace(/&/g,"&").replace(//g,">").replace(/"/g,"""),Pu=["0.2","0.5","1.0","1.5","2.0"],WB=i=>Number(i).toLocaleString(Yn()==="java"?"en":Yn(),{minimumFractionDigits:1}),ur="visustruct.simulation.stepDelay",ju="visustruct.simulation.highlightMode";function mr(i){try{return localStorage.getItem(i)}catch{return null}}function Cu(i,e){try{localStorage.setItem(i,e)}catch{}}class EB{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",Pu.includes(mr(ur)??"")?mr(ur):"0.5");y(this,"highlightMode",mr(ju)==="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 fi(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,M2(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 a;const t=this.isPlaying||this.wasPlayingBeforeInput;this.pause();const n=((a=this.engine.state.inputRequest)==null?void 0:a.prompt)??"";this.engine.provideInput(e.value),this.engine.state.inputRequest||(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 fi(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 Ah(i){return[...i].map(([e,t])=>Oh(e,t,!0))}function qn(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 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 Te=i=>i.replace(/&/g,"&").replace(//g,">").replace(/"/g,"""),Pu=["0.2","0.5","1.0","1.5","2.0"],WB=i=>Number(i).toLocaleString(Xn()==="java"?"en":Xn(),{minimumFractionDigits:1}),ur="visustruct.simulation.stepDelay",ju="visustruct.simulation.highlightMode";function mr(i){try{return localStorage.getItem(i)}catch{return null}}function Cu(i,e){try{localStorage.setItem(i,e)}catch{}}class EB{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",Pu.includes(mr(ur)??"")?mr(ur):"0.5");y(this,"highlightMode",mr(ju)==="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 fi(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,M2(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 fi(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=`

${Te(p("simulation_controls"))}

@@ -60295,22 +60311,22 @@ ${l}`)}Da=sB(((o=e.find(([l])=>l==="begriffe.md"))==null?void 0:o[1])??"")}ls("e

${Te(p("simulation_trace"))}

${Te(p("simulation_variables"))}

${Te(p("simulation_output"))}

- `;const e=a=>this.element.querySelector(a);this.buttons={play:e("[data-sim=play]"),pause:e("[data-sim=pause]"),step:e("[data-sim=step]"),stop:e("[data-sim=stop]")},this.buttons.play.addEventListener("click",()=>this.play()),this.buttons.pause.addEventListener("click",()=>this.pause()),this.buttons.step.addEventListener("click",()=>this.step()),this.buttons.stop.addEventListener("click",()=>this.reset()),this.editButton=e(".sim-edit"),this.editButton.addEventListener("click",()=>this.onEdit());const t=e("[data-sim=highlight]");t.value=this.highlightMode,t.addEventListener("change",()=>{this.highlightMode=t.value,Cu(ju,this.highlightMode)});const n=e("[data-sim=delay]");n.value=this.delay,n.addEventListener("change",()=>{this.delay=n.value,Cu(ur,this.delay)}),this.inputSection=e(".sim-input > div"),this.trace=e(".sim-trace"),this.variables=e(".sim-vars"),this.output=e(".sim-output"),this.notice=e(".sim-notice")}collectOutput(){const e=this.engine.state.outputLines;for(;this.printeds.localeCompare(r));if(n.length===0)this.variables.innerHTML=`

${Te(p("simulation_variables_placeholder"))}

`;else{const s=document.createElement("table");for(const r of n){const o=s.insertRow();o.insertCell().textContent=r;const l=e.variables.get(r),u=o.insertCell();l.kind==="grid"?u.append(Ph(l)):u.textContent=ke(l)}this.variables.replaceChildren(s)}e.outputLines.length===0&&e.files.size===0?this.output.innerHTML=`

${Te(p("simulation_output_placeholder"))}

`:(this.output.replaceChildren(...e.outputLines.map(s=>{const r=document.createElement("div");return r.textContent=s,r}),...Ah(e.files)),this.output.scrollTop=this.output.scrollHeight)}updateInput(){const e=this.engine.state.inputRequest,t=this.inputSection;if(t.parentElement.classList.toggle("active",!!e),!e){t.innerHTML=`

${Te(p("simulation_input_placeholder"))}

`;return}let n=t.querySelector("form");if(!n){n=document.createElement("form"),n.innerHTML=`

`;const o=n.querySelector("input");n.addEventListener("submit",l=>{l.preventDefault(),this.submitInput(o)}),t.replaceChildren(n),requestAnimationFrame(()=>o.focus())}n.querySelector(".sim-prompt").textContent=e.prompt;const a=n.querySelector("input");a.inputMode=e.valueType==="string"||e.valueType==="boolean"?"text":"decimal";const s=this.engine.state.inputErrorNotice,r=n.querySelector(".sim-input-error");r.textContent=s?Qn(s):"",r.hidden=!s}}function Ph(i){const e=document.createElement("table");e.className="sim-grid";for(const t of i.value){const n=e.insertRow();for(const a of t){const s=n.insertCell();s.textContent=String(a),a===!0&&(s.className="sim-grid-true")}}return e}const c1=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZ"),Ln=360/c1.length,NB="http://www.w3.org/2000/svg";function Me(i,e={},...t){const n=document.createElement(i);for(const[a,s]of Object.entries(e))n.setAttribute(a,s);return n.append(...t),n}function dt(i,e={},t){const n=document.createElementNS(NB,i);for(const[a,s]of Object.entries(e))n.setAttribute(a,String(s));return t!==void 0&&(n.textContent=t),n}function FB(i,e){const t=(e%26+26)%26;return Array.from(i).map(n=>{const a=n.charCodeAt(0);return a>=65&&a<=90?String.fromCharCode((a-65+t)%26+65):a>=97&&a<=122?String.fromCharCode((a-97+t)%26+97):n}).join("")}function Bu(i,e){const t=dt("g",{class:e}),n=c1.map((a,s)=>{const r=dt("g",{transform:`rotate(${s*Ln})`});return r.append(dt("text",{x:0,y:-i,"text-anchor":"middle","dominant-baseline":"central"},a)),t.append(r),r});return{group:t,cells:n}}function JB(i,e){let t=i,n=!1,a=-t*Ln;const s=Me("section",{class:"learn-game learn-caesar"});s.append(Me("div",{class:"learn-game-head"},Me("strong",{},p("web_learn_caesar_title")))),s.append(Me("p",{class:"learn-game-status"},p("web_learn_caesar_hint")));const r=dt("svg",{viewBox:"-200 -200 400 400",class:"learn-caesar-disc",role:"img"});r.append(dt("circle",{r:196,class:"outer-disc"})),r.append(dt("path",{d:RB(196,92,Ln/2),class:"window"}));const o=Bu(168,"outer-letters");r.append(o.group);for(let A=0;A{o.cells.forEach((W,R)=>W.classList.toggle("marked",R===A)),u.cells.forEach((W,R)=>W.classList.toggle("marked",A!==void 0&&R===(A+t)%26))},S=()=>{m.textContent=String(t),l.setAttribute("transform",`rotate(${a})`),r.setAttribute("aria-label",p("web_learn_caesar_key_fmt",t)),b.textContent=p(n?"web_learn_caesar_secret":"web_learn_caesar_plain"),w.textContent=p(n?"web_learn_caesar_plain":"web_learn_caesar_secret"),f.classList.toggle("active",!n),x.classList.toggle("active",n),k.textContent=FB(v.value,n?-t:t)||" ";const A=Array.from(v.value.toUpperCase()).reverse().find(R=>c1.includes(R));if(A===void 0)return T();const W=c1.indexOf(A);T(n?(W-t+26)%26:W)},_=A=>{t=(A%26+26)%26,a=-t*Ln,S()};c.addEventListener("click",()=>_(t-1)),d.addEventListener("click",()=>_(t+1)),f.addEventListener("click",()=>{var A;n&&(v.value=((A=k.textContent)==null?void 0:A.trim())??""),n=!1,S()}),x.addEventListener("click",()=>{var A;n||(v.value=((A=k.textContent)==null?void 0:A.trim())??""),n=!0,S()}),v.addEventListener("input",S),o.cells.forEach((A,W)=>A.addEventListener("click",()=>T(W)));let C;const B=A=>{const W=r.getBoundingClientRect();return Math.atan2(A.clientY-(W.top+W.height/2),A.clientX-(W.left+W.width/2))*180/Math.PI};l.addEventListener("pointerdown",A=>{const W=A;C=B(W)-a,l.classList.add("dragging"),r.setPointerCapture(W.pointerId),W.preventDefault()}),r.addEventListener("pointermove",A=>{if(C===void 0)return;a=B(A)-C,l.setAttribute("transform",`rotate(${a})`);const W=Math.round(-a/Ln);if((W%26+26)%26!==t){t=(W%26+26)%26;const R=a;S(),a=R,l.setAttribute("transform",`rotate(${a})`)}});const P=()=>{C!==void 0&&(C=void 0,l.classList.remove("dragging"),_(t))};return r.addEventListener("pointerup",P),r.addEventListener("pointercancel",P),S(),s}function RB(i,e,t){const n=(a,s)=>{const r=(s-90)*Math.PI/180;return`${(a*Math.cos(r)).toFixed(2)} ${(a*Math.sin(r)).toFixed(2)}`};return`M ${n(i,-t)} A ${i} ${i} 0 0 1 ${n(i,t)} L ${n(e,t)} A ${e} ${e} 0 0 0 ${n(e,-t)} Z`}const Hl=i=>p(`web_visubot_part_${i}`),jh=new WeakMap;function Ch(i,e,t,n){const a=document.createElement("div");a.className="visubot-model";const s=document.createElement("div");s.className="visubot-stage";const r=document.createElement("div");r.className="visubot-part-label",r.hidden=!0,s.append(r);const o=(c,d,h)=>{r.hidden=!1,r.textContent=Hl(c),r.style.left=`${Math.min(d+12,s.clientWidth-140)}px`,r.style.top=`${h+12}px`},l=document.createElement("p");l.className="visubot-model-hint hint",l.textContent=p("web_visubot_tap_part"),l.hidden=!!n,a.append(s,l);const u=Q(async()=>{const{Robot3D:c}=await import("./robot3d-GGJ-E5MR.js");return{Robot3D:c}},[],import.meta.url).then(({Robot3D:c})=>{const d=new c(s);d.showcase(),d.highlight(i),i.includes("leds")&&d.setLed([40,90,255]),d.focusOn([],e==="unten"||e==="bottom"?"":e,!1,1),d.focusOn(i,e,t);let h;return s.addEventListener("pointerdown",g=>h={x:g.clientX,y:g.clientY}),s.addEventListener("pointerup",g=>{if(!h||Math.hypot(g.clientX-h.x,g.clientY-h.y)>5)return;const f=d.partAt(g.clientX,g.clientY);if(!f)return;if(n)return n(f);d.highlight(f);const x=s.getBoundingClientRect();o(f,g.clientX-x.left,g.clientY-x.top)}),s.addEventListener("pointermove",g=>{if(g.pointerType!=="mouse"||n)return;const f=d.partAt(g.clientX,g.clientY);if(r.hidden=!f,!f)return;const x=s.getBoundingClientRect();o(f,g.clientX-x.left,g.clientY-x.top)}),s.addEventListener("pointerleave",()=>r.hidden=!0),d}).catch(c=>{console.error(c),s.textContent=p("web_visubot_no_3d")}),m={box:a,ready:u,focus:i,view:e};return jh.set(a,m),m}function GB(i,e,t=!1){return Ch(i,e,t).box}function HB(i){const e=i.querySelector(".visubot-model"),t=e&&jh.get(e);for(const n of i.querySelectorAll("[data-robot-part]")){const a=(n.dataset.robotPart??"").split(",").filter(Boolean);if(n.title=a.map(Hl).join(", "),!t)continue;const s=()=>void t.ready.then(o=>o==null?void 0:o.highlight(a)),r=()=>void t.ready.then(o=>o==null?void 0:o.highlight(t.focus));n.addEventListener("mouseenter",s),n.addEventListener("focus",s),n.addEventListener("mouseleave",r),n.addEventListener("blur",r),n.addEventListener("click",()=>{t.ready.then(o=>{o==null||o.highlight(a),o==null||o.focusOn(a,t.view)}),t.box.scrollIntoView({block:"nearest",behavior:"smooth"})})}}function VB(i,e){let t=0;const n=document.createElement("div");n.className="visubot-quiz-question";const a=document.createElement("p");a.className="visubot-quiz-feedback",a.setAttribute("aria-live","polite");const s=()=>{n.innerHTML=zn(`**${t+1}/${i.length}** ${i[t].question}`)},r=Ch([],void 0,!1,l=>{if(!(t>=i.length)){if(r.ready.then(u=>u==null?void 0:u.highlight(l)),l!==i[t].part){a.className="visubot-quiz-feedback wrong",a.textContent=p("web_visubot_quiz_wrong_fmt",Hl(l));return}t++,a.className="visubot-quiz-feedback right",t{u.forEach(v=>{window.clearTimeout(v),window.clearInterval(v)}),u=[]},c=()=>{a.textContent=`${p("web_game_round_fmt",o+1,r)} · ${p("web_game_score_fmt",l)}`},d=()=>{const v=V("button",{class:"primary"},o+1{o++,o{const v=i.rounds[o],w=i.seconds,k=V("div",{class:"learn-bomb-fuse"},V("span",{})),I=V("span",{class:"learn-bomb-time"}),T=V("div",{class:"learn-bomb","aria-live":"polite"},V("span",{class:"learn-bomb-icon","aria-hidden":"true"},"💣"),I,k),S=V("div",{class:"learn-game-feedback",role:"status"}),_=v.code.split(` -`).map((R,ne)=>{const ge=V("button",{class:"ln",type:"button"},R||" ");return ge.disabled=!R.trim(),ge.addEventListener("click",()=>A(ne+1===v.wrongLine?"right":"wrong",ge)),ge}),C=V("div",{class:"learn-game-code learn-bomb-code mono",dir:"ltr"},..._),B=Date.now(),P=()=>{if(!t.isConnected&&Date.now()-B>1e3)return m();const R=Math.max(0,w-(Date.now()-B)/1e3);I.textContent=p("web_game_time_fmt",Math.ceil(R)),k.firstChild.style.width=`${R/w*100}%`,T.classList.toggle("hurry",R<=5),R<=0&&A("time")},A=(R,ne)=>{m(),_.forEach((D,X)=>{D.disabled=!0,X+1===v.wrongLine&&D.classList.add("right")}),ne&&R==="wrong"&&ne.classList.add("wrong");const ge=R==="right";ge&&l++,c(),T.classList.add(ge?"defused":"boom"),T.firstChild.textContent=ge?"✂️":"💥",S.className=`learn-game-feedback ${ge?"right":"wrong"}`;const jt=d();S.replaceChildren(V("p",{},p(ge?"web_game_defused":R==="time"?"web_game_boom_time":"web_game_boom_wrong")),Zn("div",{class:"learn-game-explain"},v.explanation),V("p",{class:"learn-bomb-fix"},`${p("web_game_fix")} `,V("code",{},v.fix.trim())),jt),jt.focus({preventScroll:!0})};s.replaceChildren(T,Zn("p",{class:"learn-game-question"},v.question),C,S),P();const W=window.setInterval(P,200);u.push(W)},g=()=>{const v=i.rounds[o],w=[];v.code.trim()&&w.push(Zu(v.code).element),w.push(Zn("p",{class:"learn-game-question"},v.question),V("p",{class:"learn-order-hint"},p("web_game_order_hint")));const k=V("div",{class:"learn-game-options learn-order"}),I=V("div",{class:"learn-game-feedback",role:"status"});let T=0;const S=qB(v.options.length).map(C=>{const B=V("span",{class:"learn-order-badge","aria-hidden":"true"}),P=V("span",{});P.innerHTML=Fe(v.options[C].text);const A=V("button",{},B,P);return A.addEventListener("click",()=>{if(C!==T)return A.classList.add("wrong"),_(!1);A.classList.add("right"),B.textContent=String(++T),A.disabled=!0,T===v.options.length&&_(!0)}),k.append(A),{k:C,b:A,badge:B}}),_=C=>{for(const{k:P,b:A,badge:W}of[...S].sort((R,ne)=>R.k-ne.k))A.disabled=!0,W.textContent=String(P+1),k.append(A);C&&l++,c(),I.className=`learn-game-feedback ${C?"right":"wrong"}`;const B=d();I.replaceChildren(V("p",{},p(C?"web_game_right":"web_game_wrong_short")),Zn("div",{class:"learn-game-explain"},v.explanation),B),B.focus({preventScroll:!0})};s.replaceChildren(...w,k,I)},f=()=>{if(m(),i.kind==="bombe"||i.kind==="reihenfolge"){c(),i.kind==="bombe"?h():g();return}const v=i.rounds[o];c();const w=Zu(v.code),k=[];let I;i.kind==="zuhoerer"?(I=UB(fh(v.code),w),k.push(V("div",{class:"learn-swing-row"},w.element,I.element)),v.clicks.length&&k.push(V("p",{class:"learn-swing-clicks"},`${p("web_game_clicks")} `,...v.clicks.flatMap((B,P)=>[...P?[" → "]:[],V("code",{},B)])))):v.code.trim()&&k.push(w.element),k.push(Zn("p",{class:"learn-game-question"},v.question));const T=V("div",{class:`learn-game-options ${i.kind==="layout"?"pictures":""}`}),S=V("div",{class:"learn-game-feedback",role:"status"}),_=v.options.map(B=>{const P=V("button",{});return i.kind==="layout"?P.append(YB(B.text)):B.text.includes(` -`)?P.append($B(B.text)):P.innerHTML=Fe(B.text),P.addEventListener("click",()=>C(B.right,P)),T.append(P),P}),C=(B,P)=>{_.forEach((W,R)=>{W.disabled=!0,v.options[R].right&&W.classList.add("right")}),B||P.classList.add("wrong"),B&&l++,c(),S.className=`learn-game-feedback ${B?"right":"wrong"}`;const A=d();S.replaceChildren(V("p",{},p(B?"web_game_right":"web_game_wrong_short")),Zn("div",{class:"learn-game-explain"},v.explanation)),S.append(A),I&&(u=I.replay(v.clicks,()=>A.before(V("p",{class:"learn-swing-try"},p("web_game_try"))))),A.focus({preventScroll:!0})};s.replaceChildren(...k,T,S)},x=()=>{m(),a.textContent="";const v=V("button",{class:"primary"},p("web_game_again"));v.addEventListener("click",()=>{o=l=0,f()}),s.replaceChildren(V("p",{class:"learn-game-result"},p("web_game_done_fmt",l,r)),V("p",{},p(l===r?"web_game_perfect":l>=r*.7?"web_game_good":"web_game_practice_short")),v)},b=V("button",{class:"primary"},p("web_game_start"));return b.addEventListener("click",f),s.append(Zn("p",{},i.intro),b),t}function qB(i){const e=[...Array(i).keys()];for(;e.every((t,n)=>t===n);)for(let t=i-1;t>0;t--){const n=Math.floor(Math.random()*(t+1));[e[t],e[n]]=[e[n],e[t]]}return e}function Zu(i){const e=i.split(` + `;const e=a=>this.element.querySelector(a);this.buttons={play:e("[data-sim=play]"),pause:e("[data-sim=pause]"),step:e("[data-sim=step]"),stop:e("[data-sim=stop]")},this.buttons.play.addEventListener("click",()=>this.play()),this.buttons.pause.addEventListener("click",()=>this.pause()),this.buttons.step.addEventListener("click",()=>this.step()),this.buttons.stop.addEventListener("click",()=>this.reset()),this.editButton=e(".sim-edit"),this.editButton.addEventListener("click",()=>this.onEdit());const t=e("[data-sim=highlight]");t.value=this.highlightMode,t.addEventListener("change",()=>{this.highlightMode=t.value,Cu(ju,this.highlightMode)});const n=e("[data-sim=delay]");n.value=this.delay,n.addEventListener("change",()=>{this.delay=n.value,Cu(ur,this.delay)}),this.inputSection=e(".sim-input > div"),this.trace=e(".sim-trace"),this.variables=e(".sim-vars"),this.output=e(".sim-output"),this.notice=e(".sim-notice")}collectOutput(){const e=this.engine.state.outputLines;for(;this.printedr.localeCompare(o));if(n.length===0)this.variables.innerHTML=`

${Te(p("simulation_variables_placeholder"))}

`;else{const r=document.createElement("table");for(const o of n){const l=r.insertRow();l.insertCell().textContent=o;const u=e.variables.get(o),m=l.insertCell();u.kind==="grid"?m.append(Ph(u)):m.textContent=ke(u)}this.variables.replaceChildren(r)}e.outputLines.length===0&&e.files.size===0?this.output.innerHTML=`

${Te(p("simulation_output_placeholder"))}

`:(this.output.replaceChildren(...e.outputLines.map(r=>{const o=document.createElement("div");return o.textContent=r,o}),...Ah(e.files)),this.output.scrollTop=this.output.scrollHeight)}updateInput(){const e=this.engine.state.inputRequest,t=this.inputSection;if(t.parentElement.classList.toggle("active",!!e),!e){t.innerHTML=`

${Te(p("simulation_input_placeholder"))}

`;return}let n=t.querySelector("form");if(!n){n=document.createElement("form"),n.innerHTML=`

`;const o=n.querySelector("input");n.addEventListener("submit",l=>{l.preventDefault(),this.submitInput(o)}),t.replaceChildren(n),requestAnimationFrame(()=>o.focus())}n.querySelector(".sim-prompt").textContent=e.prompt;const a=n.querySelector("input");a.inputMode=e.valueType==="string"||e.valueType==="boolean"?"text":"decimal";const s=this.engine.state.inputErrorNotice,r=n.querySelector(".sim-input-error");r.textContent=s?qn(s):"",r.hidden=!s}}function Ph(i){const e=document.createElement("table");e.className="sim-grid";for(const t of i.value){const n=e.insertRow();for(const a of t){const s=n.insertCell();s.textContent=String(a),a===!0&&(s.className="sim-grid-true")}}return e}const c1=Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZ"),Wn=360/c1.length,NB="http://www.w3.org/2000/svg";function Me(i,e={},...t){const n=document.createElement(i);for(const[a,s]of Object.entries(e))n.setAttribute(a,s);return n.append(...t),n}function dt(i,e={},t){const n=document.createElementNS(NB,i);for(const[a,s]of Object.entries(e))n.setAttribute(a,String(s));return t!==void 0&&(n.textContent=t),n}function FB(i,e){const t=(e%26+26)%26;return Array.from(i).map(n=>{const a=n.charCodeAt(0);return a>=65&&a<=90?String.fromCharCode((a-65+t)%26+65):a>=97&&a<=122?String.fromCharCode((a-97+t)%26+97):n}).join("")}function Bu(i,e){const t=dt("g",{class:e}),n=c1.map((a,s)=>{const r=dt("g",{transform:`rotate(${s*Wn})`});return r.append(dt("text",{x:0,y:-i,"text-anchor":"middle","dominant-baseline":"central"},a)),t.append(r),r});return{group:t,cells:n}}function JB(i,e){let t=i,n=!1,a=-t*Wn;const s=Me("section",{class:"learn-game learn-caesar"});s.append(Me("div",{class:"learn-game-head"},Me("strong",{},p("web_learn_caesar_title")))),s.append(Me("p",{class:"learn-game-status"},p("web_learn_caesar_hint")));const r=dt("svg",{viewBox:"-200 -200 400 400",class:"learn-caesar-disc",role:"img"});r.append(dt("circle",{r:196,class:"outer-disc"})),r.append(dt("path",{d:RB(196,92,Wn/2),class:"window"}));const o=Bu(168,"outer-letters");r.append(o.group);for(let A=0;A{o.cells.forEach((W,R)=>W.classList.toggle("marked",R===A)),u.cells.forEach((W,R)=>W.classList.toggle("marked",A!==void 0&&R===(A+t)%26))},S=()=>{m.textContent=String(t),l.setAttribute("transform",`rotate(${a})`),r.setAttribute("aria-label",p("web_learn_caesar_key_fmt",t)),b.textContent=p(n?"web_learn_caesar_secret":"web_learn_caesar_plain"),w.textContent=p(n?"web_learn_caesar_plain":"web_learn_caesar_secret"),f.classList.toggle("active",!n),x.classList.toggle("active",n),k.textContent=FB(v.value,n?-t:t)||" ";const A=Array.from(v.value.toUpperCase()).reverse().find(R=>c1.includes(R));if(A===void 0)return T();const W=c1.indexOf(A);T(n?(W-t+26)%26:W)},_=A=>{t=(A%26+26)%26,a=-t*Wn,S()};c.addEventListener("click",()=>_(t-1)),d.addEventListener("click",()=>_(t+1)),f.addEventListener("click",()=>{var A;n&&(v.value=((A=k.textContent)==null?void 0:A.trim())??""),n=!1,S()}),x.addEventListener("click",()=>{var A;n||(v.value=((A=k.textContent)==null?void 0:A.trim())??""),n=!0,S()}),v.addEventListener("input",S),o.cells.forEach((A,W)=>A.addEventListener("click",()=>T(W)));let C;const B=A=>{const W=r.getBoundingClientRect();return Math.atan2(A.clientY-(W.top+W.height/2),A.clientX-(W.left+W.width/2))*180/Math.PI};l.addEventListener("pointerdown",A=>{const W=A;C=B(W)-a,l.classList.add("dragging"),r.setPointerCapture(W.pointerId),W.preventDefault()}),r.addEventListener("pointermove",A=>{if(C===void 0)return;a=B(A)-C,l.setAttribute("transform",`rotate(${a})`);const W=Math.round(-a/Wn);if((W%26+26)%26!==t){t=(W%26+26)%26;const R=a;S(),a=R,l.setAttribute("transform",`rotate(${a})`)}});const P=()=>{C!==void 0&&(C=void 0,l.classList.remove("dragging"),_(t))};return r.addEventListener("pointerup",P),r.addEventListener("pointercancel",P),S(),s}function RB(i,e,t){const n=(a,s)=>{const r=(s-90)*Math.PI/180;return`${(a*Math.cos(r)).toFixed(2)} ${(a*Math.sin(r)).toFixed(2)}`};return`M ${n(i,-t)} A ${i} ${i} 0 0 1 ${n(i,t)} L ${n(e,t)} A ${e} ${e} 0 0 0 ${n(e,-t)} Z`}const Hl=i=>p(`web_visubot_part_${i}`),jh=new WeakMap;function Ch(i,e,t,n){const a=document.createElement("div");a.className="visubot-model";const s=document.createElement("div");s.className="visubot-stage";const r=document.createElement("div");r.className="visubot-part-label",r.hidden=!0,s.append(r);const o=(c,d,h)=>{r.hidden=!1,r.textContent=Hl(c),r.style.left=`${Math.min(d+12,s.clientWidth-140)}px`,r.style.top=`${h+12}px`},l=document.createElement("p");l.className="visubot-model-hint hint",l.textContent=p("web_visubot_tap_part"),l.hidden=!!n,a.append(s,l);const u=Q(async()=>{const{Robot3D:c}=await import("./robot3d-FyDAbXTC.js");return{Robot3D:c}},[],import.meta.url).then(({Robot3D:c})=>{const d=new c(s);d.showcase(),d.highlight(i),i.includes("leds")&&d.setLed([40,90,255]),d.focusOn([],e==="unten"||e==="bottom"?"":e,!1,1),d.focusOn(i,e,t);let h;return s.addEventListener("pointerdown",g=>h={x:g.clientX,y:g.clientY}),s.addEventListener("pointerup",g=>{if(!h||Math.hypot(g.clientX-h.x,g.clientY-h.y)>5)return;const f=d.partAt(g.clientX,g.clientY);if(!f)return;if(n)return n(f);d.highlight(f);const x=s.getBoundingClientRect();o(f,g.clientX-x.left,g.clientY-x.top)}),s.addEventListener("pointermove",g=>{if(g.pointerType!=="mouse"||n)return;const f=d.partAt(g.clientX,g.clientY);if(r.hidden=!f,!f)return;const x=s.getBoundingClientRect();o(f,g.clientX-x.left,g.clientY-x.top)}),s.addEventListener("pointerleave",()=>r.hidden=!0),d}).catch(c=>{console.error(c),s.textContent=p("web_visubot_no_3d")}),m={box:a,ready:u,focus:i,view:e};return jh.set(a,m),m}function GB(i,e,t=!1){return Ch(i,e,t).box}function HB(i){const e=i.querySelector(".visubot-model"),t=e&&jh.get(e);for(const n of i.querySelectorAll("[data-robot-part]")){const a=(n.dataset.robotPart??"").split(",").filter(Boolean);if(n.title=a.map(Hl).join(", "),!t)continue;const s=()=>void t.ready.then(o=>o==null?void 0:o.highlight(a)),r=()=>void t.ready.then(o=>o==null?void 0:o.highlight(t.focus));n.addEventListener("mouseenter",s),n.addEventListener("focus",s),n.addEventListener("mouseleave",r),n.addEventListener("blur",r),n.addEventListener("click",()=>{t.ready.then(o=>{o==null||o.highlight(a),o==null||o.focusOn(a,t.view)}),t.box.scrollIntoView({block:"nearest",behavior:"smooth"})})}}function VB(i,e){let t=0;const n=document.createElement("div");n.className="visubot-quiz-question";const a=document.createElement("p");a.className="visubot-quiz-feedback",a.setAttribute("aria-live","polite");const s=()=>{n.innerHTML=zn(`**${t+1}/${i.length}** ${i[t].question}`)},r=Ch([],void 0,!1,l=>{if(!(t>=i.length)){if(r.ready.then(u=>u==null?void 0:u.highlight(l)),l!==i[t].part){a.className="visubot-quiz-feedback wrong",a.textContent=p("web_visubot_quiz_wrong_fmt",Hl(l));return}t++,a.className="visubot-quiz-feedback right",t{u.forEach(v=>{window.clearTimeout(v),window.clearInterval(v)}),u=[]},c=()=>{a.textContent=`${p("web_game_round_fmt",o+1,r)} · ${p("web_game_score_fmt",l)}`},d=()=>{const v=V("button",{class:"primary"},o+1{o++,o{const v=i.rounds[o],w=i.seconds,k=V("div",{class:"learn-bomb-fuse"},V("span",{})),I=V("span",{class:"learn-bomb-time"}),T=V("div",{class:"learn-bomb","aria-live":"polite"},V("span",{class:"learn-bomb-icon","aria-hidden":"true"},"💣"),I,k),S=V("div",{class:"learn-game-feedback",role:"status"}),_=v.code.split(` +`).map((R,ne)=>{const ge=V("button",{class:"ln",type:"button"},R||" ");return ge.disabled=!R.trim(),ge.addEventListener("click",()=>A(ne+1===v.wrongLine?"right":"wrong",ge)),ge}),C=V("div",{class:"learn-game-code learn-bomb-code mono",dir:"ltr"},..._),B=Date.now(),P=()=>{if(!t.isConnected&&Date.now()-B>1e3)return m();const R=Math.max(0,w-(Date.now()-B)/1e3);I.textContent=p("web_game_time_fmt",Math.ceil(R)),k.firstChild.style.width=`${R/w*100}%`,T.classList.toggle("hurry",R<=5),R<=0&&A("time")},A=(R,ne)=>{m(),_.forEach((Z,X)=>{Z.disabled=!0,X+1===v.wrongLine&&Z.classList.add("right")}),ne&&R==="wrong"&&ne.classList.add("wrong");const ge=R==="right";ge&&l++,c(),T.classList.add(ge?"defused":"boom"),T.firstChild.textContent=ge?"✂️":"💥",S.className=`learn-game-feedback ${ge?"right":"wrong"}`;const jt=d();S.replaceChildren(V("p",{},p(ge?"web_game_defused":R==="time"?"web_game_boom_time":"web_game_boom_wrong")),Mn("div",{class:"learn-game-explain"},v.explanation),V("p",{class:"learn-bomb-fix"},`${p("web_game_fix")} `,V("code",{},v.fix.trim())),jt),jt.focus({preventScroll:!0})};s.replaceChildren(T,Mn("p",{class:"learn-game-question"},v.question),C,S),P();const W=window.setInterval(P,200);u.push(W)},g=()=>{const v=i.rounds[o],w=[];v.code.trim()&&w.push(Zu(v.code).element),w.push(Mn("p",{class:"learn-game-question"},v.question),V("p",{class:"learn-order-hint"},p("web_game_order_hint")));const k=V("div",{class:"learn-game-options learn-order"}),I=V("div",{class:"learn-game-feedback",role:"status"});let T=0;const S=qB(v.options.length).map(C=>{const B=V("span",{class:"learn-order-badge","aria-hidden":"true"}),P=V("span",{});P.innerHTML=Fe(v.options[C].text);const A=V("button",{},B,P);return A.addEventListener("click",()=>{if(C!==T)return A.classList.add("wrong"),_(!1);A.classList.add("right"),B.textContent=String(++T),A.disabled=!0,T===v.options.length&&_(!0)}),k.append(A),{k:C,b:A,badge:B}}),_=C=>{for(const{k:P,b:A,badge:W}of[...S].sort((R,ne)=>R.k-ne.k))A.disabled=!0,W.textContent=String(P+1),k.append(A);C&&l++,c(),I.className=`learn-game-feedback ${C?"right":"wrong"}`;const B=d();I.replaceChildren(V("p",{},p(C?"web_game_right":"web_game_wrong_short")),Mn("div",{class:"learn-game-explain"},v.explanation),B),B.focus({preventScroll:!0})};s.replaceChildren(...w,k,I)},f=()=>{if(m(),i.kind==="bombe"||i.kind==="reihenfolge"){c(),i.kind==="bombe"?h():g();return}const v=i.rounds[o];c();const w=Zu(v.code),k=[];let I;i.kind==="zuhoerer"?(I=UB(fh(v.code),w),k.push(V("div",{class:"learn-swing-row"},w.element,I.element)),v.clicks.length&&k.push(V("p",{class:"learn-swing-clicks"},`${p("web_game_clicks")} `,...v.clicks.flatMap((B,P)=>[...P?[" → "]:[],V("code",{},B)])))):v.code.trim()&&k.push(w.element),k.push(Mn("p",{class:"learn-game-question"},v.question));const T=V("div",{class:`learn-game-options ${i.kind==="layout"?"pictures":""}`}),S=V("div",{class:"learn-game-feedback",role:"status"}),_=v.options.map(B=>{const P=V("button",{});return i.kind==="layout"?P.append(YB(B.text)):B.text.includes(` +`)?P.append($B(B.text)):P.innerHTML=Fe(B.text),P.addEventListener("click",()=>C(B.right,P)),T.append(P),P}),C=(B,P)=>{_.forEach((W,R)=>{W.disabled=!0,v.options[R].right&&W.classList.add("right")}),B||P.classList.add("wrong"),B&&l++,c(),S.className=`learn-game-feedback ${B?"right":"wrong"}`;const A=d();S.replaceChildren(V("p",{},p(B?"web_game_right":"web_game_wrong_short")),Mn("div",{class:"learn-game-explain"},v.explanation)),S.append(A),I&&(u=I.replay(v.clicks,()=>A.before(V("p",{class:"learn-swing-try"},p("web_game_try"))))),A.focus({preventScroll:!0})};s.replaceChildren(...k,T,S)},x=()=>{m(),a.textContent="";const v=V("button",{class:"primary"},p("web_game_again"));v.addEventListener("click",()=>{o=l=0,f()}),s.replaceChildren(V("p",{class:"learn-game-result"},p("web_game_done_fmt",l,r)),V("p",{},p(l===r?"web_game_perfect":l>=r*.7?"web_game_good":"web_game_practice_short")),v)},b=V("button",{class:"primary"},p("web_game_start"));return b.addEventListener("click",f),s.append(Mn("p",{},i.intro),b),t}function qB(i){const e=[...Array(i).keys()];for(;e.every((t,n)=>t===n);)for(let t=i-1;t>0;t--){const n=Math.floor(Math.random()*(t+1));[e[t],e[n]]=[e[n],e[t]]}return e}function Zu(i){const e=i.split(` `).map(n=>V("div",{class:"ln"},n||" "));return{element:V("pre",{class:"learn-game-code mono",dir:"ltr"},...e),highlight(n,a){e.forEach((s,r)=>s.classList.toggle("hit",n!==void 0&&r>=n&&r<=(a??n)))}}}function UB(i,e){const t=xh(i),n=V("div",{class:"learn-swing-window",dir:"ltr"});n.append(V("div",{class:"learn-swing-title"},i.title||" "));const a=V("div",{class:"learn-swing-body"}),s=new Map;for(const c of i.labels){const d=V("div",{class:"learn-swing-label"},t.texts[c.name]);s.set(c.name,d),a.append(d)}const r=i.buttons.map(c=>{const d=V("button",{class:"learn-swing-button",disabled:""},t.texts[c.name]);return s.set(c.name,d),a.append(d),d}),o=V("p",{class:"learn-swing-event",role:"status"}),l=V("pre",{class:"learn-swing-console mono",hidden:""});n.append(a,o,l);const u=c=>{var h,g;const d=s.get(c.button);d.classList.add("pressed"),window.setTimeout(()=>d.classList.remove("pressed"),350),e.highlight((h=c.listener)==null?void 0:h.from,(g=c.listener)==null?void 0:g.to),o.textContent=c.listener?p("web_game_event_fmt",d.textContent??""):p("web_game_nobody"),o.className=`learn-swing-event ${c.listener?"heard":"nobody"}`;for(const[f,x]of Object.entries(c.texts)){const b=s.get(f);b&&b.textContent!==x&&(b.textContent=x,b.classList.remove("changed"),b.offsetWidth,b.classList.add("changed"))}c.console.length&&(l.hidden=!1,l.textContent+=c.console.map(f=>`${f} `).join(""))},m=c=>u(bh(i,t,c));return{element:n,replay(c,d){const h=c.map((g,f)=>window.setTimeout(()=>m(g),(f+.3)*Du));return h.push(window.setTimeout(()=>{i.buttons.forEach((g,f)=>{r[f].disabled=!1,r[f].addEventListener("click",()=>u(vh(i,t,g.name)))}),d()},(c.length+.3)*Du)),h}}}function $B(i){return V("pre",{class:"learn-game-file mono",dir:"ltr"},i)}function YB(i){const e=ph(i),t=V("div",{class:"learn-layout-window",dir:"ltr"},V("div",{class:"learn-layout-title"})),n=V("div",{class:`learn-layout-body ${e.kind}`}),a=(s,r)=>V("span",{class:"learn-layout-cell",...r?{style:`grid-area:${r}`}:{}},s);if(e.kind==="border")for(const[s,r]of Object.entries(e.areas))n.append(a(r,s));else if(e.kind==="grid"){const s=Math.max(...e.rows.map(r=>r.length));n.style.gridTemplateColumns=`repeat(${s}, 1fr)`;for(const r of e.rows)for(let o=0;oa(r))));return t.append(n),t}function J(i,e={},...t){const n=document.createElement(i);for(const[a,s]of Object.entries(e))n.setAttribute(a,s);return n.append(...t),n}function bn(i,e,t){const n=J(i,e);return n.innerHTML=Fe(t),n}function Mu(i){return J("pre",{class:"learn-game-code mono",dir:"ltr"},...i.split(` `).map(e=>J("div",{class:"ln"},e||" ")))}function XB(i,e){const t=J("section",{class:"learn-game learn-rescue"}),n=J("div",{class:"learn-game-head"});n.append(J("img",{src:e,alt:"",width:"40",height:"40"}),J("strong",{},i.title));const a=i.stations.length,s=i.stations.map(()=>J("span",{class:"learn-rescue-dot"})),r=J("img",{class:"learn-rescue-ludwig",src:e,alt:"",width:"32",height:"32"}),o=J("span",{class:"learn-rescue-tower","aria-hidden":"true"},"🏰",J("span",{class:"learn-rescue-zora"},"🐐"),J("span",{class:"learn-rescue-fox"},"🦊")),l=J("span",{class:"learn-rescue-free"},"🐐"),u=J("div",{class:"learn-rescue-path","aria-hidden":"true"},r,...s,o),m=J("p",{class:"learn-game-status"}),c=J("div",{class:"learn-game-stage"}),d=KB(i);t.append(n,u,m,c);let h=0;const g=()=>{s.forEach((I,T)=>I.classList.toggle("done",T{const I=[...i.alphabet].map((T,S)=>J("span",{class:"learn-rescue-letter"},J("b",{},T),J("small",{},String(S))));return{element:J("div",{class:"learn-rescue-alphabet mono",dir:"ltr"},...I),cells:I}},x=I=>{const T=i.stations[I];m.textContent=p("web_learn_rescue_station_fmt",I+1,a,T.name);const S=f(),_=J("input",{type:"text",inputmode:"numeric",autocomplete:"off",class:"learn-rescue-number mono","aria-label":p("web_learn_rescue_number")}),C=J("button",{class:"primary"},p("web_learn_check")),B=J("div",{class:"learn-game-feedback",role:"status"}),P=()=>{const A=_.value.trim();if(!/^-?\d+$/.test(A)){B.className="learn-game-feedback wrong",B.replaceChildren(J("p",{},p("web_learn_rescue_not_number")));return}if(Number(A)!==T.answer){B.className="learn-game-feedback wrong",B.replaceChildren(J("p",{},p("web_learn_rescue_wrong")),...T.hint?[bn("div",{class:"learn-game-explain"},`**${p("web_learn_hint")}:** ${T.hint}`)]:[]),_.select();return}_.disabled=C.disabled=!0;const W=i.alphabet.charAt(T.answer);S.cells[T.answer].classList.add("hit"),d.give(T.row,T.col,W),h++,g();const R=I+1===a,ne=J("button",{class:"primary"},p(R?"web_learn_rescue_to_crossword":"web_game_next"));ne.addEventListener("click",()=>R?b():x(I+1)),B.className="learn-game-feedback right",B.replaceChildren(J("p",{},p("web_game_right")),J("p",{class:"learn-rescue-charat mono",dir:"ltr"},`alphabet.charAt(${T.answer})`,J("span",{"aria-hidden":"true"}," → "),J("code",{},`'${W}'`)),bn("div",{class:"learn-game-explain"},T.explanation),J("p",{class:"learn-rescue-moved"},p("web_learn_rescue_letter_moved")),ne),ne.focus({preventScroll:!0})};C.addEventListener("click",P),_.addEventListener("keydown",A=>{A.key==="Enter"&&P()}),c.replaceChildren(Mu(T.code),bn("p",{class:"learn-game-question"},T.question),J("div",{class:"learn-rescue-answer"},_,C),B,J("p",{class:"learn-rescue-label"},p("web_learn_rescue_alphabet")),Mu(`String alphabet = "${i.alphabet}";`),S.element,d.element),_.focus({preventScroll:!0})},b=()=>{m.textContent=p("web_learn_rescue_crossword");const I=J("div",{class:"learn-game-feedback",role:"status"}),T=J("button",{class:"primary"},p("web_learn_check"));T.addEventListener("click",()=>{if(!d.check()){I.className="learn-game-feedback wrong",I.replaceChildren(J("p",{},p("web_learn_rescue_cw_wrong")));return}T.disabled=!0,d.lock();const S=J("button",{class:"primary"},p("web_learn_rescue_to_gate"));S.addEventListener("click",v),I.className="learn-game-feedback right",I.replaceChildren(J("p",{},p("web_learn_rescue_cw_done")),S),S.focus({preventScroll:!0})}),d.unlock(),c.replaceChildren(bn("p",{},i.crosswordText),d.element,T,I),d.focusFirst()},v=()=>{m.textContent=p("web_learn_rescue_gate");const I=J("input",{type:"text",autocomplete:"off",autocapitalize:"off",spellcheck:"false",class:"learn-rescue-word mono",size:String(i.keyword.length+2),"aria-label":p("web_learn_rescue_word")}),T=i.gateCode.split(` `).map(B=>{const P=B.indexOf(os);return P<0?J("div",{class:"ln"},B||" "):J("div",{class:"ln"},B.slice(0,P),I,B.slice(P+os.length))}),S=J("button",{class:"primary"},p("web_learn_rescue_open")),_=J("div",{class:"learn-game-feedback",role:"status"}),C=()=>{const B=I.value.trim();if(B!==i.keyword){const A=B.toUpperCase()===i.keyword.toUpperCase();_.className="learn-game-feedback wrong",_.replaceChildren(J("p",{},p(A?"web_learn_rescue_gate_case":"web_learn_rescue_gate_wrong"))),I.select();return}I.disabled=S.disabled=!0,t.classList.add("freed"),r.after(l),m.textContent="";const P=J("button",{},p("web_game_again"));P.addEventListener("click",w),_.className="learn-game-feedback right",_.replaceChildren(J("p",{},p("web_learn_rescue_freed")),bn("div",{class:"learn-game-explain"},i.end),P)};S.addEventListener("click",C),I.addEventListener("keydown",B=>{B.key==="Enter"&&C()}),c.replaceChildren(bn("p",{},i.gateText),J("div",{class:"learn-game-code mono learn-rescue-gate",dir:"ltr"},...T),S,_),I.focus({preventScroll:!0})},w=()=>{h=0,t.classList.remove("freed"),l.remove(),d.reset(),g(),x(0)},k=J("button",{class:"primary"},p("web_game_start"));return k.addEventListener("click",w),c.append(bn("p",{},i.intro),k),t}function KB(i){const e=dB(i),t=new Map(i.solution.map((g,f)=>[`${g.row} ${g.col}`,f])),n=new Map;for(const g of i.words)n.set(`${g.row} ${g.col}`,g.number);const a=new Map,s=J("div",{class:"learn-cw-grid",dir:"ltr"});s.style.gridTemplateColumns=`repeat(${i.cols}, var(--cw-cell))`;let r=!0;const o=(g,f)=>i.words.filter(x=>x.across?x.row===g&&f>=x.col&&f=x.row&&g{var v;const b=r?`${g} ${f+x}`:`${g+x} ${f}`;(v=a.get(b))==null||v.focus()};e.forEach((g,f)=>g.forEach((x,b)=>{if(!x)return s.append(J("span",{class:"learn-cw-empty"}));const v=`${f} ${b}`,w=J("input",{type:"text",maxlength:"1",autocomplete:"off",autocapitalize:"characters",spellcheck:"false","aria-label":p("web_learn_rescue_cell_fmt",f+1,b+1)});w.disabled=!0,w.addEventListener("focus",()=>{const S=o(f,b);S.some(_=>_.across===r)||(r=S[0].across),w.select()}),w.addEventListener("input",()=>{w.value=w.value.slice(-1).toUpperCase(),w.classList.remove("wrong"),c(),w.value&&l(f,b,1)}),w.addEventListener("keydown",S=>{if(S.key==="Backspace"&&!w.value)l(f,b,-1);else if(S.key==="ArrowRight"||S.key==="ArrowLeft")r=!0,l(f,b,S.key==="ArrowRight"?1:-1);else if(S.key==="ArrowDown"||S.key==="ArrowUp")r=!1,l(f,b,S.key==="ArrowDown"?1:-1);else return;S.preventDefault()}),a.set(v,w);const k=t.get(v),I=J("span",{class:`learn-cw-cell${k!==void 0?" key":""}`}),T=n.get(v);T&&I.append(J("small",{class:"learn-cw-number"},String(T))),k!==void 0&&I.append(J("small",{class:"learn-cw-keyindex"},String(k+1))),I.append(w),s.append(I)}));const u=g=>{const f=J("ol",{class:"learn-cw-clues"});for(const x of i.words.filter(b=>b.across===g).sort((b,v)=>b.number-v.number)){const b=bn("li",{value:String(x.number)},`${x.clue} (${x.word.length})`);b.addEventListener("click",()=>{var v;r=x.across,(v=a.get(`${x.row} ${x.col}`))==null||v.focus()}),f.append(b)}return J("div",{},J("strong",{},p(g?"web_learn_rescue_across":"web_learn_rescue_down")),f)},m=i.solution.map(()=>J("span",{class:"learn-cw-keybox"})),c=()=>i.solution.forEach((g,f)=>m[f].textContent=a.get(`${g.row} ${g.col}`).value||" "),d=J("div",{class:"learn-cw"},J("div",{class:"learn-cw-board"},s,J("p",{class:"learn-cw-keyword"},`${p("web_learn_rescue_keyword")} `,J("span",{class:"mono",dir:"ltr"},...m))),J("div",{class:"learn-cw-cluebox"},u(!0),u(!1))),h=new Set;return{element:d,give(g,f,x){const b=a.get(`${g} ${f}`);b.value=x,b.parentElement.classList.add("given","arrived"),h.add(`${g} ${f}`),c()},unlock(){for(const[g,f]of a)f.disabled=h.has(g)},lock(){for(const g of a.values())g.disabled=!0},focusFirst(){var g;(g=[...a].find(([f])=>!h.has(f)))==null||g[1].focus({preventScroll:!0})},check(){let g=!0;for(const[f,x]of a){const[b,v]=f.split(" ").map(Number),w=x.value!==e[b][v];x.classList.toggle("wrong",w),w&&(g=!1)}return g},reset(){h.clear();for(const g of a.values())g.value="",g.disabled=!0,g.classList.remove("wrong"),g.parentElement.classList.remove("given","arrived");c()}}}function vt(i,e={},...t){const n=document.createElement(i);for(const[a,s]of Object.entries(e))n.setAttribute(a,s);return n.append(...t),n}function Lu(i,e,t){const n=vt(i,e);return n.innerHTML=Fe(t),n}function eD(i){const e=vt("section",{class:"learn-cloze"});e.append(vt("strong",{class:"learn-cloze-title"},i.title)),i.task&&e.append(Lu("p",{},i.task)),e.append(vt("p",{class:"learn-cloze-hint"},p("web_learn_cloze_hint")));const t=[];for(const m of i.blocks){const c=vt("pre",{class:"learn-cloze-code mono",dir:"ltr"});for(const d of m){const h=vt("div",{class:"ln"});for(const g of d){if(typeof g=="string"){h.append(g);continue}const f=vt("input",{type:"text",class:"learn-cloze-gap mono",autocomplete:"off",autocapitalize:"off",autocorrect:"off",spellcheck:"false",enterkeyhint:"done","aria-label":`${t.length+1}`});f.style.width=`${Math.max(3,...g.answers.map(x=>x.length))+1}ch`,t.push({input:f,answers:g.answers}),h.append(f)}d.length||h.append(` -`),c.append(h)}e.append(c)}const n=vt("p",{class:"learn-cloze-status",role:"status"}),a=i.explanation?Lu("p",{class:"learn-explanation"},i.explanation):void 0;a&&(a.hidden=!0);const s=vt("button",{class:"learn-cloze-check"},p("web_learn_check")),r=vt("button",{},p("web_learn_cloze_solution")),o=vt("button",{},p("web_learn_cloze_again"));r.hidden=!0,o.hidden=!0;const l=vt("div",{class:"learn-cloze-actions"},s,r,o);e.append(l,n),a&&e.append(a);const u=()=>{var d;let m=0;for(const h of t){const g=bB(h.answers,h.input.value);h.input.classList.toggle("right",g),h.input.classList.toggle("wrong",!g),g&&m++}const c=m===t.length;n.textContent=c?p("web_learn_cloze_all_right"):p("web_learn_cloze_score_fmt",m,t.length),n.className=`learn-cloze-status ${c?"right":"wrong"}`,a&&(a.hidden=!c),c?(t.forEach(h=>h.input.disabled=!0),s.hidden=!0,o.hidden=!1):(r.hidden=!1,(d=t.find(h=>h.input.classList.contains("wrong")))==null||d.input.focus())};return s.addEventListener("click",u),r.addEventListener("click",()=>{for(const m of t)m.input.value=m.answers[0],m.input.classList.remove("right","wrong"),m.input.classList.add("shown"),m.input.disabled=!0;n.textContent="",n.className="learn-cloze-status",a&&(a.hidden=!1),s.hidden=!0,r.hidden=!0,o.hidden=!1}),o.addEventListener("click",()=>{var m;for(const c of t)c.input.value="",c.input.classList.remove("right","wrong","shown"),c.input.disabled=!1;n.textContent="",n.className="learn-cloze-status",a&&(a.hidden=!0),s.hidden=!1,r.hidden=!0,o.hidden=!0,(m=t[0])==null||m.input.focus()}),t.forEach((m,c)=>{m.input.addEventListener("input",()=>m.input.classList.remove("right","wrong")),m.input.addEventListener("keydown",d=>{d.key==="Enter"&&(d.preventDefault(),c[...o.querySelectorAll("strong")])){const o=vu(e),l=o==null?void 0:o.exec(r.textContent??""),u=l?yu(e,l[0]):void 0;u&&n.add(u)}let a=e.filter(r=>!n.has(r));for(const r of t){const o=document.createTreeWalker(r,NodeFilter.SHOW_TEXT),l=[];for(;o.nextNode();){const u=o.currentNode;(s=u.parentElement)!=null&&s.closest(tD)||l.push(u)}for(let u of l)for(;;){const m=vu(a),c=m==null?void 0:m.exec(u.data),d=c?yu(a,c[0]):void 0;if(!c||!d)break;const h=u.splitText(c.index);u=h.splitText(c[0].length);const g=document.createElement("span");g.className="term",g.tabIndex=0,g.setAttribute("role","button"),g.setAttribute("aria-describedby","term-tip"),g.dataset.term=d.term,g.dataset.text=d.text,h.replaceWith(g),g.append(h),a=a.filter(f=>f!==d)}}}function nD(i){const e=document.createElement("div");e.id="term-tip",e.className="term-tip",e.setAttribute("role","tooltip"),e.hidden=!0,document.body.append(e);let t,n=!1;const a=o=>{t=o,e.replaceChildren();const l=document.createElement("strong");l.textContent=o.dataset.term??"",e.append(l,document.createTextNode(" "+(o.dataset.text??""))),e.hidden=!1;const u=o.getBoundingClientRect(),m=e.offsetWidth,c=e.offsetHeight,d=Math.max(8,Math.min(u.left,window.innerWidth-m-8)),h=u.bottom+6;e.style.left=`${d}px`,e.style.top=`${h+c>window.innerHeight-8?Math.max(8,u.top-c-6):h}px`,o.setAttribute("aria-expanded","true")},s=()=>{t==null||t.setAttribute("aria-expanded","false"),t=void 0,n=!1,e.hidden=!0},r=o=>{var l,u;return((u=(l=o.target)==null?void 0:l.closest)==null?void 0:u.call(l,".term"))??void 0};return i.addEventListener("pointerover",o=>{const l=r(o);l&&o.pointerType==="mouse"&&!n&&a(l)}),i.addEventListener("pointerout",o=>{r(o)&&o.pointerType==="mouse"&&!n&&s()}),i.addEventListener("click",o=>{const l=r(o);if(l){if(n&&t===l)return s();a(l),n=!0}}),i.addEventListener("focusin",o=>{const l=r(o);l&&!n&&a(l)}),i.addEventListener("focusout",o=>{r(o)&&!n&&s()}),i.addEventListener("keydown",o=>{const l=r(o);o.key==="Escape"&&t?s():l&&(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),l.click())}),i.addEventListener("scroll",s,!0),document.addEventListener("pointerdown",o=>{t&&!r(o)&&!e.contains(o.target)&&s()}),{hide:s}}const Bh={leiste:".topbar > .toolbar",werkzeuge:".diagram-tools",dateien:".files-rail, .files",codelive:".live-rail, .livecode",ausfuehren:"[data-run=play]",konsole:".livecode .console",einzelschritt:"[data-run=step]",elemente:".palette",struktogramm:".canvas",objektinspektor:".inspector",reiter:".tabs",titel:".caption",neu:"[data-action=new]",oeffnen:"[data-action=open]",speichern:"[data-action=save]",exportieren:"[data-action=export]",rueckgaengig:"[data-action=undo]",textgroesse:"[data-action=settings]",einstellungen:"[data-action=settings]",lernen:".learn .learn-hide",code:"[data-action=code]",simulation:"[data-action=simulate]"},iD=new Set(["werkzeuge","elemente","struktogramm","objektinspektor","reiter","titel","rueckgaengig","exportieren","code","simulation"]),aD=new Set(["ausfuehren","konsole","einzelschritt"]);function Vl(i,e){return[...i.querySelectorAll(".ui-pointer")].some(t=>e.has(t.dataset.target??""))}function sD(i){return Vl(i,new Set(["dateien"]))}function rD(i){return Vl(i,iD)}function oD(i){return Vl(i,aD)}function Eu(i){for(const e of i.querySelectorAll('a[href^="#zeige-"]')){const t=e.getAttribute("href").slice(7);if(!(t in Bh))continue;const n=document.createElement("span");n.className="ui-pointer",n.tabIndex=0,n.setAttribute("role","button"),n.dataset.target=t,n.append(...e.childNodes),e.replaceWith(n)}}function lD(i){let e,t;const n=()=>{e==null||e.classList.remove("ui-spot"),e=void 0,window.clearTimeout(t)},a=(r,o)=>{n();const l=[...document.querySelectorAll(Bh[r.dataset.target??""]??":not(*)")].find(u=>u.getClientRects().length>0);l&&(e=l,l.classList.add("ui-spot"),o&&(t=window.setTimeout(n,2500)))},s=r=>{var o,l;return((l=(o=r.target)==null?void 0:o.closest)==null?void 0:l.call(o,".ui-pointer"))??void 0};return i.addEventListener("pointerover",r=>{const o=s(r);o&&r.pointerType==="mouse"&&a(o,!1)}),i.addEventListener("pointerout",r=>{s(r)&&r.pointerType==="mouse"&&n()}),i.addEventListener("click",r=>{const o=s(r);o&&a(o,!0)}),i.addEventListener("focusin",r=>{const o=s(r);o&&a(o,!1)}),i.addEventListener("focusout",r=>{s(r)&&n()}),i.addEventListener("keydown",r=>{const o=s(r);o&&(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),a(o,!0))}),{off:n}}const $t='',uD=()=>{const i=[];for(const e of Zt){const t=i.at(-1);t&&t.name===e.section?t.lessons.push(e):i.push({name:e.section,lessons:[e]})}return i};function O(i,e={},...t){const n=document.createElement(i);for(const[a,s]of Object.entries(e))n.setAttribute(a,s);return n.append(...t),n}function mt(i,e,t){const n=O(i,e);return n.innerHTML=t,n}const mD=i=>p(`element_${z[i]}`);function cD(i){return{caption:i,elements:[ve(z.anweisung,{textLines:["ø"]})]}}function Nu(i){const e=i.start?U1(i.start):void 0;return e?{...e,caption:e.caption||i.title}:cD(i.title)}class dD{constructor(e){y(this,"element");y(this,"tab","lessons");y(this,"returnTo");y(this,"lessonId");y(this,"taskId");y(this,"body");y(this,"tips");y(this,"pointers");this.host=e,this.element=O("aside",{class:"learn","aria-label":p("web_learn_title")}),this.tips=nD(this.element),this.pointers=lD(this.element),ls(Su(Yn())),this.restore()}restore(){const e=ce.view();e&&(this.tab=["lessons","tasks","reference"].find(t=>t===e.tab)??"lessons",this.lessonId=Zt.some(t=>t.id===e.lesson)?e.lesson:void 0,this.taskId=x1.some(t=>t.id===e.task)?e.task:void 0),this.render()}render(){this.tips.hide(),this.pointers.off(),ls(Su(Yn()));const e=O("div",{class:"segmented learn-tabs",role:"tablist"});for(const[a,s]of[["lessons",p("web_learn_lessons")],["tasks",p("web_learn_tasks")],["reference",p("web_learn_reference")]]){const r=O("button",{role:"tab","aria-pressed":String(this.tab===a),"data-learn-tab":a},s);r.addEventListener("click",()=>{this.tab===a&&(a==="lessons"&&(this.lessonId=void 0),a==="tasks"&&(this.taskId=void 0)),this.tab=a,this.persist(),this.render()}),e.append(r)}const t=mt("button",{class:"learn-hide",title:p("web_learn_hide"),"aria-label":p("web_learn_hide")},$t);t.addEventListener("click",()=>this.host.collapse());const n=O("div",{class:"learn-head"},e,t);if(this.body=O("div",{class:"learn-body"}),this.element.replaceChildren(n,this.body),this.tab==="lessons"){const a=Zt.find(s=>s.id===this.lessonId);a?this.renderLesson(a):this.renderLessonList()}else if(this.tab==="tasks"){const a=x1.find(s=>s.id===this.taskId);a?this.renderTask(a):this.renderTaskList()}else{const a=Da.map(r=>`- **${r.term}:** ${r.text}`).join(` +`),c.append(h)}e.append(c)}const n=vt("p",{class:"learn-cloze-status",role:"status"}),a=i.explanation?Lu("p",{class:"learn-explanation"},i.explanation):void 0;a&&(a.hidden=!0);const s=vt("button",{class:"learn-cloze-check"},p("web_learn_check")),r=vt("button",{},p("web_learn_cloze_solution")),o=vt("button",{},p("web_learn_cloze_again"));r.hidden=!0,o.hidden=!0;const l=vt("div",{class:"learn-cloze-actions"},s,r,o);e.append(l,n),a&&e.append(a);const u=()=>{var d;let m=0;for(const h of t){const g=bB(h.answers,h.input.value);h.input.classList.toggle("right",g),h.input.classList.toggle("wrong",!g),g&&m++}const c=m===t.length;n.textContent=c?p("web_learn_cloze_all_right"):p("web_learn_cloze_score_fmt",m,t.length),n.className=`learn-cloze-status ${c?"right":"wrong"}`,a&&(a.hidden=!c),c?(t.forEach(h=>h.input.disabled=!0),s.hidden=!0,o.hidden=!1):(r.hidden=!1,(d=t.find(h=>h.input.classList.contains("wrong")))==null||d.input.focus())};return s.addEventListener("click",u),r.addEventListener("click",()=>{for(const m of t)m.input.value=m.answers[0],m.input.classList.remove("right","wrong"),m.input.classList.add("shown"),m.input.disabled=!0;n.textContent="",n.className="learn-cloze-status",a&&(a.hidden=!1),s.hidden=!0,r.hidden=!0,o.hidden=!1}),o.addEventListener("click",()=>{var m;for(const c of t)c.input.value="",c.input.classList.remove("right","wrong","shown"),c.input.disabled=!1;n.textContent="",n.className="learn-cloze-status",a&&(a.hidden=!0),s.hidden=!1,r.hidden=!0,o.hidden=!0,(m=t[0])==null||m.input.focus()}),t.forEach((m,c)=>{m.input.addEventListener("input",()=>m.input.classList.remove("right","wrong")),m.input.addEventListener("keydown",d=>{d.key==="Enter"&&(d.preventDefault(),c[...o.querySelectorAll("strong")])){const o=vu(e),l=o==null?void 0:o.exec(r.textContent??""),u=l?yu(e,l[0]):void 0;u&&n.add(u)}let a=e.filter(r=>!n.has(r));for(const r of t){const o=document.createTreeWalker(r,NodeFilter.SHOW_TEXT),l=[];for(;o.nextNode();){const u=o.currentNode;(s=u.parentElement)!=null&&s.closest(tD)||l.push(u)}for(let u of l)for(;;){const m=vu(a),c=m==null?void 0:m.exec(u.data),d=c?yu(a,c[0]):void 0;if(!c||!d)break;const h=u.splitText(c.index);u=h.splitText(c[0].length);const g=document.createElement("span");g.className="term",g.tabIndex=0,g.setAttribute("role","button"),g.setAttribute("aria-describedby","term-tip"),g.dataset.term=d.term,g.dataset.text=d.text,h.replaceWith(g),g.append(h),a=a.filter(f=>f!==d)}}}function nD(i){const e=document.createElement("div");e.id="term-tip",e.className="term-tip",e.setAttribute("role","tooltip"),e.hidden=!0,document.body.append(e);let t,n=!1;const a=o=>{t=o,e.replaceChildren();const l=document.createElement("strong");l.textContent=o.dataset.term??"",e.append(l,document.createTextNode(" "+(o.dataset.text??""))),e.hidden=!1;const u=o.getBoundingClientRect(),m=e.offsetWidth,c=e.offsetHeight,d=Math.max(8,Math.min(u.left,window.innerWidth-m-8)),h=u.bottom+6;e.style.left=`${d}px`,e.style.top=`${h+c>window.innerHeight-8?Math.max(8,u.top-c-6):h}px`,o.setAttribute("aria-expanded","true")},s=()=>{t==null||t.setAttribute("aria-expanded","false"),t=void 0,n=!1,e.hidden=!0},r=o=>{var l,u;return((u=(l=o.target)==null?void 0:l.closest)==null?void 0:u.call(l,".term"))??void 0};return i.addEventListener("pointerover",o=>{const l=r(o);l&&o.pointerType==="mouse"&&!n&&a(l)}),i.addEventListener("pointerout",o=>{r(o)&&o.pointerType==="mouse"&&!n&&s()}),i.addEventListener("click",o=>{const l=r(o);if(l){if(n&&t===l)return s();a(l),n=!0}}),i.addEventListener("focusin",o=>{const l=r(o);l&&!n&&a(l)}),i.addEventListener("focusout",o=>{r(o)&&!n&&s()}),i.addEventListener("keydown",o=>{const l=r(o);o.key==="Escape"&&t?s():l&&(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),l.click())}),i.addEventListener("scroll",s,!0),document.addEventListener("pointerdown",o=>{t&&!r(o)&&!e.contains(o.target)&&s()}),{hide:s}}const Bh={leiste:".topbar > .toolbar",werkzeuge:".diagram-tools",dateien:".files-rail, .files",codelive:".live-rail, .livecode",ausfuehren:"[data-run=play]",konsole:".livecode .console",einzelschritt:"[data-run=step]",elemente:".palette",struktogramm:".canvas",objektinspektor:".inspector",reiter:".tabs",titel:".caption",neu:"[data-action=new]",oeffnen:"[data-action=open]",speichern:"[data-action=save]",exportieren:"[data-action=export]",rueckgaengig:"[data-action=undo]",textgroesse:"[data-action=settings]",einstellungen:"[data-action=settings]",lernen:".learn .learn-hide",code:"[data-action=code]",simulation:"[data-action=simulate]"},iD=new Set(["werkzeuge","elemente","struktogramm","objektinspektor","reiter","titel","rueckgaengig","exportieren","code","simulation"]),aD=new Set(["ausfuehren","konsole","einzelschritt"]);function Vl(i,e){return[...i.querySelectorAll(".ui-pointer")].some(t=>e.has(t.dataset.target??""))}function sD(i){return Vl(i,new Set(["dateien"]))}function rD(i){return Vl(i,iD)}function oD(i){return Vl(i,aD)}function Eu(i){for(const e of i.querySelectorAll('a[href^="#zeige-"]')){const t=e.getAttribute("href").slice(7);if(!(t in Bh))continue;const n=document.createElement("span");n.className="ui-pointer",n.tabIndex=0,n.setAttribute("role","button"),n.dataset.target=t,n.append(...e.childNodes),e.replaceWith(n)}}function lD(i){let e,t;const n=()=>{e==null||e.classList.remove("ui-spot"),e=void 0,window.clearTimeout(t)},a=(r,o)=>{n();const l=[...document.querySelectorAll(Bh[r.dataset.target??""]??":not(*)")].find(u=>u.getClientRects().length>0);l&&(e=l,l.classList.add("ui-spot"),o&&(t=window.setTimeout(n,2500)))},s=r=>{var o,l;return((l=(o=r.target)==null?void 0:o.closest)==null?void 0:l.call(o,".ui-pointer"))??void 0};return i.addEventListener("pointerover",r=>{const o=s(r);o&&r.pointerType==="mouse"&&a(o,!1)}),i.addEventListener("pointerout",r=>{s(r)&&r.pointerType==="mouse"&&n()}),i.addEventListener("click",r=>{const o=s(r);o&&a(o,!0)}),i.addEventListener("focusin",r=>{const o=s(r);o&&a(o,!1)}),i.addEventListener("focusout",r=>{s(r)&&n()}),i.addEventListener("keydown",r=>{const o=s(r);o&&(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),a(o,!0))}),{off:n}}const Yt='',uD=()=>{const i=[];for(const e of Zt){const t=i.at(-1);t&&t.name===e.section?t.lessons.push(e):i.push({name:e.section,lessons:[e]})}return i};function O(i,e={},...t){const n=document.createElement(i);for(const[a,s]of Object.entries(e))n.setAttribute(a,s);return n.append(...t),n}function mt(i,e,t){const n=O(i,e);return n.innerHTML=t,n}const mD=i=>p(`element_${z[i]}`);function cD(i){return{caption:i,elements:[ve(z.anweisung,{textLines:["ø"]})]}}function Nu(i){const e=i.start?U1(i.start):void 0;return e?{...e,caption:e.caption||i.title}:cD(i.title)}class dD{constructor(e){y(this,"element");y(this,"tab","lessons");y(this,"returnTo");y(this,"lessonId");y(this,"taskId");y(this,"body");y(this,"tips");y(this,"pointers");this.host=e,this.element=O("aside",{class:"learn","aria-label":p("web_learn_title")}),this.tips=nD(this.element),this.pointers=lD(this.element),ls(Su(Xn())),this.restore()}restore(){const e=ce.view();e&&(this.tab=["lessons","tasks","reference"].find(t=>t===e.tab)??"lessons",this.lessonId=Zt.some(t=>t.id===e.lesson)?e.lesson:void 0,this.taskId=x1.some(t=>t.id===e.task)?e.task:void 0),this.render()}render(){this.tips.hide(),this.pointers.off(),ls(Su(Xn()));const e=O("div",{class:"segmented learn-tabs",role:"tablist"});for(const[a,s]of[["lessons",p("web_learn_lessons")],["tasks",p("web_learn_tasks")],["reference",p("web_learn_reference")]]){const r=O("button",{role:"tab","aria-pressed":String(this.tab===a),"data-learn-tab":a},s);r.addEventListener("click",()=>{this.tab===a&&(a==="lessons"&&(this.lessonId=void 0),a==="tasks"&&(this.taskId=void 0)),this.tab=a,this.persist(),this.render()}),e.append(r)}const t=mt("button",{class:"learn-hide",title:p("web_learn_hide"),"aria-label":p("web_learn_hide")},Yt);t.addEventListener("click",()=>this.host.collapse());const n=O("div",{class:"learn-head"},e,t);if(this.body=O("div",{class:"learn-body"}),this.element.replaceChildren(n,this.body),this.tab==="lessons"){const a=Zt.find(s=>s.id===this.lessonId);a?this.renderLesson(a):this.renderLessonList()}else if(this.tab==="tasks"){const a=x1.find(s=>s.id===this.taskId);a?this.renderTask(a):this.renderTaskList()}else{const a=Da.map(r=>`- **${r.term}:** ${r.text}`).join(` `),s=mt("div",{class:"learn-text learn-reference"},zn(`${Ba} ## ${p("web_learn_terms")} -${a}`));this.body.append(s),this.foldReference(s)}}foldReference(e){const t="visustruct.reference.open";let n=[];try{n=JSON.parse(localStorage.getItem(t)??"[]")}catch{}for(const a of[...e.querySelectorAll("h2")]){const s=a.textContent??"",r=O("details",{class:"reference-group"});r.open=n.includes(s);const o=O("summary",{},s);for(a.replaceWith(r),r.append(o);r.nextSibling&&r.nextSibling.nodeName!=="H2";)r.append(r.nextSibling);r.addEventListener("toggle",()=>{n=r.open?[...new Set([...n,s])]:n.filter(l=>l!==s);try{localStorage.setItem(t,JSON.stringify(n))}catch{}})}}showReference(){this.tab="reference",this.persist(),this.render()}persist(){ce.setView({tab:this.tab,lesson:this.lessonId,task:this.taskId})}openLesson(e){this.tab="lessons",this.lessonId=e,this.returnTo=void 0,this.persist(),this.render(),this.body.scrollTop=0}renderLessonList(){this.body.append(O("p",{class:"hint"},p("web_learn_intro")));for(const e of uD()){this.body.append(O("h3",{class:"learn-section"},e.name));const t=O("ol",{class:"learn-list"});for(const n of e.lessons){const a=ce.lesson(n.id),s=a.done?"✓":a.step>0?p("web_learn_step_of_fmt",a.step+1,n.steps.length):"",r=O("button",{class:"learn-item"+(a.done?" done":""),"data-lesson":n.id},O("span",{class:"learn-num"},String(n.number)),O("span",{class:"learn-item-text"},O("strong",{},n.title),O("small",{},n.summary)),O("span",{class:"learn-status"},s));r.addEventListener("click",()=>this.openLesson(n.id)),t.append(O("li",{},r))}this.body.append(t)}this.body.append(this.renderTeacherBox())}renderLesson(e){var c;const t=ce.lesson(e.id),n=Math.min(t.step,e.steps.length-1),a=e.steps[n],s=O("button",{class:"learn-back"},`← ${p("web_learn_all_lessons")}`);s.addEventListener("click",()=>this.openLesson(void 0));const r=O("nav",{class:"learn-progress","aria-label":p("web_learn_step_of_fmt",n+1,e.steps.length)});r.append(...e.steps.map((d,h)=>{const g=p("web_learn_step_fmt",h+1,d.title),f=hthis.goToStep(e,h)),x})),this.body.append(s,O("p",{class:"learn-kicker"},`${p("web_learn_lesson_fmt",e.number)} · ${e.section}`),O("h2",{class:"learn-title"},O("span",{class:"learn-num","aria-hidden":"true"},String(e.number)),e.title),r,O("h3",{class:"learn-step-title"},`${n+1}. ${a.title}`));const o=((c=this.returnTo)==null?void 0:c.lesson)===e.id&&this.returnTo.step!==n?this.returnTo:void 0,l=()=>{const d=O("button",{class:"learn-return"},`↩ ${p("web_learn_back_to_checklist")}`);return d.addEventListener("click",()=>{this.returnTo=void 0,this.goToStep(e,o.step),this.body.scrollTop=o.scroll}),d};o&&this.body.append(l()),a.blocks.forEach((d,h)=>this.body.append(this.renderBlock(d,`${n}-${h}`,e))),Eu(this.body),HB(this.body),this.openNeededColumns(a.blocks),Wu(this.body,Da);const u=O("div",{class:"learn-nav"}),m=O("button",{},`← ${p("web_learn_back")}`);if(m.disabled=n===0,m.addEventListener("click",()=>this.goToStep(e,n-1)),u.append(m),nthis.goToStep(e,n+1)),u.append(d)}else{const d=O("button",{class:"primary"},t.done?`✓ ${p("web_learn_done")}`:p("web_learn_finish"));d.addEventListener("click",()=>{ce.updateLesson(e.id,{done:!0});const h=Zt.find(g=>g.number===e.number+1);this.openLesson(h==null?void 0:h.id)}),u.append(d)}this.body.append(u),o&&this.body.append(l())}goToStep(e,t){ce.updateLesson(e.id,{step:t}),this.render(),this.body.scrollTop=0}openNeededColumns(e){const t=e.flatMap(n=>n.kind==="exercise"?[n.exercise]:[]);rD(this.body)?this.host.showEditor():sD(this.body)?this.host.showFiles():t.some(n=>n.code!=="java")?this.host.showEditor():(t.length>0||this.body.querySelector(".lesson-code[data-lang=java]"))&&this.host.showJava(),oD(this.body)&&this.host.showLiveCode()}renderTaskList(){this.body.append(O("p",{class:"hint"},p("web_learn_tasks_intro")));const e=O("ul",{class:"learn-list"});for(const t of x1){const n=this.taskExercises(t),a=n.length>0&&n.every(o=>ce.exercise(o.id).done),s=Zt.find(o=>o.number===t.after),r=O("button",{class:"learn-item"+(a?" done":""),"data-task":t.id},O("span",{class:"learn-num","aria-label":p("web_learn_level_fmt",t.level)},"★".repeat(t.level)),O("span",{class:"learn-item-text"},O("strong",{},t.title),O("small",{},s?p("web_learn_after_fmt",s.number,s.title):"")),O("span",{class:"learn-status"},a?"✓":""));r.addEventListener("click",()=>{this.taskId=t.id,this.persist(),this.render(),this.body.scrollTop=0}),e.append(O("li",{},r))}this.body.append(e,this.renderTeacherBox())}renderTeacherBox(){const e=O("details",{class:"learn-teacher"},O("summary",{},p("web_learn_teacher")));if(Au()){e.setAttribute("open","");const s=O("button",{},p("web_learn_teacher_off"));return s.addEventListener("click",()=>{LB(),this.render()}),e.append(O("p",{},p("web_learn_teacher_on")),s),e}const t=O("input",{type:"password",autocomplete:"off","aria-label":p("web_learn_teacher_code"),placeholder:p("web_learn_teacher_code")}),n=O("p",{class:"learn-result",role:"status"}),a=O("form",{class:"group"},t,O("button",{type:"submit"},p("web_learn_teacher_unlock")));return a.addEventListener("submit",async s=>{s.preventDefault(),await MB(t.value)?this.render():(n.className="learn-result info",n.textContent=p("web_learn_teacher_wrong"))}),e.append(O("p",{class:"hint"},p("web_learn_teacher_intro")),a,n),e}taskExercises(e){return e.blocks.flatMap(t=>t.kind==="exercise"?[t.exercise]:[])}renderTask(e){const t=O("button",{class:"learn-back"},`← ${p("web_learn_all_tasks")}`);t.addEventListener("click",()=>{this.taskId=void 0,this.persist(),this.render()});const n=Zt.find(a=>a.number===e.after);if(this.body.append(t,O("h2",{class:"learn-title"},e.title)),n){const a=O("button",{class:"link-button"},p("web_learn_after_fmt",n.number,n.title));a.addEventListener("click",()=>this.openLesson(n.id)),this.body.append(O("p",{class:"learn-kicker"},a))}e.blocks.forEach((a,s)=>this.body.append(this.renderBlock(a,`task-${s}`))),Eu(this.body),this.openNeededColumns(e.blocks),Wu(this.body,Da)}renderBlock(e,t,n){switch(e.kind){case"markdown":return mt("div",{class:"learn-text"},zn(e.text));case"diagram":return this.renderDiagram(e.file,e.caption);case"exercise":return this.renderExercise(e.exercise);case"checklist":return this.renderChecklist(e.items,t,n);case"quiz":return this.renderQuiz(e.questions,t,n);case"brag":return this.renderBrag(e.text,e.tip);case"images":return this.renderImages(e.files,e.caption);case"graphic":return this.renderGraphic(e.file,e.caption);case"game":return this.renderGame(e.game);case"roundGame":return QB(e.game,ta);case"rescueGame":return XB(e.game,ta);case"caesar":return JB(e.key,e.text);case"cloze":return eD(e.cloze);case"textFile":return Oh(e.name,e.content);case"robotModel":return GB(e.focus,e.view,e.spin);case"robotQuiz":return VB(e.tasks,e.done)}}renderBrag(e,t=!1){const n=O("aside",{class:"learn-brag"});n.append(O("img",{src:ta,alt:"",width:"48",height:"48"}));const a=O("div",{},O("p",{class:"learn-brag-title"},p(t?"web_learn_ludwig_tip":"web_learn_brag")));return a.append(mt("div",{class:"learn-text"},zn(e))),n.append(a),n}renderGame(e){const n=O("section",{class:"learn-game"}),a=O("div",{class:"learn-game-head"});a.append(O("img",{src:ta,alt:"",width:"40",height:"40"}),O("strong",{},p("web_game_title")));const s=O("p",{class:"learn-game-status"}),r=O("div",{class:"learn-game-stage"});n.append(a,s,r);let o=0,l=0;const u=()=>{const d=Px(e,o,10);s.textContent=`${p("web_game_round_fmt",o+1,10)} · ${p("web_game_score_fmt",l)}`;const h=O("div",{class:"learn-game-values mono"});for(const[w,k]of jx(d))h.append(O("code",{},`${w} = ${k}`));const g=O("div",{class:"group learn-game-answers"}),f=O("button",{class:"learn-game-true"},`✓ ${p("web_game_true")}`),x=O("button",{class:"learn-game-false"},`✗ ${p("web_game_false")}`);g.append(f,x);const b=O("div",{class:"learn-game-feedback",role:"status"}),v=w=>{f.disabled=x.disabled=!0;const k=w===d.answer;k&&l++,s.textContent=`${p("web_game_round_fmt",o+1,10)} · ${p("web_game_score_fmt",l)}`,b.className=`learn-game-feedback ${k?"right":"wrong"}`;const I=O("div",{class:"learn-game-steps mono"});Ox(d.condition,d.values).forEach((S,_)=>I.append(O("div",{},`${_?"→ ":""}${S}`)));const T=O("button",{class:"primary"},o+1<10?p("web_game_next"):p("web_game_finish"));T.addEventListener("click",()=>{o++,o<10?u():m()}),b.replaceChildren(O("p",{},p(k?"web_game_right":"web_game_wrong")),I,T),T.focus()};f.addEventListener("click",()=>v(!0)),x.addEventListener("click",()=>v(!1)),r.replaceChildren(h,O("div",{class:"learn-game-condition mono"},d.condition),g,b)},m=()=>{s.textContent="";const d=O("button",{class:"primary"},p("web_game_again"));d.addEventListener("click",()=>{o=l=0,u()}),r.replaceChildren(O("p",{class:"learn-game-result"},p("web_game_done_fmt",l,10)),O("p",{},p(l===10?"web_game_perfect":l>=10*.7?"web_game_good":"web_game_practice")),d)},c=O("button",{class:"primary"},p("web_game_start"));return c.addEventListener("click",u),r.append(O("p",{},p("web_game_intro")),c),n}renderImages(e,t){const n=O("figure",{class:"learn-figure"}),a=O("div",{class:"learn-images"});for(const s of e){const r=Tu(s);r&&a.append(O("img",{src:r,alt:"",loading:"lazy"}))}return n.append(a),t&&n.append(mt("figcaption",{},Fe(t))),n}renderGraphic(e,t){const n=O("figure",{class:"learn-figure"}),a=Tu(e);return a&&n.append(O("img",{class:"learn-graphic",src:a,alt:"",loading:"lazy"})),t&&n.append(mt("figcaption",{},Fe(t))),n}renderDiagram(e,t){const n=U1(e),a=O("figure",{class:"learn-figure"});if(!n)return a;const s=this.host.preview(n);s&&a.append(O("div",{class:"learn-preview",dir:"ltr"},s)),t&&a.append(mt("figcaption",{},Fe(t)));const r=O("button",{},p("web_learn_open_in_editor"));return r.addEventListener("click",()=>this.host.openDiagram(n,e)),a.append(r),a}renderExercise(e){const t=O("section",{class:"learn-exercise","data-exercise":e.id}),n=()=>ce.exercise(e.id),a=O("span",{class:"learn-badge"},`✓ ${p("web_learn_solved")}`);a.hidden=!n().done,t.append(O("h4",{},`${p("web_learn_exercise")}: ${e.title}`,a),mt("div",{class:"learn-text"},zn(e.task)));const s=O("div",{class:"learn-result",role:"status"}),r=O("div",{class:"learn-hints"}),o=O("div",{class:"group"}),l=O("button",{class:"primary"},p("web_learn_open_exercise"));l.addEventListener("click",()=>{const c=n().xml;let d=Nu(e);if(c)try{d=Il(c)}catch{}this.host.openExercise(e,d)});const u=O("button",{},p("web_learn_check"));if(u.addEventListener("click",()=>{const c=this.host.exerciseDocument(e.id);if(!c){s.className="learn-result info",s.textContent=p("web_learn_open_first");return}if(c.elements.every(vl)){s.className="learn-result info",s.textContent=p("web_learn_empty");return}this.host.stopSimulation();const d=Ix(c,e.tests,this.host.subprogramsFor(e.id),Za),h=kx(c),g=e.requires.map(b=>b==="forZaehlSchleife"?"forSchleife":b).filter(b=>b in z&&!h.has(z[b])),f=e.loopDepth!==void 0&&xo(c.elements)b.passed)&&g.length===0&&!f;this.showResult(s,d,g,x,f),x&&(ce.updateExercise(e.id,{done:!0}),a.hidden=!1)}),o.append(l,u),e.hints.length>0){const c=O("button",{},p("web_learn_hint"));c.addEventListener("click",()=>{const d=r.children.length;if(d>=e.hints.length)return;const h=e.hints.length>1?`**${p("web_learn_hint_fmt",d+1,e.hints.length)}:** `:"";r.append(mt("aside",{class:"lesson-note"},zn(h+e.hints[d]))),c.textContent=p("web_learn_hint_more"),c.toggleAttribute("disabled",d+1>=e.hints.length)}),o.append(c)}const m=O("button",{class:"danger-text"},p("web_learn_reset"));if(m.addEventListener("click",()=>{if(m.dataset.confirm!=="1"){m.dataset.confirm="1",m.textContent=p("web_learn_reset_confirm"),setTimeout(()=>{m.dataset.confirm="",m.textContent=p("web_learn_reset")},4e3);return}ce.resetExercise(e.id),this.host.resetExercise(e.id,Nu(e)),a.hidden=!0,s.replaceChildren(),s.className="learn-result",m.dataset.confirm="",m.textContent=p("web_learn_reset")}),o.append(m),t.append(o,r,s),Au()&&e.solution){const c=U1(e.solution);if(c){const d=O("details",{class:"learn-solution"},O("summary",{},p("web_learn_solution")));d.addEventListener("toggle",()=>{if(!d.open||d.querySelector(".learn-preview"))return;const h=this.host.preview(c);h&&d.append(O("div",{class:"learn-preview",dir:"ltr"},h));const g=O("button",{},p("web_learn_open_in_editor"));g.addEventListener("click",()=>{this.host.openDiagram(c,e.solution);for(const f of e.subprograms){const x=U1(f);x&&this.host.openDiagram(x,f)}});for(const f of e.subprograms){const x=U1(f),b=x&&this.host.preview(x);b&&d.append(O("div",{class:"learn-preview",dir:"ltr"},b))}d.append(g)}),t.append(d)}}return t}showResult(e,t,n,a,s){var o,l,u,m,c;e.className="learn-result "+(a?"ok":"fail"),e.replaceChildren(O("p",{class:"learn-result-head"},a?`🎉 ${p("web_learn_passed")}`:p("web_learn_failed")));for(const d of n)e.append(O("p",{},`✗ ${p("web_learn_missing_fmt",mD(z[d]))}`));s&&e.append(O("p",{},`✗ ${p("web_visubot_depth_fmt",s)}`));const r=O("ul",{class:"learn-tests",dir:"auto"});for(const d of t){const h=d.test.world?t.filter(b=>b.test.world).indexOf(d)+1:0,g=d.test.world?`🗺 ${p("web_visubot_world_fmt",h)}`:d.test.actions?`🤖 ${p("web_visubot_actions")}`:d.test.sensors?`🎛 ${Object.entries(d.test.sensors).map(([b,v])=>`mbot.${b}() = ${v.join(" → ")}`).join(", ")}`:d.test.drive?`🤖 ${p("web_visubot_drive")}`:d.test.inputs.length?p("web_learn_input_fmt",d.test.inputs.join(", ")):p("web_learn_no_input"),f=[`${d.passed?"✓":"✗"} ${g}`],x=O("div",{class:"learn-test-detail"});if(d.test.drive&&x.append(O("span",{},`${p("web_learn_expected")}: `,O("code",{},V1(d.test.drive)||"–")),O("span",{},`${p("web_learn_actual")}: `,O("code",{},V1(d.result.drive??[])||"–"))),d.test.actions&&x.append(O("span",{},`${p("web_learn_expected")}: `,O("code",{},V1(d.test.actions)||"–")),O("span",{},`${p("web_learn_actual")}: `,O("code",{},V1(d.result.actions??[])||"–"))),d.test.led!==void 0){const b=v=>p(v?"web_visubot_led_on":"web_visubot_led_off");x.append(O("span",{},`💡 ${p("web_learn_expected")}: ${b(d.test.led)} · ${p("web_learn_actual")}: ${b(d.result.led)}`))}if(d.test.tone!==void 0){const b=v=>p(v?"web_visubot_tone_yes":"web_visubot_tone_no");x.append(O("span",{},`🔊 ${p("web_learn_expected")}: ${b(d.test.tone)} · ${p("web_learn_actual")}: ${b(d.result.tone)}`))}d.test.screen!==void 0&&x.append(O("span",{},`📺 ${p("web_learn_expected")}: `,O("code",{},d.test.screen),` · ${p("web_learn_actual")}: `,O("code",{},d.result.screen??"–"))),d.test.world&&(((l=(o=Za(d.test.world))==null?void 0:o.goals)!=null&&l.length||(m=(u=Za(d.test.world))==null?void 0:u.targets)!=null&&m.length)&&x.append(O("span",{},d.result.atGoal?`✓ ${p("web_visubot_goal_reached")}`:`✗ ${p("web_visubot_goal_missed")}`)),d.result.bumps&&x.append(O("span",{class:"learn-error"},`⚠︎ ${p("web_visubot_bumps")}: ${d.result.bumps}`))),(!d.test.drive&&!d.test.world&&!d.test.sensors&&!d.test.actions||d.result.outputs.length)&&x.append(O("span",{},`${p("web_learn_expected")}: `,O("code",{},d.test.expected.join(" | ")||"–")),O("span",{},`${p("web_learn_actual")}: `,O("code",{},d.result.outputs.join(" | ")||"–")));for(const b of d.test.files??[])x.append(O("span",{},`📄 ${b.name}, ${p("web_learn_expected")}: `,O("code",{},b.lines.join(" | ")||"–")),O("span",{},`📄 ${b.name}, ${p("web_learn_actual")}: `,O("code",{},gh((c=d.result.files)==null?void 0:c.get(b.name)).join(" | ")||"–")));d.result.error&&x.append(O("span",{class:"learn-error"},Qn(d.result.error))),d.result.missingInput&&x.append(O("span",{class:"learn-error"},p("web_learn_missing_input"))),d.result.tooManySteps&&x.append(O("span",{class:"learn-error"},p("web_learn_too_many_steps"))),!d.passed&&d.result.unusedInputs&&x.append(O("span",{class:"learn-error"},p("web_learn_unused_input"))),r.append(O("li",{class:d.passed?"ok":"fail"},...f,x))}e.append(r)}renderChecklist(e,t,n){const a=O("ul",{class:"learn-checklist"});return e.forEach((s,r)=>{var c;const o=`${t}-${r}`,l=O("input",{type:"checkbox"});l.checked=!!(n&&((c=ce.lesson(n.id).checks)!=null&&c[o])),l.addEventListener("change",()=>{if(!n)return;const d={...ce.lesson(n.id).checks??{},[o]:l.checked};ce.updateLesson(n.id,{checks:d})});const u=O("label",{},l);u.insertAdjacentHTML("beforeend"," "+Fe(s.text));const m=O("li",{},u);if(n&&s.step!==void 0){const d=s.step,h=p("web_learn_step_fmt",d+1,n.steps[d].title),g=O("button",{class:"link-button learn-check-link",title:h,"aria-label":`${p("web_learn_review")}: ${h}`},p("web_learn_review"));g.addEventListener("click",()=>{this.returnTo={lesson:n.id,step:ce.lesson(n.id).step,scroll:this.body.scrollTop},this.goToStep(n,d)}),m.append(g)}a.append(m)}),a}renderQuiz(e,t,n){const a=O("div",{class:"learn-quiz"}),s=O("p",{class:"learn-score",role:"status"}),r=()=>n?ce.lesson(n.id).quiz??{}:{},o=()=>{const l=r(),u=(h,g)=>h.pairs?h.pairs.every((f,x)=>l[`${t}-${g}-${x}`]!==void 0):l[`${t}-${g}`]!==void 0,m=(h,g)=>{var f;return h.pairs?h.pairs.every((x,b)=>Fu(h)[l[`${t}-${g}-${b}`]]===h.pairs[b].right):(f=h.options[l[`${t}-${g}`]])==null?void 0:f.correct},c=e.filter(u).length,d=e.filter(m).length;s.textContent=c===e.length?p("web_learn_score_fmt",d,e.length):""};return e.forEach((l,u)=>{const m=`${t}-${u}`,c=O("fieldset",{},mt("legend",{},Fe(l.question))),d=mt("p",{class:"learn-explanation"},Fe(l.explanation??""));if(l.pairs){c.append(this.renderMatch(l,m,r,n,d,o),d),a.append(c);return}const h=g=>{c.querySelectorAll("button").forEach((f,x)=>{f.classList.toggle("right",g!==void 0&&l.options[x].correct),f.classList.toggle("wrong",g===x&&!l.options[x].correct),f.setAttribute("aria-pressed",String(g===x))}),d.hidden=g===void 0||!l.explanation};l.options.forEach((g,f)=>{const x=mt("button",{class:"learn-option"},Fe(g.text));x.addEventListener("click",()=>{n&&ce.updateLesson(n.id,{quiz:{...r(),[m]:f}}),h(f),o()}),c.append(x)}),c.append(d),h(r()[m]),a.append(c)}),a.append(s),o(),a}renderMatch(e,t,n,a,s,r){const o=e.pairs,l=Fu(e),u=O("div",{class:"learn-match"});let m={};const c=()=>a?n():m,d=x=>a?ce.updateLesson(a.id,{quiz:x}):m=x,h=x=>c()[`${t}-${x}`],g=o.map(x=>{const b=O("select",{class:"learn-match-select"});b.append(O("option",{value:""},"–")),l.forEach((w,k)=>b.append(O("option",{value:String(k)},w)));const v=mt("label",{class:"learn-match-left"},Fe(x.left));return v.append(b),u.append(v),b}),f=()=>{const x=o.every((b,v)=>h(v)!==void 0);g.forEach((b,v)=>{const w=h(v);b.value=w===void 0?"":String(w),b.classList.toggle("right",x&&l[w]===o[v].right),b.classList.toggle("wrong",x&&l[w]!==o[v].right)}),s.hidden=!x||!e.explanation};return g.forEach((x,b)=>x.addEventListener("change",()=>{const v={...c()};x.value===""?delete v[`${t}-${b}`]:v[`${t}-${b}`]=Number(x.value),d(v),f(),r()})),f(),u}}function Fu(i){return(i.pairs??[]).map(e=>e.right).sort((e,t)=>e.localeCompare(t,"de"))}const hD=""+new URL("visubot-CyGFOI9V.webp",import.meta.url).href,Ql="visustruct.visubot";function ql(){try{return localStorage.getItem(Ql)}catch{return null}}function ai(){const i=ql();return i==="1"||i==="kurs"?"on":"off"}const Dh=()=>ql()==="2";function Zh(){try{localStorage.setItem(Ql,"2")}catch{}}const gD=()=>ql()!==null;function cr(i){try{localStorage.setItem(Ql,i==="on"?"1":"0")}catch{}}const pD=`VisuBot`,Wn=()=>ai()!=="off",Ju=i=>i.replace(/[&<>"]/g,e=>({"&":"&","<":"<",">":">",'"':"""})[e]);function wo(){const i=Dh()?"object":ai(),e=(n,a)=>``,t={off:"web_visubot_world_visustruct_hint",on:"web_visubot_world_visubot_hint",object:"web_visuobject_world_hint"}[i];return`
+${a}`));this.body.append(s),this.foldReference(s)}}foldReference(e){const t="visustruct.reference.open";let n=[];try{n=JSON.parse(localStorage.getItem(t)??"[]")}catch{}for(const a of[...e.querySelectorAll("h2")]){const s=a.textContent??"",r=O("details",{class:"reference-group"});r.open=n.includes(s);const o=O("summary",{},s);for(a.replaceWith(r),r.append(o);r.nextSibling&&r.nextSibling.nodeName!=="H2";)r.append(r.nextSibling);r.addEventListener("toggle",()=>{n=r.open?[...new Set([...n,s])]:n.filter(l=>l!==s);try{localStorage.setItem(t,JSON.stringify(n))}catch{}})}}showReference(){this.tab="reference",this.persist(),this.render()}persist(){ce.setView({tab:this.tab,lesson:this.lessonId,task:this.taskId})}openLesson(e){this.tab="lessons",this.lessonId=e,this.returnTo=void 0,this.persist(),this.render(),this.body.scrollTop=0}renderLessonList(){this.body.append(O("p",{class:"hint"},p("web_learn_intro")));for(const e of uD()){this.body.append(O("h3",{class:"learn-section"},e.name));const t=O("ol",{class:"learn-list"});for(const n of e.lessons){const a=ce.lesson(n.id),s=a.done?"✓":a.step>0?p("web_learn_step_of_fmt",a.step+1,n.steps.length):"",r=O("button",{class:"learn-item"+(a.done?" done":""),"data-lesson":n.id},O("span",{class:"learn-num"},String(n.number)),O("span",{class:"learn-item-text"},O("strong",{},n.title),O("small",{},n.summary)),O("span",{class:"learn-status"},s));r.addEventListener("click",()=>this.openLesson(n.id)),t.append(O("li",{},r))}this.body.append(t)}this.body.append(this.renderTeacherBox())}renderLesson(e){var c;const t=ce.lesson(e.id),n=Math.min(t.step,e.steps.length-1),a=e.steps[n],s=O("button",{class:"learn-back"},`← ${p("web_learn_all_lessons")}`);s.addEventListener("click",()=>this.openLesson(void 0));const r=O("nav",{class:"learn-progress","aria-label":p("web_learn_step_of_fmt",n+1,e.steps.length)});r.append(...e.steps.map((d,h)=>{const g=p("web_learn_step_fmt",h+1,d.title),f=hthis.goToStep(e,h)),x})),this.body.append(s,O("p",{class:"learn-kicker"},`${p("web_learn_lesson_fmt",e.number)} · ${e.section}`),O("h2",{class:"learn-title"},O("span",{class:"learn-num","aria-hidden":"true"},String(e.number)),e.title),r,O("h3",{class:"learn-step-title"},`${n+1}. ${a.title}`));const o=((c=this.returnTo)==null?void 0:c.lesson)===e.id&&this.returnTo.step!==n?this.returnTo:void 0,l=()=>{const d=O("button",{class:"learn-return"},`↩ ${p("web_learn_back_to_checklist")}`);return d.addEventListener("click",()=>{this.returnTo=void 0,this.goToStep(e,o.step),this.body.scrollTop=o.scroll}),d};o&&this.body.append(l()),a.blocks.forEach((d,h)=>this.body.append(this.renderBlock(d,`${n}-${h}`,e))),Eu(this.body),HB(this.body),this.openNeededColumns(a.blocks),Wu(this.body,Da);const u=O("div",{class:"learn-nav"}),m=O("button",{},`← ${p("web_learn_back")}`);if(m.disabled=n===0,m.addEventListener("click",()=>this.goToStep(e,n-1)),u.append(m),nthis.goToStep(e,n+1)),u.append(d)}else{const d=O("button",{class:"primary"},t.done?`✓ ${p("web_learn_done")}`:p("web_learn_finish"));d.addEventListener("click",()=>{ce.updateLesson(e.id,{done:!0});const h=Zt.find(g=>g.number===e.number+1);this.openLesson(h==null?void 0:h.id)}),u.append(d)}this.body.append(u),o&&this.body.append(l())}goToStep(e,t){ce.updateLesson(e.id,{step:t}),this.render(),this.body.scrollTop=0}openNeededColumns(e){const t=e.flatMap(n=>n.kind==="exercise"?[n.exercise]:[]);rD(this.body)?this.host.showEditor():sD(this.body)?this.host.showFiles():t.some(n=>n.code!=="java")?this.host.showEditor():(t.length>0||this.body.querySelector(".lesson-code[data-lang=java]"))&&this.host.showJava(),oD(this.body)&&this.host.showLiveCode()}renderTaskList(){this.body.append(O("p",{class:"hint"},p("web_learn_tasks_intro")));const e=O("ul",{class:"learn-list"});for(const t of x1){const n=this.taskExercises(t),a=n.length>0&&n.every(o=>ce.exercise(o.id).done),s=Zt.find(o=>o.number===t.after),r=O("button",{class:"learn-item"+(a?" done":""),"data-task":t.id},O("span",{class:"learn-num","aria-label":p("web_learn_level_fmt",t.level)},"★".repeat(t.level)),O("span",{class:"learn-item-text"},O("strong",{},t.title),O("small",{},s?p("web_learn_after_fmt",s.number,s.title):"")),O("span",{class:"learn-status"},a?"✓":""));r.addEventListener("click",()=>{this.taskId=t.id,this.persist(),this.render(),this.body.scrollTop=0}),e.append(O("li",{},r))}this.body.append(e,this.renderTeacherBox())}renderTeacherBox(){const e=O("details",{class:"learn-teacher"},O("summary",{},p("web_learn_teacher")));if(Au()){e.setAttribute("open","");const s=O("button",{},p("web_learn_teacher_off"));return s.addEventListener("click",()=>{LB(),this.render()}),e.append(O("p",{},p("web_learn_teacher_on")),s),e}const t=O("input",{type:"password",autocomplete:"off","aria-label":p("web_learn_teacher_code"),placeholder:p("web_learn_teacher_code")}),n=O("p",{class:"learn-result",role:"status"}),a=O("form",{class:"group"},t,O("button",{type:"submit"},p("web_learn_teacher_unlock")));return a.addEventListener("submit",async s=>{s.preventDefault(),await MB(t.value)?this.render():(n.className="learn-result info",n.textContent=p("web_learn_teacher_wrong"))}),e.append(O("p",{class:"hint"},p("web_learn_teacher_intro")),a,n),e}taskExercises(e){return e.blocks.flatMap(t=>t.kind==="exercise"?[t.exercise]:[])}renderTask(e){const t=O("button",{class:"learn-back"},`← ${p("web_learn_all_tasks")}`);t.addEventListener("click",()=>{this.taskId=void 0,this.persist(),this.render()});const n=Zt.find(a=>a.number===e.after);if(this.body.append(t,O("h2",{class:"learn-title"},e.title)),n){const a=O("button",{class:"link-button"},p("web_learn_after_fmt",n.number,n.title));a.addEventListener("click",()=>this.openLesson(n.id)),this.body.append(O("p",{class:"learn-kicker"},a))}e.blocks.forEach((a,s)=>this.body.append(this.renderBlock(a,`task-${s}`))),Eu(this.body),this.openNeededColumns(e.blocks),Wu(this.body,Da)}renderBlock(e,t,n){switch(e.kind){case"markdown":return mt("div",{class:"learn-text"},zn(e.text));case"diagram":return this.renderDiagram(e.file,e.caption);case"exercise":return this.renderExercise(e.exercise);case"checklist":return this.renderChecklist(e.items,t,n);case"quiz":return this.renderQuiz(e.questions,t,n);case"brag":return this.renderBrag(e.text,e.tip);case"images":return this.renderImages(e.files,e.caption);case"graphic":return this.renderGraphic(e.file,e.caption);case"game":return this.renderGame(e.game);case"roundGame":return QB(e.game,ta);case"rescueGame":return XB(e.game,ta);case"caesar":return JB(e.key,e.text);case"cloze":return eD(e.cloze);case"textFile":return Oh(e.name,e.content);case"robotModel":return GB(e.focus,e.view,e.spin);case"robotQuiz":return VB(e.tasks,e.done)}}renderBrag(e,t=!1){const n=O("aside",{class:"learn-brag"});n.append(O("img",{src:ta,alt:"",width:"48",height:"48"}));const a=O("div",{},O("p",{class:"learn-brag-title"},p(t?"web_learn_ludwig_tip":"web_learn_brag")));return a.append(mt("div",{class:"learn-text"},zn(e))),n.append(a),n}renderGame(e){const n=O("section",{class:"learn-game"}),a=O("div",{class:"learn-game-head"});a.append(O("img",{src:ta,alt:"",width:"40",height:"40"}),O("strong",{},p("web_game_title")));const s=O("p",{class:"learn-game-status"}),r=O("div",{class:"learn-game-stage"});n.append(a,s,r);let o=0,l=0;const u=()=>{const d=Px(e,o,10);s.textContent=`${p("web_game_round_fmt",o+1,10)} · ${p("web_game_score_fmt",l)}`;const h=O("div",{class:"learn-game-values mono"});for(const[w,k]of jx(d))h.append(O("code",{},`${w} = ${k}`));const g=O("div",{class:"group learn-game-answers"}),f=O("button",{class:"learn-game-true"},`✓ ${p("web_game_true")}`),x=O("button",{class:"learn-game-false"},`✗ ${p("web_game_false")}`);g.append(f,x);const b=O("div",{class:"learn-game-feedback",role:"status"}),v=w=>{f.disabled=x.disabled=!0;const k=w===d.answer;k&&l++,s.textContent=`${p("web_game_round_fmt",o+1,10)} · ${p("web_game_score_fmt",l)}`,b.className=`learn-game-feedback ${k?"right":"wrong"}`;const I=O("div",{class:"learn-game-steps mono"});Ox(d.condition,d.values).forEach((S,_)=>I.append(O("div",{},`${_?"→ ":""}${S}`)));const T=O("button",{class:"primary"},o+1<10?p("web_game_next"):p("web_game_finish"));T.addEventListener("click",()=>{o++,o<10?u():m()}),b.replaceChildren(O("p",{},p(k?"web_game_right":"web_game_wrong")),I,T),T.focus()};f.addEventListener("click",()=>v(!0)),x.addEventListener("click",()=>v(!1)),r.replaceChildren(h,O("div",{class:"learn-game-condition mono"},d.condition),g,b)},m=()=>{s.textContent="";const d=O("button",{class:"primary"},p("web_game_again"));d.addEventListener("click",()=>{o=l=0,u()}),r.replaceChildren(O("p",{class:"learn-game-result"},p("web_game_done_fmt",l,10)),O("p",{},p(l===10?"web_game_perfect":l>=10*.7?"web_game_good":"web_game_practice")),d)},c=O("button",{class:"primary"},p("web_game_start"));return c.addEventListener("click",u),r.append(O("p",{},p("web_game_intro")),c),n}renderImages(e,t){const n=O("figure",{class:"learn-figure"}),a=O("div",{class:"learn-images"});for(const s of e){const r=Tu(s);r&&a.append(O("img",{src:r,alt:"",loading:"lazy"}))}return n.append(a),t&&n.append(mt("figcaption",{},Fe(t))),n}renderGraphic(e,t){const n=O("figure",{class:"learn-figure"}),a=Tu(e);return a&&n.append(O("img",{class:"learn-graphic",src:a,alt:"",loading:"lazy"})),t&&n.append(mt("figcaption",{},Fe(t))),n}renderDiagram(e,t){const n=U1(e),a=O("figure",{class:"learn-figure"});if(!n)return a;const s=this.host.preview(n);s&&a.append(O("div",{class:"learn-preview",dir:"ltr"},s)),t&&a.append(mt("figcaption",{},Fe(t)));const r=O("button",{},p("web_learn_open_in_editor"));return r.addEventListener("click",()=>this.host.openDiagram(n,e)),a.append(r),a}renderExercise(e){const t=O("section",{class:"learn-exercise","data-exercise":e.id}),n=()=>ce.exercise(e.id),a=O("span",{class:"learn-badge"},`✓ ${p("web_learn_solved")}`);a.hidden=!n().done,t.append(O("h4",{},`${p("web_learn_exercise")}: ${e.title}`,a),mt("div",{class:"learn-text"},zn(e.task)));const s=O("div",{class:"learn-result",role:"status"}),r=O("div",{class:"learn-hints"}),o=O("div",{class:"group"}),l=O("button",{class:"primary"},p("web_learn_open_exercise"));l.addEventListener("click",()=>{const c=n().xml;let d=Nu(e);if(c)try{d=Il(c)}catch{}this.host.openExercise(e,d)});const u=O("button",{},p("web_learn_check"));if(u.addEventListener("click",()=>{const c=this.host.exerciseDocument(e.id);if(!c){s.className="learn-result info",s.textContent=p("web_learn_open_first");return}if(c.elements.every(vl)){s.className="learn-result info",s.textContent=p("web_learn_empty");return}this.host.stopSimulation();const d=Ix(c,e.tests,this.host.subprogramsFor(e.id),Za),h=kx(c),g=e.requires.map(b=>b==="forZaehlSchleife"?"forSchleife":b).filter(b=>b in z&&!h.has(z[b])),f=e.loopDepth!==void 0&&xo(c.elements)b.passed)&&g.length===0&&!f;this.showResult(s,d,g,x,f),x&&(ce.updateExercise(e.id,{done:!0}),a.hidden=!1)}),o.append(l,u),e.hints.length>0){const c=O("button",{},p("web_learn_hint"));c.addEventListener("click",()=>{const d=r.children.length;if(d>=e.hints.length)return;const h=e.hints.length>1?`**${p("web_learn_hint_fmt",d+1,e.hints.length)}:** `:"";r.append(mt("aside",{class:"lesson-note"},zn(h+e.hints[d]))),c.textContent=p("web_learn_hint_more"),c.toggleAttribute("disabled",d+1>=e.hints.length)}),o.append(c)}const m=O("button",{class:"danger-text"},p("web_learn_reset"));if(m.addEventListener("click",()=>{if(m.dataset.confirm!=="1"){m.dataset.confirm="1",m.textContent=p("web_learn_reset_confirm"),setTimeout(()=>{m.dataset.confirm="",m.textContent=p("web_learn_reset")},4e3);return}ce.resetExercise(e.id),this.host.resetExercise(e.id,Nu(e)),a.hidden=!0,s.replaceChildren(),s.className="learn-result",m.dataset.confirm="",m.textContent=p("web_learn_reset")}),o.append(m),t.append(o,r,s),Au()&&e.solution){const c=U1(e.solution);if(c){const d=O("details",{class:"learn-solution"},O("summary",{},p("web_learn_solution")));d.addEventListener("toggle",()=>{if(!d.open||d.querySelector(".learn-preview"))return;const h=this.host.preview(c);h&&d.append(O("div",{class:"learn-preview",dir:"ltr"},h));const g=O("button",{},p("web_learn_open_in_editor"));g.addEventListener("click",()=>{this.host.openDiagram(c,e.solution);for(const f of e.subprograms){const x=U1(f);x&&this.host.openDiagram(x,f)}});for(const f of e.subprograms){const x=U1(f),b=x&&this.host.preview(x);b&&d.append(O("div",{class:"learn-preview",dir:"ltr"},b))}d.append(g)}),t.append(d)}}return t}showResult(e,t,n,a,s){var o,l,u,m,c;e.className="learn-result "+(a?"ok":"fail"),e.replaceChildren(O("p",{class:"learn-result-head"},a?`🎉 ${p("web_learn_passed")}`:p("web_learn_failed")));for(const d of n)e.append(O("p",{},`✗ ${p("web_learn_missing_fmt",mD(z[d]))}`));s&&e.append(O("p",{},`✗ ${p("web_visubot_depth_fmt",s)}`));const r=O("ul",{class:"learn-tests",dir:"auto"});for(const d of t){const h=d.test.world?t.filter(b=>b.test.world).indexOf(d)+1:0,g=d.test.world?`🗺 ${p("web_visubot_world_fmt",h)}`:d.test.actions?`🤖 ${p("web_visubot_actions")}`:d.test.sensors?`🎛 ${Object.entries(d.test.sensors).map(([b,v])=>`mbot.${b}() = ${v.join(" → ")}`).join(", ")}`:d.test.drive?`🤖 ${p("web_visubot_drive")}`:d.test.inputs.length?p("web_learn_input_fmt",d.test.inputs.join(", ")):p("web_learn_no_input"),f=[`${d.passed?"✓":"✗"} ${g}`],x=O("div",{class:"learn-test-detail"});if(d.test.drive&&x.append(O("span",{},`${p("web_learn_expected")}: `,O("code",{},V1(d.test.drive)||"–")),O("span",{},`${p("web_learn_actual")}: `,O("code",{},V1(d.result.drive??[])||"–"))),d.test.actions&&x.append(O("span",{},`${p("web_learn_expected")}: `,O("code",{},V1(d.test.actions)||"–")),O("span",{},`${p("web_learn_actual")}: `,O("code",{},V1(d.result.actions??[])||"–"))),d.test.led!==void 0){const b=v=>p(v?"web_visubot_led_on":"web_visubot_led_off");x.append(O("span",{},`💡 ${p("web_learn_expected")}: ${b(d.test.led)} · ${p("web_learn_actual")}: ${b(d.result.led)}`))}if(d.test.tone!==void 0){const b=v=>p(v?"web_visubot_tone_yes":"web_visubot_tone_no");x.append(O("span",{},`🔊 ${p("web_learn_expected")}: ${b(d.test.tone)} · ${p("web_learn_actual")}: ${b(d.result.tone)}`))}d.test.screen!==void 0&&x.append(O("span",{},`📺 ${p("web_learn_expected")}: `,O("code",{},d.test.screen),` · ${p("web_learn_actual")}: `,O("code",{},d.result.screen??"–"))),d.test.world&&(((l=(o=Za(d.test.world))==null?void 0:o.goals)!=null&&l.length||(m=(u=Za(d.test.world))==null?void 0:u.targets)!=null&&m.length)&&x.append(O("span",{},d.result.atGoal?`✓ ${p("web_visubot_goal_reached")}`:`✗ ${p("web_visubot_goal_missed")}`)),d.result.bumps&&x.append(O("span",{class:"learn-error"},`⚠︎ ${p("web_visubot_bumps")}: ${d.result.bumps}`))),(!d.test.drive&&!d.test.world&&!d.test.sensors&&!d.test.actions||d.result.outputs.length)&&x.append(O("span",{},`${p("web_learn_expected")}: `,O("code",{},d.test.expected.join(" | ")||"–")),O("span",{},`${p("web_learn_actual")}: `,O("code",{},d.result.outputs.join(" | ")||"–")));for(const b of d.test.files??[])x.append(O("span",{},`📄 ${b.name}, ${p("web_learn_expected")}: `,O("code",{},b.lines.join(" | ")||"–")),O("span",{},`📄 ${b.name}, ${p("web_learn_actual")}: `,O("code",{},gh((c=d.result.files)==null?void 0:c.get(b.name)).join(" | ")||"–")));d.result.error&&x.append(O("span",{class:"learn-error"},qn(d.result.error))),d.result.missingInput&&x.append(O("span",{class:"learn-error"},p("web_learn_missing_input"))),d.result.tooManySteps&&x.append(O("span",{class:"learn-error"},p("web_learn_too_many_steps"))),!d.passed&&d.result.unusedInputs&&x.append(O("span",{class:"learn-error"},p("web_learn_unused_input"))),r.append(O("li",{class:d.passed?"ok":"fail"},...f,x))}e.append(r)}renderChecklist(e,t,n){const a=O("ul",{class:"learn-checklist"});return e.forEach((s,r)=>{var c;const o=`${t}-${r}`,l=O("input",{type:"checkbox"});l.checked=!!(n&&((c=ce.lesson(n.id).checks)!=null&&c[o])),l.addEventListener("change",()=>{if(!n)return;const d={...ce.lesson(n.id).checks??{},[o]:l.checked};ce.updateLesson(n.id,{checks:d})});const u=O("label",{},l);u.insertAdjacentHTML("beforeend"," "+Fe(s.text));const m=O("li",{},u);if(n&&s.step!==void 0){const d=s.step,h=p("web_learn_step_fmt",d+1,n.steps[d].title),g=O("button",{class:"link-button learn-check-link",title:h,"aria-label":`${p("web_learn_review")}: ${h}`},p("web_learn_review"));g.addEventListener("click",()=>{this.returnTo={lesson:n.id,step:ce.lesson(n.id).step,scroll:this.body.scrollTop},this.goToStep(n,d)}),m.append(g)}a.append(m)}),a}renderQuiz(e,t,n){const a=O("div",{class:"learn-quiz"}),s=O("p",{class:"learn-score",role:"status"}),r=()=>n?ce.lesson(n.id).quiz??{}:{},o=()=>{const l=r(),u=(h,g)=>h.pairs?h.pairs.every((f,x)=>l[`${t}-${g}-${x}`]!==void 0):l[`${t}-${g}`]!==void 0,m=(h,g)=>{var f;return h.pairs?h.pairs.every((x,b)=>Fu(h)[l[`${t}-${g}-${b}`]]===h.pairs[b].right):(f=h.options[l[`${t}-${g}`]])==null?void 0:f.correct},c=e.filter(u).length,d=e.filter(m).length;s.textContent=c===e.length?p("web_learn_score_fmt",d,e.length):""};return e.forEach((l,u)=>{const m=`${t}-${u}`,c=O("fieldset",{},mt("legend",{},Fe(l.question))),d=mt("p",{class:"learn-explanation"},Fe(l.explanation??""));if(l.pairs){c.append(this.renderMatch(l,m,r,n,d,o),d),a.append(c);return}const h=g=>{c.querySelectorAll("button").forEach((f,x)=>{f.classList.toggle("right",g!==void 0&&l.options[x].correct),f.classList.toggle("wrong",g===x&&!l.options[x].correct),f.setAttribute("aria-pressed",String(g===x))}),d.hidden=g===void 0||!l.explanation};l.options.forEach((g,f)=>{const x=mt("button",{class:"learn-option"},Fe(g.text));x.addEventListener("click",()=>{n&&ce.updateLesson(n.id,{quiz:{...r(),[m]:f}}),h(f),o()}),c.append(x)}),c.append(d),h(r()[m]),a.append(c)}),a.append(s),o(),a}renderMatch(e,t,n,a,s,r){const o=e.pairs,l=Fu(e),u=O("div",{class:"learn-match"});let m={};const c=()=>a?n():m,d=x=>a?ce.updateLesson(a.id,{quiz:x}):m=x,h=x=>c()[`${t}-${x}`],g=o.map(x=>{const b=O("select",{class:"learn-match-select"});b.append(O("option",{value:""},"–")),l.forEach((w,k)=>b.append(O("option",{value:String(k)},w)));const v=mt("label",{class:"learn-match-left"},Fe(x.left));return v.append(b),u.append(v),b}),f=()=>{const x=o.every((b,v)=>h(v)!==void 0);g.forEach((b,v)=>{const w=h(v);b.value=w===void 0?"":String(w),b.classList.toggle("right",x&&l[w]===o[v].right),b.classList.toggle("wrong",x&&l[w]!==o[v].right)}),s.hidden=!x||!e.explanation};return g.forEach((x,b)=>x.addEventListener("change",()=>{const v={...c()};x.value===""?delete v[`${t}-${b}`]:v[`${t}-${b}`]=Number(x.value),d(v),f(),r()})),f(),u}}function Fu(i){return(i.pairs??[]).map(e=>e.right).sort((e,t)=>e.localeCompare(t,"de"))}const hD=""+new URL("visubot-CyGFOI9V.webp",import.meta.url).href,Ql="visustruct.visubot";function ql(){try{return localStorage.getItem(Ql)}catch{return null}}function ai(){const i=ql();return i==="1"||i==="kurs"?"on":"off"}const Dh=()=>ql()==="2";function Zh(){try{localStorage.setItem(Ql,"2")}catch{}}const gD=()=>ql()!==null;function cr(i){try{localStorage.setItem(Ql,i==="on"?"1":"0")}catch{}}const pD=`VisuBot`,En=()=>ai()!=="off",Ju=i=>i.replace(/[&<>"]/g,e=>({"&":"&","<":"<",">":">",'"':"""})[e]);function wo(){const i=Dh()?"object":ai(),e=(n,a)=>``,t={off:"web_visubot_world_visustruct_hint",on:"web_visubot_world_visubot_hint",object:"web_visuobject_world_hint"}[i];return`
${e("off","VisuStruct")}${e("on","🤖 VisuBot")}${e("object","VisuObject")}
- ${Ju(p(t))}`}class fD{constructor(e=bi){y(this,"element");y(this,"world");y(this,"view");y(this,"loading");y(this,"status");y(this,"stage");y(this,"picker");y(this,"applied",0);y(this,"sent",0);y(this,"liveStatus");y(this,"stopListening");y(this,"realSensors");y(this,"controls",{getBrightness:50,getLoudness:0,getPitch:0,getRoll:0});y(this,"pressTimers",new Map);y(this,"check");y(this,"checking",!1);y(this,"onWorldChange");this.world=new ss(e),this.element=document.createElement("section"),this.element.className="visubot",this.element.innerHTML=`

${p("web_visubot_world")}

${xD()}${bD()}`,this.stage=this.element.querySelector(".visubot-stage"),this.picker=this.element.querySelector(".visubot-worlds"),this.status=this.element.querySelector(".visubot-status"),this.liveStatus=this.element.querySelector(".visubot-live"),this.stopListening=oe.listen(()=>this.updateLive()),this.setupControls(),this.check=this.element.querySelector(".visubot-check"),this.setupCheck(),this.updateLive(),this.updateStatus()}show(){this.loading??(this.loading=Q(async()=>{const{Robot3D:e}=await import("./robot3d-GGJ-E5MR.js");return{Robot3D:e}},[],import.meta.url).then(({Robot3D:e})=>{this.view=new e(this.stage),this.view.setWorld(this.world.setup),this.view.place(this.world.pose,this.world.trail),this.view.setLeds(this.world.leds)}).catch(()=>{this.stage.textContent=p("web_visubot_no_3d")}))}setWorlds(e){this.picker.replaceChildren(),this.picker.hidden=e.length<2,e.forEach((t,n)=>{const a=document.createElement("button");a.textContent=p("web_visubot_world_fmt",n+1),a.addEventListener("click",()=>this.useWorld(t,a)),this.picker.append(a)}),this.useWorld(e[0]??bi,this.picker.firstElementChild)}useWorld(e,t){var n,a,s,r,o;for(const l of this.picker.children)l.classList.toggle("active",l===t);e!==this.world.setup&&(this.world=new ss(e),this.applied=0,this.sent=0,(n=this.view)==null||n.setWorld(e),(a=this.view)==null||a.place(this.world.pose,this.world.trail),(s=this.view)==null||s.setLed(void 0),(r=this.view)==null||r.setScreen(void 0),this.updateStatus(),(o=this.onWorldChange)==null||o.call(this))}reset(){var e,t,n;this.world.reset(),this.applied=0,this.sent=0,this.realSensors=void 0,(e=this.view)==null||e.place(this.world.pose,this.world.trail),(t=this.view)==null||t.setLed(void 0),(n=this.view)==null||n.setScreen(void 0),this.updateStatus()}prepare(e){e.robotSensors={...this.controls,...this.world.sensors()}}setupControls(){for(const e of this.element.querySelectorAll(".visubot-controls input[type=range]")){const t=e.parentElement.querySelector("output"),n=()=>{this.controls[e.name]=Number(e.value),t.textContent=e.value};e.addEventListener("input",n),n()}for(const e of this.element.querySelectorAll(".visubot-controls button[name]"))e.addEventListener("click",()=>{const t=e.name;this.controls[t]=!0,e.classList.add("pressed"),window.clearTimeout(this.pressTimers.get(t)),this.pressTimers.set(t,window.setTimeout(()=>{this.controls[t]=!1,e.classList.remove("pressed")},1e3))})}setupCheck(){for(const e of this.check.querySelectorAll("button[data-py]"))e.addEventListener("click",()=>{const{after:t,wait:n}=e.dataset;oe.run(e.dataset.py).then(()=>t?new Promise(a=>setTimeout(a,Number(n))).then(()=>oe.run(t)):void 0).catch(a=>this.liveFailed(a))});this.check.addEventListener("toggle",()=>void this.readCheck())}async readCheck(){if(!this.checking){this.checking=!0;try{for(;this.check.open&&oe.connected;){for(const e of this.check.querySelectorAll("[data-sensor]")){if(!this.check.open||!oe.connected)break;const t=e.dataset.sensor,n=await oe.ask(wt[t].python).catch(()=>{});n!==void 0&&(e.textContent=typeof wt[t].simulated=="boolean"?n===!0||typeof n=="number"&&n!==0?"✓":"–":String(typeof n=="number"?Math.round(n*10)/10:n))}await new Promise(e=>setTimeout(e,200))}}finally{this.checking=!1}}}get live(){return oe.connected}async prepareLive(e,t=[]){const n={};for(const a of new Set(["getDistance","getLine",...t])){const s=await oe.ask(wt[a].python);typeof wt[a].simulated=="boolean"?n[a]=s===!0||typeof s=="number"&&s!==0:typeof wt[a].simulated=="string"?n[a]=typeof s=="string"?s:String(wt[a].simulated):n[a]=typeof s=="number"?a==="getDistance"?Math.round(s):s:0}this.realSensors=n,e.robotSensors={...this.controls,...this.world.sensors(),...n}}async drive(e){for(;this.sentsetTimeout(n,t.args[0]))}}liveFailed(e){oe.disconnect(e instanceof Error?e.message:String(e))}updateLive(){this.liveStatus.textContent=Lh(),this.liveStatus.classList.toggle("connected",oe.connected),this.check.hidden=!oe.connected,oe.connected||(this.check.open=!1),this.updateStatus()}follow(e,t){var a,s,r,o;for(;this.appliedl!==0);this.world.tick(Jl),n&&((o=this.view)==null||o.moveTo(this.world.pose,this.world.trail,t)),this.updateStatus()}dispose(){var e;this.stopListening();for(const t of this.pressTimers.values())window.clearTimeout(t);(e=this.view)==null||e.dispose(),this.view=void 0,this.loading=void 0}updateStatus(){const e=this.world.lineState().toString(2).padStart(4,"0"),t=[`${p("web_visubot_distance")}: ${this.world.distance()} cm`,`${p("web_visubot_line")}: ${e}`];this.world.bumps>0&&t.push(`⚠︎ ${p("web_visubot_bumps")}: ${this.world.bumps}`),this.world.screen!==void 0&&t.push(`📺 ${this.world.screen}`),this.realSensors&&oe.connected&&t.push(`🤖 ${p("web_visubot_distance")}: ${this.realSensors.getDistance} cm · ${p("web_visubot_line")}: ${Number(this.realSensors.getLine).toString(2).padStart(4,"0")}`),this.status.textContent=t.join(" · ")}}let E1;function Mh(i,e){try{E1??(E1=new AudioContext);const t=E1.createOscillator(),n=E1.createGain();t.type="square",t.frequency.value=Math.max(20,Math.min(2e4,i)),n.gain.value=.05,t.connect(n).connect(E1.destination);const a=E1.currentTime+Math.min(Math.max(e,0),5e3)/1e3;t.start(),t.stop(a)}catch{}}function xD(){const i=(t,n,a,s,r)=>``,e=(t,n,a)=>``;return`
🎛 ${p("web_visubot_controls")} + ${Ju(p(t))}`}class fD{constructor(e=bi){y(this,"element");y(this,"world");y(this,"view");y(this,"loading");y(this,"status");y(this,"stage");y(this,"picker");y(this,"applied",0);y(this,"sent",0);y(this,"liveStatus");y(this,"stopListening");y(this,"realSensors");y(this,"controls",{getBrightness:50,getLoudness:0,getPitch:0,getRoll:0});y(this,"pressTimers",new Map);y(this,"check");y(this,"checking",!1);y(this,"onWorldChange");this.world=new ss(e),this.element=document.createElement("section"),this.element.className="visubot",this.element.innerHTML=`

${p("web_visubot_world")}

${xD()}${bD()}`,this.stage=this.element.querySelector(".visubot-stage"),this.picker=this.element.querySelector(".visubot-worlds"),this.status=this.element.querySelector(".visubot-status"),this.liveStatus=this.element.querySelector(".visubot-live"),this.stopListening=oe.listen(()=>this.updateLive()),this.setupControls(),this.check=this.element.querySelector(".visubot-check"),this.setupCheck(),this.updateLive(),this.updateStatus()}show(){this.loading??(this.loading=Q(async()=>{const{Robot3D:e}=await import("./robot3d-FyDAbXTC.js");return{Robot3D:e}},[],import.meta.url).then(({Robot3D:e})=>{this.view=new e(this.stage),this.view.setWorld(this.world.setup),this.view.place(this.world.pose,this.world.trail),this.view.setLeds(this.world.leds)}).catch(()=>{this.stage.textContent=p("web_visubot_no_3d")}))}setWorlds(e){this.picker.replaceChildren(),this.picker.hidden=e.length<2,e.forEach((t,n)=>{const a=document.createElement("button");a.textContent=p("web_visubot_world_fmt",n+1),a.addEventListener("click",()=>this.useWorld(t,a)),this.picker.append(a)}),this.useWorld(e[0]??bi,this.picker.firstElementChild)}useWorld(e,t){var n,a,s,r,o;for(const l of this.picker.children)l.classList.toggle("active",l===t);e!==this.world.setup&&(this.world=new ss(e),this.applied=0,this.sent=0,(n=this.view)==null||n.setWorld(e),(a=this.view)==null||a.place(this.world.pose,this.world.trail),(s=this.view)==null||s.setLed(void 0),(r=this.view)==null||r.setScreen(void 0),this.updateStatus(),(o=this.onWorldChange)==null||o.call(this))}reset(){var e,t,n;this.world.reset(),this.applied=0,this.sent=0,this.realSensors=void 0,(e=this.view)==null||e.place(this.world.pose,this.world.trail),(t=this.view)==null||t.setLed(void 0),(n=this.view)==null||n.setScreen(void 0),this.updateStatus()}prepare(e){e.robotSensors={...this.controls,...this.world.sensors()}}setupControls(){for(const e of this.element.querySelectorAll(".visubot-controls input[type=range]")){const t=e.parentElement.querySelector("output"),n=()=>{this.controls[e.name]=Number(e.value),t.textContent=e.value};e.addEventListener("input",n),n()}for(const e of this.element.querySelectorAll(".visubot-controls button[name]"))e.addEventListener("click",()=>{const t=e.name;this.controls[t]=!0,e.classList.add("pressed"),window.clearTimeout(this.pressTimers.get(t)),this.pressTimers.set(t,window.setTimeout(()=>{this.controls[t]=!1,e.classList.remove("pressed")},1e3))})}setupCheck(){for(const e of this.check.querySelectorAll("button[data-py]"))e.addEventListener("click",()=>{const{after:t,wait:n}=e.dataset;oe.run(e.dataset.py).then(()=>t?new Promise(a=>setTimeout(a,Number(n))).then(()=>oe.run(t)):void 0).catch(a=>this.liveFailed(a))});this.check.addEventListener("toggle",()=>void this.readCheck())}async readCheck(){if(!this.checking){this.checking=!0;try{for(;this.check.open&&oe.connected;){for(const e of this.check.querySelectorAll("[data-sensor]")){if(!this.check.open||!oe.connected)break;const t=e.dataset.sensor,n=await oe.ask(wt[t].python).catch(()=>{});n!==void 0&&(e.textContent=typeof wt[t].simulated=="boolean"?n===!0||typeof n=="number"&&n!==0?"✓":"–":String(typeof n=="number"?Math.round(n*10)/10:n))}await new Promise(e=>setTimeout(e,200))}}finally{this.checking=!1}}}get live(){return oe.connected}async prepareLive(e,t=[]){const n={};for(const a of new Set(["getDistance","getLine",...t])){const s=await oe.ask(wt[a].python);typeof wt[a].simulated=="boolean"?n[a]=s===!0||typeof s=="number"&&s!==0:typeof wt[a].simulated=="string"?n[a]=typeof s=="string"?s:String(wt[a].simulated):n[a]=typeof s=="number"?a==="getDistance"?Math.round(s):s:0}this.realSensors=n,e.robotSensors={...this.controls,...this.world.sensors(),...n}}async drive(e){for(;this.sentsetTimeout(n,t.args[0]))}}liveFailed(e){oe.disconnect(e instanceof Error?e.message:String(e))}updateLive(){this.liveStatus.textContent=Lh(),this.liveStatus.classList.toggle("connected",oe.connected),this.check.hidden=!oe.connected,oe.connected||(this.check.open=!1),this.updateStatus()}follow(e,t){var a,s,r,o;for(;this.appliedl!==0);this.world.tick(Jl),n&&((o=this.view)==null||o.moveTo(this.world.pose,this.world.trail,t)),this.updateStatus()}dispose(){var e;this.stopListening();for(const t of this.pressTimers.values())window.clearTimeout(t);(e=this.view)==null||e.dispose(),this.view=void 0,this.loading=void 0}updateStatus(){const e=this.world.lineState().toString(2).padStart(4,"0"),t=[`${p("web_visubot_distance")}: ${this.world.distance()} cm`,`${p("web_visubot_line")}: ${e}`];this.world.bumps>0&&t.push(`⚠︎ ${p("web_visubot_bumps")}: ${this.world.bumps}`),this.world.screen!==void 0&&t.push(`📺 ${this.world.screen}`),this.realSensors&&oe.connected&&t.push(`🤖 ${p("web_visubot_distance")}: ${this.realSensors.getDistance} cm · ${p("web_visubot_line")}: ${Number(this.realSensors.getLine).toString(2).padStart(4,"0")}`),this.status.textContent=t.join(" · ")}}let E1;function Mh(i,e){try{E1??(E1=new AudioContext);const t=E1.createOscillator(),n=E1.createGain();t.type="square",t.frequency.value=Math.max(20,Math.min(2e4,i)),n.gain.value=.05,t.connect(n).connect(E1.destination);const a=E1.currentTime+Math.min(Math.max(e,0),5e3)/1e3;t.start(),t.stop(a)}catch{}}function xD(){const i=(t,n,a,s,r)=>``,e=(t,n,a)=>``;return`
🎛 ${p("web_visubot_controls")}

${p("web_visubot_controls_hint")}

${i("getBrightness","web_visubot_sensor_brightness",0,100,50)} ${i("getLoudness","web_visubot_sensor_loudness",0,100,0)} @@ -60343,7 +60359,7 @@ ${a}`));this.body.append(s),this.foldReference(s)}}foldReference(e){const t="vis

${q(p("web_files_title"))}

- +
`,this.body=this.element.querySelector(".files-body");const e=(t,n)=>this.element.querySelector(`[data-files=${t}]`).addEventListener("click",n);e("hide",()=>this.host.hide()),e("new-folder",()=>void this.newFolder()),e("switch",()=>void this.switchWorkspace()),this.body.addEventListener("click",t=>void this.onTreeClick(t)),this.render()}async restore(){if(Eh(sa)==="browser")this.workspace=Ru();else if(na()){const e=await kD();e!=null&&e.ready?this.workspace=await Gu(e.handle):this.pending=e==null?void 0:e.handle}await this.render(),this.workspace||this.startDialog()}async startDialog(){var r;const e=p("web_learn_start_folder"),t=(o,l,u=!1,m)=>`${m?`

${q(m)}

`:""}`,n=na()?[this.pending?t("reconnect",`${ee.open} ${q(p("web_learn_start_continue_fmt",this.pending.name))}`,!0):"",t("pick",`${ee.open} ${q(p("web_learn_start_open"))}`,!this.pending),t("create",`${ee.newFolder} ${q(p("web_learn_start_create_fmt",e))}`,!1,p("web_learn_start_create_hint"))]:[t("browser",q(p("web_files_browser")),!0,p("web_files_browser_hint"))],a=document.createElement("div");a.className="confirm",a.innerHTML=` `,this.swingElement.append(this.swingDisplay),this.swingElement.querySelector(".console-hide").addEventListener("click",()=>{this.swingElement.hidden=!0,mF()});const e=this.consoleElement;this.consoleResizer.title=p("web_console_resize"),this.element.append(this.swingElement,this.consoleResizer,e),this.consoleLines=e.querySelector(".livecode-console-lines"),this.consoleForm=e.querySelector(".livecode-console-input"),this.consoleNotice=e.querySelector(".livecode-console-notice"),e.querySelector(".console-hide").addEventListener("click",()=>this.hideConsole()),this.runButton.addEventListener("click",()=>{var t;return(t=this.run)!=null&&t.paused?this.resume():this.startRun(!1)}),this.stepButton.addEventListener("click",()=>{var t;return(t=this.run)!=null&&t.paused?this.stepOnce():this.startRun(!0)}),this.stopButton.addEventListener("click",()=>this.stopRun(!0)),this.consoleForm.addEventListener("submit",t=>{t.preventDefault(),this.submitInput()}),this.run=void 0,this.view.addEventListener("click",t=>{const n=t.target.closest(".ln");if(!n||!this.view.classList.contains("selectable"))return;const a=_a(this.spans,Number(n.dataset.line));a&&this.onSelect(a.path)}),this.code=new tF(this.editor,{onChange:()=>this.codeChanged(),onCaret:()=>this.caretMoved(),onUndo:t=>this.onUndo(t),words:()=>this.snippetWords,breakpointLine:t=>{var n;return(n=_a(this.spans,t))==null?void 0:n.from},onBreakpoints:()=>this.breakpoints=this.code.breakpoints},p("web_live_edit_label")),this.editor.querySelector(".cm-gutters").title=p("web_debug_gutter_title"),this.breakpoints=new Set,this.debugLine=void 0,this.highlighted=void 0,this.html="",this.parsed=void 0,this.showMode()}javaFor(e,t){const n=this.textFor.get(e);if(n!==void 0)return n;const a=this.shown.get(t);return a?Xu(a.text,a.doc,e,this.labels,{},this.form):si(e,this.labels,this.form)}adoptJava(e,t){this.textFor.set(e,t),this.parsed=void 0,this.last&&this.refresh(this.last.doc,this.last.highlight,this.last.context)}documentFromJavaText(e){return Io({caption:"",elements:[]},zo(e,this.labels))}get javaForm(){return this.form}setJavaForm(e){this.form=e;try{localStorage.setItem(Bc,e.asClass?"1":"0"),localStorage.setItem(Dc,e.withMain?"1":"0")}catch{}this.textFor=new WeakMap,this.shown=new WeakMap,this.parsed=void 0,this.last&&this.refresh(this.last.doc,this.last.highlight,this.last.context)}get swingSupport(){return this.swing}setSwingSupport(e){this.swing=e;try{localStorage.setItem(Zc,e?"1":"0")}catch{}e||(this.swingElement.hidden=!0)}get language(){return this.target}setTarget(e){this.target=e;try{localStorage.setItem(yf,e)}catch{}this.showMode(),this.last&&this.refresh(this.last.doc,this.last.highlight,this.last.context)}showMode(){const e=this.target==="java";this.view.hidden=e,this.editor.hidden=!e,this.problemLine.hidden=!e,this.indentButton.hidden=!e,this.hint.textContent=p(e?"web_live_hint_edit":"web_live_hint"),this.element.querySelector(".livecode-lang").textContent={java:"Java",javascript:"JavaScript",python:"Python"}[this.target]}refresh(e,t,n){this.last={doc:e,highlight:t,context:n},this.target==="java"?this.refreshEditor(e,t,n):this.refreshView(e,t,n.editable)}refreshView(e,t,n){var l;const a=lh(e,this.target,this.labels);this.spans=a.spans;const s=t&&a.spans.find(u=>H1(u.path,t));this.view.classList.toggle("selectable",n);const r=a.text.split(` -`).map((u,m)=>`
${fF(u)||" "}
`).join("");r!==this.html&&(this.view.innerHTML=r),this.html=r;const o=s?`${s.from}-${s.to}`:void 0;o&&o!==this.highlighted&&((l=this.view.querySelector(`.ln[data-line="${s.from}"]`))==null||l.scrollIntoView({block:"nearest"})),this.highlighted=o}startRun(e){var n,a;if((n=this.onRobotRun)!=null&&n.call(this,e))return;const t=this.target==="java"?this.problems.find(s=>s.key==="web_parse_missing_import"||s.key==="web_parse_missing_scanner"):void 0;if(t){this.stopRun(!1),this.setConsoleVisible(!0),this.consoleLines.replaceChildren(),this.consoleNotice.textContent=p("web_parse_line_fmt",this.code.lineAt(t.from)+1,p(t.key,t.arg??"")),this.consoleNotice.classList.add("error"),this.showProblems=!0,this.drawMarks((a=this.last)==null?void 0:a.highlight);return}if(this.swing&&this.target==="java"&&!e&&this.code.breakpoints.size===0)return void this.startJavaRun();this.last&&(this.stopRun(!1),this.run={engine:new fi(this.last.doc,this.last.context.resolve),doc:this.last.doc,printed:0,paused:!1,stepping:e,debugged:!1},this.breakpoints=this.code.breakpoints,this.debugPanel.hidden=!0,this.setConsoleVisible(!0),this.consoleLines.replaceChildren(),this.consoleNotice.textContent="",this.consoleNotice.classList.remove("error"),this.setRunning(!0),e?this.pause():this.continueRun(!1))}async startJavaRun(){var e;this.stopRun(!1),(e=this.stopWatchingFiles)==null||e.call(this),this.setConsoleVisible(!0),this.consoleLines.replaceChildren(),this.consoleLines.id="console",this.consoleForm.hidden=!0,this.consoleNotice.classList.remove("error"),this.runButton.disabled=this.stepButton.disabled=!0;try{this.consoleNotice.textContent=p("web_live_swing_loading"),await sF(this.swingDisplay),this.consoleNotice.textContent=p("web_live_swing_compiling");const{result:t,files:n}=await dF(this.code.text,()=>this.swingElement.hidden=!1);this.showWrittenFiles(n),this.consoleNotice.textContent=p({"compile-error":"web_live_swing_compile_failed",windows:"web_live_swing_running",finished:"web_live_run_finished"}[t]),this.consoleNotice.classList.toggle("error",t==="compile-error"),this.swingElement.hidden=t!=="windows",t==="windows"&&(this.stopWatchingFiles=cF(n,a=>this.showWrittenFiles(a)))}catch{this.consoleNotice.textContent=p("web_live_swing_failed"),this.consoleNotice.classList.add("error")}this.runButton.disabled=this.stepButton.disabled=!1}continueRun(e){const t=this.run;if(!t)return;const{engine:n}=t;for(let a=0;athis.continueRun(!1),0))}afterSteps(){const e=this.run,t=e.engine.state;return this.printNewLines(),t.inputRequest?(this.askInput(),!0):t.isHalted||!e.engine.canStep?(this.showWrittenFiles(t.files),this.finishRun(t.isHalted&&t.notice?Qn(t.notice):p("web_live_run_finished"),t.isHalted),!0):!1}atBreakpoint(e){if(!e||e.callPath||e.kind==="forLoopIncrement"||e.kind==="forLoopStart"||e.kind==="callEnd")return!1;const t=this.lineOf(e.path);return t!==void 0&&this.breakpoints.has(t)}lineOf(e){var t;return e&&((t=this.spans.find(n=>H1(n.path,e)))==null?void 0:t.from)}pause(){var a,s;const e=this.run;e.paused=!0,e.debugged=!0;const t=e.engine.currentStepPath;this.debugLine=this.lineOf(t),this.consoleNotice.classList.remove("error"),this.consoleNotice.textContent=this.debugLine===void 0?"":p("web_debug_paused_fmt",this.debugLine+1),this.showVariables(),this.setRunning(!0);const n=(a=this.last)==null?void 0:a.highlight;t&&!(n&&H1(n,t))?this.onSelect(t):this.drawMarks((s=this.last)==null?void 0:s.highlight)}resume(){const e=this.run;e!=null&&e.paused&&(e.paused=!1,e.stepping=!1,this.leavePause(),this.continueRun(!0))}stepOnce(){var a,s;const e=this.run;if(!(e!=null&&e.paused))return;e.paused=!1,e.stepping=!0,this.leavePause();const{engine:t}=e,n=(a=t.steps[t.state.stepIndex])==null?void 0:a.kind;t.step(),(n==="forLoopStart"||n==="forLoopIncrement")&&t.canStep&&((s=t.steps[t.state.stepIndex])==null?void 0:s.kind)==="forLoopCondition"&&t.step(),this.afterSteps()||this.pause()}leavePause(){var e;this.debugLine=void 0,this.consoleNotice.textContent="",this.setRunning(!0),this.drawMarks((e=this.last)==null?void 0:e.highlight)}showVariables(){const e=this.run,t=e.engine.state.variables;this.debugPanel.hidden=!1;const n=[...t.keys()].sort((a,s)=>a.localeCompare(s));if(n.length===0)this.debugVars.innerHTML=`

${he(p("simulation_variables_placeholder"))}

`;else{const a=document.createElement("table");for(const s of n){const r=t.get(s),o=ke(r),l=a.insertRow();l.insertCell().textContent=s;const u=l.insertCell();r.kind==="grid"?u.append(Ph(r)):u.textContent=o,e.values&&e.values.get(s)!==o&&l.classList.add("changed")}this.debugVars.replaceChildren(a)}e.values=new Map(n.map(a=>[a,ke(t.get(a))]))}printNewLines(e){const t=this.run;if(!t)return;const n=t.engine.state.outputLines;for(;t.printedn.focus())}submitInput(){const e=this.run;if(!(e!=null&&e.engine.state.inputRequest))return;const t=this.consoleForm.querySelector("input"),n=e.engine.state.inputRequest.prompt;if(e.engine.provideInput(t.value),e.engine.state.inputRequest)return this.askInput();if(this.printNewLines({prompt:n,value:t.value}),t.value="",this.consoleForm.hidden=!0,!e.stepping)return this.continueRun(!1);this.afterSteps()||this.pause()}stopRun(e){var t;this.run&&(window.clearTimeout(this.run.timer),e&&this.finishRun(p("web_live_run_stopped"),!1),this.run=void 0,this.debugLine=void 0,this.debugPanel.hidden=!0,this.setRunning(!1),this.drawMarks((t=this.last)==null?void 0:t.highlight))}finishRun(e,t){var n,a;this.run&&window.clearTimeout(this.run.timer),this.consoleForm.hidden=!0,this.consoleNotice.textContent=e,this.consoleNotice.classList.toggle("error",t),(n=this.run)!=null&&n.debugged?this.showVariables():this.debugPanel.hidden=!0,this.run=void 0,this.debugLine=void 0,this.setRunning(!1),this.drawMarks((a=this.last)==null?void 0:a.highlight)}showTranscript(e){this.stopRun(!1),this.setConsoleVisible(!0),this.consoleForm.hidden=!0,this.consoleLines.replaceChildren();for(const t of e.lines){const n=this.consoleLine(t.text);if(t.typed!==void 0){const a=document.createElement("span");a.className="typed",a.textContent=t.typed,n.append(a)}}e.pending!==void 0&&this.consoleLine(e.pending).classList.add("pending"),this.consoleLines.scrollTop=this.consoleLines.scrollHeight,this.consoleNotice.textContent=e.notice??"",this.consoleNotice.classList.toggle("error",e.error)}hideConsole(){this.stopRun(!1),this.setConsoleVisible(!1)}setConsoleVisible(e){this.consoleElement.hidden!==!e&&(this.consoleElement.hidden=!e,this.consoleResizer.hidden=!e)}makeConsoleResizer(){const e=document.createElement("div");e.className="console-resizer",e.hidden=!0,e.tabIndex=0,e.setAttribute("role","separator"),e.setAttribute("aria-orientation","horizontal");const t=this.consoleElement,n=r=>Math.round(Math.max(80,Math.min(r,this.element.getBoundingClientRect().height-160))),a=(r,o)=>{t.style.height=r===void 0?"":`${n(r)}px`,o&&gF(Mc,r===void 0?"":String(n(r)))},s=Number(hF(Mc));return s>0&&(t.style.height=`${s}px`),e.addEventListener("pointerdown",r=>{if(r.button!==0)return;r.preventDefault(),e.setPointerCapture(r.pointerId);const o=r.clientY,l=t.getBoundingClientRect().height;e.classList.add("dragging");const u=c=>a(l-(c.clientY-o),!1),m=c=>{e.removeEventListener("pointermove",u),e.removeEventListener("pointerup",m),e.removeEventListener("pointercancel",m),e.classList.remove("dragging"),a(l-(c.clientY-o),!0)};e.addEventListener("pointermove",u),e.addEventListener("pointerup",m),e.addEventListener("pointercancel",m)}),e.addEventListener("dblclick",()=>a(void 0,!0)),e.addEventListener("keydown",r=>{const o=r.key==="ArrowUp"?20:r.key==="ArrowDown"?-20:0;o&&(r.preventDefault(),a(t.getBoundingClientRect().height+o,!0))}),e}setRunning(e){var a,s;const t=!!((a=this.run)!=null&&a.paused);this.runButton.disabled=e&&!t,this.stepButton.disabled=e&&!t,this.stopButton.disabled=!e,this.indentButton.disabled=e;const n=p(t?"web_debug_continue":"web_live_run_title");this.runButton.dataset.tip=n,this.runButton.setAttribute("aria-label",t?n:p("web_live_run")),this.element.classList.toggle("running",e&&!t),this.element.classList.toggle("debugging",t),this.code.setReadOnly(e||!((s=this.last)!=null&&s.context.editable))}textForDocument(e,t){const n=this.textFor.get(e);if(n!==void 0)return n;const a=this.shown.get(t.owner);return a?yF(a.text,Xu(a.text,a.doc,e,this.labels,{subprograms:t.subprograms},this.form)):si(e,this.labels,this.form)}refreshEditor(e,t,n){var r;const a=this.textForDocument(e,n);this.textFor.set(e,a),this.shown.set(n.owner,{doc:e,text:a}),this.run&&this.run.doc!==e&&this.stopRun(!1),this.code.setReadOnly(!n.editable||!!this.run),this.code.text!==a?(this.code.setText(a),this.analyze(a,n)):this.parsed||this.analyze(a,n);const s=Nh(e,this.labels,this.form);this.spans=a===s.text?s.spans:((r=this.parsed)==null?void 0:r.spans)??[],this.drawMarks(t)}analyze(e,t){this.parsed=zo(e,this.labels,{subprograms:t.subprograms}),this.placeholders=this.parsed.placeholders,this.problems=this.parsed.problems}drawMarks(e){var r;const t=e&&this.spans.find(o=>H1(o.path,e)),n=t?`${t.from}-${t.to}`:void 0,a=((r=this.last)==null?void 0:r.context.editable)===!1&&t?t.from:void 0;this.code.setMarks({placeholders:this.placeholders,problems:this.showProblems?this.problems:[],lines:t&&a===void 0?{from:t.from,to:t.to}:void 0,current:this.debugLine??a},n!==void 0&&n!==this.highlighted&&!this.code.hasFocus);const s=this.showProblems?this.problems[0]:void 0;this.problemLine.textContent=s?p("web_parse_line_fmt",this.code.lineAt(s.from)+1,p(s.key,s.arg??"")):"",this.highlighted=n}codeChanged(){var u,m,c,d;const e=(u=this.last)==null?void 0:u.context,t=(m=this.last)==null?void 0:m.doc;if(!e||!t)return;const n=this.code.text;this.analyze(n,e);const a=Io(t,this.parsed),s=JSON.stringify([a.caption,a.elements])===JSON.stringify([t.caption,t.elements]),r=s?t:a;this.textFor.set(r,n),this.shown.set(e.owner,{doc:r,text:n}),this.showProblems=!1,window.clearTimeout(this.problemTimer),this.problemTimer=window.setTimeout(()=>{var h;this.showProblems=!0,this.drawMarks((h=this.last)==null?void 0:h.highlight)},xF);const o=this.code.lineAt(this.code.caret),l=(c=_a(this.parsed.spans,o))==null?void 0:c.path;s?(this.spans=this.parsed.spans,this.drawMarks((d=this.last)==null?void 0:d.highlight),l&&this.onSelect(l)):this.onCode(r,l)}caretMoved(){var n,a;const e=_a(this.spans,this.code.lineAt(this.code.caret)),t=(n=this.last)==null?void 0:n.highlight;e&&((a=this.last)!=null&&a.context.editable)&&!(t&&H1(t,e.path))&&this.onSelect(e.path)}get snippetWords(){const e=this.labels;return{condition:e.condition,selector:e.selector,code:e.code,start:e.start,step:e.step,branch:p("element_verzweigung"),branchElse:p("element_verzweigung"),switchCase:p("element_fallauswahl"),forLoop:p("element_forSchleife"),whileLoop:p("element_whileSchleife"),doLoop:p("element_doUntilSchleife"),output:p("inspector_io_mode_output"),input:p("inspector_io_mode_input")}}}function yF(i,e){const t=i.split(` +`).map((u,m)=>`
${fF(u)||" "}
`).join("");r!==this.html&&(this.view.innerHTML=r),this.html=r;const o=s?`${s.from}-${s.to}`:void 0;o&&o!==this.highlighted&&((l=this.view.querySelector(`.ln[data-line="${s.from}"]`))==null||l.scrollIntoView({block:"nearest"})),this.highlighted=o}startRun(e){var n,a;if((n=this.onRobotRun)!=null&&n.call(this,e))return;const t=this.target==="java"?this.problems.find(s=>s.key==="web_parse_missing_import"||s.key==="web_parse_missing_scanner"):void 0;if(t){this.stopRun(!1),this.setConsoleVisible(!0),this.consoleLines.replaceChildren(),this.consoleNotice.textContent=p("web_parse_line_fmt",this.code.lineAt(t.from)+1,p(t.key,t.arg??"")),this.consoleNotice.classList.add("error"),this.showProblems=!0,this.drawMarks((a=this.last)==null?void 0:a.highlight);return}if(this.swing&&this.target==="java"&&!e&&this.code.breakpoints.size===0)return void this.startJavaRun();this.last&&(this.stopRun(!1),this.run={engine:new fi(this.last.doc,this.last.context.resolve),doc:this.last.doc,printed:0,paused:!1,stepping:e,debugged:!1},this.breakpoints=this.code.breakpoints,this.debugPanel.hidden=!0,this.setConsoleVisible(!0),this.consoleLines.replaceChildren(),this.consoleNotice.textContent="",this.consoleNotice.classList.remove("error"),this.setRunning(!0),e?this.pause():this.continueRun(!1))}async startJavaRun(){var e;this.stopRun(!1),(e=this.stopWatchingFiles)==null||e.call(this),this.setConsoleVisible(!0),this.consoleLines.replaceChildren(),this.consoleLines.id="console",this.consoleForm.hidden=!0,this.consoleNotice.classList.remove("error"),this.runButton.disabled=this.stepButton.disabled=!0;try{this.consoleNotice.textContent=p("web_live_swing_loading"),await sF(this.swingDisplay),this.consoleNotice.textContent=p("web_live_swing_compiling");const{result:t,files:n}=await dF(this.code.text,()=>this.swingElement.hidden=!1);this.showWrittenFiles(n),this.consoleNotice.textContent=p({"compile-error":"web_live_swing_compile_failed",windows:"web_live_swing_running",finished:"web_live_run_finished"}[t]),this.consoleNotice.classList.toggle("error",t==="compile-error"),this.swingElement.hidden=t!=="windows",t==="windows"&&(this.stopWatchingFiles=cF(n,a=>this.showWrittenFiles(a)))}catch{this.consoleNotice.textContent=p("web_live_swing_failed"),this.consoleNotice.classList.add("error")}this.runButton.disabled=this.stepButton.disabled=!1}continueRun(e){const t=this.run;if(!t)return;const{engine:n}=t;for(let a=0;athis.continueRun(!1),0))}afterSteps(){const e=this.run,t=e.engine.state;return this.printNewLines(),t.inputRequest?(this.askInput(),!0):t.isHalted||!e.engine.canStep?(this.showWrittenFiles(t.files),this.finishRun(t.isHalted&&t.notice?qn(t.notice):p("web_live_run_finished"),t.isHalted),!0):!1}atBreakpoint(e){if(!e||e.callPath||e.kind==="forLoopIncrement"||e.kind==="forLoopStart"||e.kind==="callEnd")return!1;const t=this.lineOf(e.path);return t!==void 0&&this.breakpoints.has(t)}lineOf(e){var t;return e&&((t=this.spans.find(n=>H1(n.path,e)))==null?void 0:t.from)}pause(){var a,s;const e=this.run;e.paused=!0,e.debugged=!0;const t=e.engine.currentStepPath;this.debugLine=this.lineOf(t),this.consoleNotice.classList.remove("error"),this.consoleNotice.textContent=this.debugLine===void 0?"":p("web_debug_paused_fmt",this.debugLine+1),this.showVariables(),this.setRunning(!0);const n=(a=this.last)==null?void 0:a.highlight;t&&!(n&&H1(n,t))?this.onSelect(t):this.drawMarks((s=this.last)==null?void 0:s.highlight)}resume(){const e=this.run;e!=null&&e.paused&&(e.paused=!1,e.stepping=!1,this.leavePause(),this.continueRun(!0))}stepOnce(){var a,s;const e=this.run;if(!(e!=null&&e.paused))return;e.paused=!1,e.stepping=!0,this.leavePause();const{engine:t}=e,n=(a=t.steps[t.state.stepIndex])==null?void 0:a.kind;t.step(),(n==="forLoopStart"||n==="forLoopIncrement")&&t.canStep&&((s=t.steps[t.state.stepIndex])==null?void 0:s.kind)==="forLoopCondition"&&t.step(),this.afterSteps()||this.pause()}leavePause(){var e;this.debugLine=void 0,this.consoleNotice.textContent="",this.setRunning(!0),this.drawMarks((e=this.last)==null?void 0:e.highlight)}showVariables(){const e=this.run,t=e.engine.state.variables;this.debugPanel.hidden=!1;const n=[...t.keys()].sort((a,s)=>a.localeCompare(s));if(n.length===0)this.debugVars.innerHTML=`

${he(p("simulation_variables_placeholder"))}

`;else{const a=document.createElement("table");for(const s of n){const r=t.get(s),o=ke(r),l=a.insertRow();l.insertCell().textContent=s;const u=l.insertCell();r.kind==="grid"?u.append(Ph(r)):u.textContent=o,e.values&&e.values.get(s)!==o&&l.classList.add("changed")}this.debugVars.replaceChildren(a)}e.values=new Map(n.map(a=>[a,ke(t.get(a))]))}printNewLines(e){const t=this.run;if(!t)return;const n=t.engine.state.outputLines;for(;t.printedn.focus())}submitInput(){const e=this.run;if(!(e!=null&&e.engine.state.inputRequest))return;const t=this.consoleForm.querySelector("input"),{prompt:n,continuesLine:a}=e.engine.state.inputRequest;if(e.engine.provideInput(t.value),e.engine.state.inputRequest)return this.askInput();if(this.printNewLines({prompt:n,value:t.value,continuesLine:a}),t.value="",this.consoleForm.hidden=!0,!e.stepping)return this.continueRun(!1);this.afterSteps()||this.pause()}stopRun(e){var t;this.run&&(window.clearTimeout(this.run.timer),e&&this.finishRun(p("web_live_run_stopped"),!1),this.run=void 0,this.debugLine=void 0,this.debugPanel.hidden=!0,this.setRunning(!1),this.drawMarks((t=this.last)==null?void 0:t.highlight))}finishRun(e,t){var n,a;this.run&&window.clearTimeout(this.run.timer),this.consoleForm.hidden=!0,this.consoleNotice.textContent=e,this.consoleNotice.classList.toggle("error",t),(n=this.run)!=null&&n.debugged?this.showVariables():this.debugPanel.hidden=!0,this.run=void 0,this.debugLine=void 0,this.setRunning(!1),this.drawMarks((a=this.last)==null?void 0:a.highlight)}showTranscript(e){this.stopRun(!1),this.setConsoleVisible(!0),this.consoleForm.hidden=!0,this.consoleLines.replaceChildren();for(const t of e.lines){const n=this.consoleLine(t.text);if(t.typed!==void 0){const a=document.createElement("span");a.className="typed",a.textContent=t.typed,n.append(a)}}e.pending!==void 0&&this.consoleLine(e.pending).classList.add("pending"),this.consoleLines.scrollTop=this.consoleLines.scrollHeight,this.consoleNotice.textContent=e.notice??"",this.consoleNotice.classList.toggle("error",e.error)}hideConsole(){this.stopRun(!1),this.setConsoleVisible(!1)}setConsoleVisible(e){this.consoleElement.hidden!==!e&&(this.consoleElement.hidden=!e,this.consoleResizer.hidden=!e)}makeConsoleResizer(){const e=document.createElement("div");e.className="console-resizer",e.hidden=!0,e.tabIndex=0,e.setAttribute("role","separator"),e.setAttribute("aria-orientation","horizontal");const t=this.consoleElement,n=r=>Math.round(Math.max(80,Math.min(r,this.element.getBoundingClientRect().height-160))),a=(r,o)=>{t.style.height=r===void 0?"":`${n(r)}px`,o&&gF(Mc,r===void 0?"":String(n(r)))},s=Number(hF(Mc));return s>0&&(t.style.height=`${s}px`),e.addEventListener("pointerdown",r=>{if(r.button!==0)return;r.preventDefault(),e.setPointerCapture(r.pointerId);const o=r.clientY,l=t.getBoundingClientRect().height;e.classList.add("dragging");const u=c=>a(l-(c.clientY-o),!1),m=c=>{e.removeEventListener("pointermove",u),e.removeEventListener("pointerup",m),e.removeEventListener("pointercancel",m),e.classList.remove("dragging"),a(l-(c.clientY-o),!0)};e.addEventListener("pointermove",u),e.addEventListener("pointerup",m),e.addEventListener("pointercancel",m)}),e.addEventListener("dblclick",()=>a(void 0,!0)),e.addEventListener("keydown",r=>{const o=r.key==="ArrowUp"?20:r.key==="ArrowDown"?-20:0;o&&(r.preventDefault(),a(t.getBoundingClientRect().height+o,!0))}),e}setRunning(e){var a,s;const t=!!((a=this.run)!=null&&a.paused);this.runButton.disabled=e&&!t,this.stepButton.disabled=e&&!t,this.stopButton.disabled=!e,this.indentButton.disabled=e;const n=p(t?"web_debug_continue":"web_live_run_title");this.runButton.dataset.tip=n,this.runButton.setAttribute("aria-label",t?n:p("web_live_run")),this.element.classList.toggle("running",e&&!t),this.element.classList.toggle("debugging",t),this.code.setReadOnly(e||!((s=this.last)!=null&&s.context.editable))}textForDocument(e,t){const n=this.textFor.get(e);if(n!==void 0)return n;const a=this.shown.get(t.owner);return a?yF(a.text,Xu(a.text,a.doc,e,this.labels,{subprograms:t.subprograms},this.form)):si(e,this.labels,this.form)}refreshEditor(e,t,n){var r;const a=this.textForDocument(e,n);this.textFor.set(e,a),this.shown.set(n.owner,{doc:e,text:a}),this.run&&this.run.doc!==e&&this.stopRun(!1),this.code.setReadOnly(!n.editable||!!this.run),this.code.text!==a?(this.code.setText(a),this.analyze(a,n)):this.parsed||this.analyze(a,n);const s=Nh(e,this.labels,this.form);this.spans=a===s.text?s.spans:((r=this.parsed)==null?void 0:r.spans)??[],this.drawMarks(t)}analyze(e,t){this.parsed=zo(e,this.labels,{subprograms:t.subprograms}),this.placeholders=this.parsed.placeholders,this.problems=this.parsed.problems}drawMarks(e){var r;const t=e&&this.spans.find(o=>H1(o.path,e)),n=t?`${t.from}-${t.to}`:void 0,a=((r=this.last)==null?void 0:r.context.editable)===!1&&t?t.from:void 0;this.code.setMarks({placeholders:this.placeholders,problems:this.showProblems?this.problems:[],lines:t&&a===void 0?{from:t.from,to:t.to}:void 0,current:this.debugLine??a},n!==void 0&&n!==this.highlighted&&!this.code.hasFocus);const s=this.showProblems?this.problems[0]:void 0;this.problemLine.textContent=s?p("web_parse_line_fmt",this.code.lineAt(s.from)+1,p(s.key,s.arg??"")):"",this.highlighted=n}codeChanged(){var u,m,c,d;const e=(u=this.last)==null?void 0:u.context,t=(m=this.last)==null?void 0:m.doc;if(!e||!t)return;const n=this.code.text;this.analyze(n,e);const a=Io(t,this.parsed),s=JSON.stringify([a.caption,a.elements])===JSON.stringify([t.caption,t.elements]),r=s?t:a;this.textFor.set(r,n),this.shown.set(e.owner,{doc:r,text:n}),this.showProblems=!1,window.clearTimeout(this.problemTimer),this.problemTimer=window.setTimeout(()=>{var h;this.showProblems=!0,this.drawMarks((h=this.last)==null?void 0:h.highlight)},xF);const o=this.code.lineAt(this.code.caret),l=(c=_a(this.parsed.spans,o))==null?void 0:c.path;s?(this.spans=this.parsed.spans,this.drawMarks((d=this.last)==null?void 0:d.highlight),l&&this.onSelect(l)):this.onCode(r,l)}caretMoved(){var n,a;const e=_a(this.spans,this.code.lineAt(this.code.caret)),t=(n=this.last)==null?void 0:n.highlight;e&&((a=this.last)!=null&&a.context.editable)&&!(t&&H1(t,e.path))&&this.onSelect(e.path)}get snippetWords(){const e=this.labels;return{condition:e.condition,selector:e.selector,code:e.code,start:e.start,step:e.step,branch:p("element_verzweigung"),branchElse:p("element_verzweigung"),switchCase:p("element_fallauswahl"),forLoop:p("element_forSchleife"),whileLoop:p("element_whileSchleife"),doLoop:p("element_doUntilSchleife"),output:p("inspector_io_mode_output"),input:p("inspector_io_mode_input")}}}function yF(i,e){const t=i.split(` `),n=e.split(` `);let a=0;for(;aa?lf(e,a+1,n.length-s):e}const wF=5e3;function zF(i,e,t,n={}){const a=new fi(i,e),s=new ss(t),r=m=>({pose:{...s.pose},trail:s.trail.map(c=>({...c})),leds:[...s.leds],screen:s.screen,tone:m}),o=[r()];let l=0;const u=(m,c)=>({frames:o,stop:m,notice:c,bumps:s.bumps,distance:Math.round(s.trail.slice(1).reduce((d,h,g)=>d+Math.hypot(h.x-s.trail[g].x,h.y-s.trail[g].y),0))});for(let m=0;mh!==0);s.tick(Jl),d&&o.push(r())}return u("limit")}const fn=i=>i.replace(/&/g,"&").replace(//g,">").replace(/"/g,"""),Jr=300;class IF{constructor(){y(this,"element");y(this,"rail");y(this,"heightBar");y(this,"onHide",()=>{});y(this,"onToggleStacked",()=>{});y(this,"stage");y(this,"status");y(this,"picker");y(this,"playButton");y(this,"stackButton");y(this,"view");y(this,"loading");y(this,"worlds",[]);y(this,"worldsKey");y(this,"setup",bi);y(this,"result");y(this,"lastKey");y(this,"pending");y(this,"playTimer");y(this,"input");this.element=document.createElement("aside"),this.element.className="robotpreview",this.element.innerHTML=` @@ -60532,13 +60548,13 @@ ${i}

🤖 ${fn(p("web_visubot_preview_title"))}

- +

${fn(p("web_visubot_preview_hint"))}

-

`;const e=t=>this.element.querySelector(t);this.heightBar=e(".robotpreview-height"),this.stage=e(".robotpreview-stage"),this.status=e(".robotpreview-status"),this.picker=e(".visubot-worlds"),this.playButton=e(".robotpreview-play"),this.stackButton=e(".robotpreview-stack"),this.playButton.addEventListener("click",()=>this.playTimer===void 0?this.play():this.stopPlaying(!0)),this.stackButton.addEventListener("click",()=>this.onToggleStacked()),e(".learn-hide").addEventListener("click",()=>this.onHide()),this.rail=document.createElement("button"),this.rail.className="learn-rail robotpreview-rail",this.setStacked(!1),this.relabel()}relabel(){const e=n=>this.element.querySelector(n);e("h2").textContent=`🤖 ${p("web_visubot_preview_title")}`,e(".hint").textContent=p("web_visubot_preview_hint"),this.heightBar.title=p("web_visubot_preview_resize");const t=e(".learn-hide");t.title=p("web_visubot_preview_hide"),t.setAttribute("aria-label",p("web_visubot_preview_hide")),this.rail.title=p("web_visubot_preview_show"),this.rail.innerHTML=`${$t}🤖 ${fn(p("web_visubot_preview_title"))}`,this.setStacked(this.stackButton.textContent==="▥"),this.stopPlaying(!1),this.worldsKey=void 0,this.lastKey=void 0}setStacked(e){const t=e?"web_visubot_preview_side":"web_visubot_preview_stack";this.stackButton.innerHTML=e?"▥":"⬓",this.stackButton.className="icon robotpreview-stack",this.stackButton.dataset.tip=p(t),this.stackButton.setAttribute("aria-label",p(t))}show(){this.loading??(this.loading=Q(async()=>{const{Robot3D:e}=await import("./robot3d-GGJ-E5MR.js");return{Robot3D:e}},[],import.meta.url).then(({Robot3D:e})=>{var t;this.view=new e(this.stage),this.view.setWorld(this.setup),this.showFrame((t=this.result)==null?void 0:t.frames.at(-1))}).catch(()=>{this.stage.textContent=p("web_visubot_no_3d")}))}update(e,t,n,a,s){this.show(),a!==this.worldsKey&&(this.worldsKey=a,this.setWorlds(n)),this.input={doc:e,resolve:t};const r=JSON.stringify(s)+` -`+JSON.stringify(e);r!==this.lastKey&&(this.lastKey=r,window.clearTimeout(this.pending),this.pending=window.setTimeout(()=>this.recompute(),120))}setWorlds(e){this.worlds=e,this.picker.replaceChildren(),this.picker.hidden=e.length<2,e.forEach((t,n)=>{const a=document.createElement("button");a.textContent=p("web_visubot_world_fmt",n+1),a.addEventListener("click",()=>this.useWorld(t)),this.picker.append(a)}),this.useWorld(e[0]??bi)}useWorld(e){var t;this.worlds.forEach((n,a)=>{var s;return(s=this.picker.children[a])==null?void 0:s.classList.toggle("active",n===e)}),!(e===this.setup&&this.result)&&(this.setup=e,(t=this.view)==null||t.setWorld(e),this.recompute())}recompute(){var e;if(this.pending=void 0,this.stopPlaying(!1),!!this.input){try{this.result=zF(this.input.doc,this.input.resolve,this.setup)}catch{this.result=void 0}this.showFrame((e=this.result)==null?void 0:e.frames.at(-1)),this.updateStatus()}}showFrame(e,t=0){if(!this.view)return;const n=e??{pose:{...this.setup.start},trail:[{x:this.setup.start.x,y:this.setup.start.y}],leds:Array(5).fill(void 0),screen:void 0};t>0?this.view.moveTo(n.pose,n.trail,t):this.view.place(n.pose,n.trail),this.view.setLeds(n.leds),this.view.setScreen(n.screen)}play(){var a;const e=(a=this.result)==null?void 0:a.frames;if(!e||e.length<2||!this.view)return;this.stopPlaying(!1);let t=0;this.showFrame(e[0]),this.playButton.innerHTML=ee.stop,this.playButton.dataset.tip=p("web_visubot_preview_stop"),this.playButton.setAttribute("aria-label",p("web_visubot_preview_stop"));const n=()=>{if(t++,t>=e.length){this.stopPlaying(!1);return}const s=e[t];s.tone&&Mh(s.tone[0],s.tone[1]),this.showFrame(s,Jr-30),this.playTimer=window.setTimeout(n,Jr)};this.playTimer=window.setTimeout(n,Jr)}stopPlaying(e){var t;this.playTimer!==void 0&&window.clearTimeout(this.playTimer),this.playTimer=void 0,this.playButton.innerHTML=ee.play,this.playButton.dataset.tip=p("web_visubot_preview_play"),this.playButton.setAttribute("aria-label",p("web_visubot_preview_play")),e&&this.showFrame((t=this.result)==null?void 0:t.frames.at(-1))}updateStatus(){const e=this.result;if(this.playButton.disabled=!e||e.frames.length<2,!e){this.status.textContent="";return}const t=[p("web_visubot_preview_distance_fmt",e.distance)];e.bumps>0&&t.push(`⚠︎ ${p("web_visubot_bumps")}: ${e.bumps}`),e.stop==="input"?t.push(p("web_visubot_preview_input")):e.stop==="limit"?t.push(p("web_visubot_preview_limit")):e.stop==="error"&&e.notice&&t.push(`⚠︎ ${Qn(e.notice)}`),this.status.textContent=t.join(" · ")}pause(){window.clearTimeout(this.pending),this.pending=void 0,this.lastKey=void 0,this.stopPlaying(!1)}}const kF={left:12,top:10},SF=8,js=8e3,hi=16,Rr=12,wf="#fafafa";function zf(i){const e=i.caption.trim();return e===""?p("diagram_title_placeholder"):e}function Lc(i){let e=i.trim().replace(/\.visustruct$/i,"");if(e==="")return"";for(e=e.replace(/\s/g,"-").replace(/[/:\\*?"<>|]/g,"-");e.includes("--");)e=e.replace(/--/g,"-");return e=e.replace(/^-+|-+$/g,""),e.length>120&&(e=e.slice(0,120).replace(/^-+|-+$/g,"")),e}function Wc(i,e){return Lc(i.caption)||Lc(e)||"VisuStruct"}function _F(i,e,t){const n=i.split(/\s+/),a=[];let s="";for(const r of n){const o=s?`${s} ${r}`:r;s&&t(o,hi,"bold")>e?(a.push(s),s=r):s=o}if(s&&a.push(s),a.length>2){let r=a.slice(1).join(" ");for(;r.length>1&&t(r+"…",hi,"bold")>e;)r=r.slice(0,-1);return[a[0],r+"…"]}return a}function Ec(i,e,t,n=320){const a={...i,elements:i.elements.map(Ha)},s=new bd(e,t).layout(a,kF),r=Math.min(js,Math.max(n,s.canvasSize.width)),o=Math.min(js,Math.max(n,s.canvasSize.height));if(r<=2||o<=2)return;const l=_F(zf(i),r-2*Rr,t),u=Math.ceil(hi*1.2),m=Math.min(56,l.length*u+2),c=m+o,d=new wd(e,t).render(s,{width:r,height:o},void 0,SF);d.setAttribute("y",String(m)),d.removeAttribute("class");const h=fe("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:c,viewBox:`0 0 ${r} ${c}`});h.append(fe("rect",{x:0,y:0,width:r,height:c,fill:wf}));const g=fe("text",{x:Rr,y:0,"font-family":Cs,"font-size":hi,"font-weight":600,fill:"black"});return l.forEach((f,x)=>{const b=fe("tspan",{x:Rr,y:x*u+hi});b.textContent=f,g.append(b)}),h.append(g,d),{svg:h,width:r,height:c}}function If(i){return` +

`;const e=t=>this.element.querySelector(t);this.heightBar=e(".robotpreview-height"),this.stage=e(".robotpreview-stage"),this.status=e(".robotpreview-status"),this.picker=e(".visubot-worlds"),this.playButton=e(".robotpreview-play"),this.stackButton=e(".robotpreview-stack"),this.playButton.addEventListener("click",()=>this.playTimer===void 0?this.play():this.stopPlaying(!0)),this.stackButton.addEventListener("click",()=>this.onToggleStacked()),e(".learn-hide").addEventListener("click",()=>this.onHide()),this.rail=document.createElement("button"),this.rail.className="learn-rail robotpreview-rail",this.setStacked(!1),this.relabel()}relabel(){const e=n=>this.element.querySelector(n);e("h2").textContent=`🤖 ${p("web_visubot_preview_title")}`,e(".hint").textContent=p("web_visubot_preview_hint"),this.heightBar.title=p("web_visubot_preview_resize");const t=e(".learn-hide");t.title=p("web_visubot_preview_hide"),t.setAttribute("aria-label",p("web_visubot_preview_hide")),this.rail.title=p("web_visubot_preview_show"),this.rail.innerHTML=`${Yt}🤖 ${fn(p("web_visubot_preview_title"))}`,this.setStacked(this.stackButton.textContent==="▥"),this.stopPlaying(!1),this.worldsKey=void 0,this.lastKey=void 0}setStacked(e){const t=e?"web_visubot_preview_side":"web_visubot_preview_stack";this.stackButton.innerHTML=e?"▥":"⬓",this.stackButton.className="icon robotpreview-stack",this.stackButton.dataset.tip=p(t),this.stackButton.setAttribute("aria-label",p(t))}show(){this.loading??(this.loading=Q(async()=>{const{Robot3D:e}=await import("./robot3d-FyDAbXTC.js");return{Robot3D:e}},[],import.meta.url).then(({Robot3D:e})=>{var t;this.view=new e(this.stage),this.view.setWorld(this.setup),this.showFrame((t=this.result)==null?void 0:t.frames.at(-1))}).catch(()=>{this.stage.textContent=p("web_visubot_no_3d")}))}update(e,t,n,a,s){this.show(),a!==this.worldsKey&&(this.worldsKey=a,this.setWorlds(n)),this.input={doc:e,resolve:t};const r=JSON.stringify(s)+` +`+JSON.stringify(e);r!==this.lastKey&&(this.lastKey=r,window.clearTimeout(this.pending),this.pending=window.setTimeout(()=>this.recompute(),120))}setWorlds(e){this.worlds=e,this.picker.replaceChildren(),this.picker.hidden=e.length<2,e.forEach((t,n)=>{const a=document.createElement("button");a.textContent=p("web_visubot_world_fmt",n+1),a.addEventListener("click",()=>this.useWorld(t)),this.picker.append(a)}),this.useWorld(e[0]??bi)}useWorld(e){var t;this.worlds.forEach((n,a)=>{var s;return(s=this.picker.children[a])==null?void 0:s.classList.toggle("active",n===e)}),!(e===this.setup&&this.result)&&(this.setup=e,(t=this.view)==null||t.setWorld(e),this.recompute())}recompute(){var e;if(this.pending=void 0,this.stopPlaying(!1),!!this.input){try{this.result=zF(this.input.doc,this.input.resolve,this.setup)}catch{this.result=void 0}this.showFrame((e=this.result)==null?void 0:e.frames.at(-1)),this.updateStatus()}}showFrame(e,t=0){if(!this.view)return;const n=e??{pose:{...this.setup.start},trail:[{x:this.setup.start.x,y:this.setup.start.y}],leds:Array(5).fill(void 0),screen:void 0};t>0?this.view.moveTo(n.pose,n.trail,t):this.view.place(n.pose,n.trail),this.view.setLeds(n.leds),this.view.setScreen(n.screen)}play(){var a;const e=(a=this.result)==null?void 0:a.frames;if(!e||e.length<2||!this.view)return;this.stopPlaying(!1);let t=0;this.showFrame(e[0]),this.playButton.innerHTML=ee.stop,this.playButton.dataset.tip=p("web_visubot_preview_stop"),this.playButton.setAttribute("aria-label",p("web_visubot_preview_stop"));const n=()=>{if(t++,t>=e.length){this.stopPlaying(!1);return}const s=e[t];s.tone&&Mh(s.tone[0],s.tone[1]),this.showFrame(s,Jr-30),this.playTimer=window.setTimeout(n,Jr)};this.playTimer=window.setTimeout(n,Jr)}stopPlaying(e){var t;this.playTimer!==void 0&&window.clearTimeout(this.playTimer),this.playTimer=void 0,this.playButton.innerHTML=ee.play,this.playButton.dataset.tip=p("web_visubot_preview_play"),this.playButton.setAttribute("aria-label",p("web_visubot_preview_play")),e&&this.showFrame((t=this.result)==null?void 0:t.frames.at(-1))}updateStatus(){const e=this.result;if(this.playButton.disabled=!e||e.frames.length<2,!e){this.status.textContent="";return}const t=[p("web_visubot_preview_distance_fmt",e.distance)];e.bumps>0&&t.push(`⚠︎ ${p("web_visubot_bumps")}: ${e.bumps}`),e.stop==="input"?t.push(p("web_visubot_preview_input")):e.stop==="limit"?t.push(p("web_visubot_preview_limit")):e.stop==="error"&&e.notice&&t.push(`⚠︎ ${qn(e.notice)}`),this.status.textContent=t.join(" · ")}pause(){window.clearTimeout(this.pending),this.pending=void 0,this.lastKey=void 0,this.stopPlaying(!1)}}const kF={left:12,top:10},SF=8,js=8e3,hi=16,Rr=12,wf="#fafafa";function zf(i){const e=i.caption.trim();return e===""?p("diagram_title_placeholder"):e}function Lc(i){let e=i.trim().replace(/\.visustruct$/i,"");if(e==="")return"";for(e=e.replace(/\s/g,"-").replace(/[/:\\*?"<>|]/g,"-");e.includes("--");)e=e.replace(/--/g,"-");return e=e.replace(/^-+|-+$/g,""),e.length>120&&(e=e.slice(0,120).replace(/^-+|-+$/g,"")),e}function Wc(i,e){return Lc(i.caption)||Lc(e)||"VisuStruct"}function _F(i,e,t){const n=i.split(/\s+/),a=[];let s="";for(const r of n){const o=s?`${s} ${r}`:r;s&&t(o,hi,"bold")>e?(a.push(s),s=r):s=o}if(s&&a.push(s),a.length>2){let r=a.slice(1).join(" ");for(;r.length>1&&t(r+"…",hi,"bold")>e;)r=r.slice(0,-1);return[a[0],r+"…"]}return a}function Ec(i,e,t,n=320){const a={...i,elements:i.elements.map(Ha)},s=new bd(e,t).layout(a,kF),r=Math.min(js,Math.max(n,s.canvasSize.width)),o=Math.min(js,Math.max(n,s.canvasSize.height));if(r<=2||o<=2)return;const l=_F(zf(i),r-2*Rr,t),u=Math.ceil(hi*1.2),m=Math.min(56,l.length*u+2),c=m+o,d=new wd(e,t).render(s,{width:r,height:o},void 0,SF);d.setAttribute("y",String(m)),d.removeAttribute("class");const h=fe("svg",{xmlns:"http://www.w3.org/2000/svg",width:r,height:c,viewBox:`0 0 ${r} ${c}`});h.append(fe("rect",{x:0,y:0,width:r,height:c,fill:wf}));const g=fe("text",{x:Rr,y:0,"font-family":Cs,"font-size":hi,"font-weight":600,fill:"black"});return l.forEach((f,x)=>{const b=fe("tspan",{x:Rr,y:x*u+hi});b.textContent=f,g.append(b)}),h.append(g,d),{svg:h,width:r,height:c}}function If(i){return` `+new XMLSerializer().serializeToString(i.svg)}async function Nc(i,e){const t=Math.max(1,Math.min(e,js/i.width,js/i.height)),n=URL.createObjectURL(new Blob([If(i)],{type:"image/svg+xml"}));try{const a=new Image;a.src=n,await a.decode();const s=document.createElement("canvas");s.width=Math.round(i.width*t),s.height=Math.round(i.height*t);const r=s.getContext("2d");return r.fillStyle=wf,r.fillRect(0,0,s.width,s.height),r.drawImage(a,0,0,s.width,s.height),s}finally{URL.revokeObjectURL(n)}}function TF(i){return new Promise((e,t)=>i.toBlob(n=>n?e(n):t(new Error("PNG konnte nicht erzeugt werden.")),"image/png"))}function OF(i,e){const a=Math.max(1,i),s=Math.max(1,e),r=f=>{const x=f.width-64,b=f.height-64;return{s:Math.min(x/a,b/s)*.98,cw:x,ch:b}},o={width:595,height:842},l={width:842,height:595},u=r(o),m=r(l),[c,d]=m.s>u.s?[l,m]:[o,u],h=a*d.s,g=s*d.s;return{page:c,draw:{x:32+(d.cw-h)/2,y:32+(d.ch-g)/2,width:h,height:g}}}async function AF(i){const e=new Blob([i]).stream().pipeThrough(new CompressionStream("deflate"));return new Uint8Array(await new Response(e).arrayBuffer())}function Fc(i){let e="FEFF";for(let t=0;t`}async function PF(i,e,t,n,a){const{page:s,draw:r}=OF(n.width,n.height),o=await AF(i),l=b=>(Math.round(b*100)/100).toString(),u=`q ${l(r.width)} 0 0 ${l(r.height)} ${l(r.x)} ${l(s.height-r.y-r.height)} cm /Im0 Do Q`,m=new TextEncoder,c=[["<< /Type /Catalog /Pages 2 0 R >>"],["<< /Type /Pages /Kids [3 0 R] /Count 1 >>"],[`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${s.width} ${s.height}] /Resources << /XObject << /Im0 4 0 R >> >> /Contents 5 0 R >>`],[`<< /Type /XObject /Subtype /Image /Width ${e} /Height ${t} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /FlateDecode /Length ${o.length} >> stream `,o,` @@ -60686,9 +60702,9 @@ ${c} `;const n=t.querySelector(".mbot-upload-status"),a=t.querySelector("progress"),s=t.querySelector("[data-action=upload-start]");let r=!1;const o=()=>!r&&t.close();t.querySelector("[data-action=upload-close]").addEventListener("click",o),t.addEventListener("cancel",u=>r&&u.preventDefault()),t.addEventListener("click",u=>u.target===t&&o()),t.addEventListener("close",()=>t.remove());const l=MF(i,e,Z2(),p("web_visubot_upload_label"));"error"in l&&(n.textContent=`⚠︎ ${p(`web_visubot_upload_error_${l.error}`)}`,s.hidden=!0),s.addEventListener("click",async()=>{if("source"in l){r=!0,s.disabled=!0,a.hidden=!1,a.value=0,n.textContent=p("web_visubot_upload_busy");try{await oe.upload(l.source,(u,m)=>a.value=u/m),a.value=1,n.textContent=`✓ ${p("web_visubot_upload_done")}`,n.classList.add("done")}catch(u){const m=u;n.textContent=m.name==="NotFoundError"?"":`⚠︎ ${p("web_visubot_upload_failed")} (${m.message})`,a.hidden=!0,await oe.disconnect(m.name==="NotFoundError"?void 0:m.message).catch(()=>{})}finally{r=!1,s.disabled=!1}}}),document.body.append(t),t.showModal()}const Gc=[z.verzweigung,z.whileSchleife,z.doUntilSchleife,z.anweisung],Hc=()=>[{description:p("web_file_type"),accept:{"application/xml":[".visustruct",".strk"]}}],Gr=i=>p(`element_${z[i]}`),NF={[z.verzweigung]:"age >= 18",[z.whileSchleife]:"i < 10",[z.doUntilSchleife]:"again == 1",[z.fallauswahl]:"day"},FF={statement:'int number = 5 | double x = 1.5 | String text = "Your text" | boolean ok = true | const double PI = 3.14',input:'input: int age "Enter age" | input: double price "Enter price" | input: String name "Enter name"',output:'output: number | output: "Your text" | output: "Your age: " + age'};function Vc(i){switch(i.type){case z.anweisung:{const e=Ra(i.textLines.join(` `));return e==="input"?"input:":e==="output"?"output:":void 0}case z.verzweigung:return"if";case z.whileSchleife:case z.doUntilSchleife:return"while";case z.fallauswahl:return"switch";default:return}}function JF(i){switch(i.type){case z.anweisung:{const e=Ra(i.textLines.join(` -`));return e==="input"?'int age "Enter age"':e==="output"?'"Your age: " + age':p("inspector_placeholder_statement")}case z.verzweigung:case z.whileSchleife:case z.doUntilSchleife:case z.endlosschleife:return p("inspector_placeholder_condition");case z.fallauswahl:return p("inspector_placeholder_selector");case z.aufruf:return p("inspector_placeholder_call");case z.aussprung:return p("inspector_placeholder_break");default:return""}}function ae(i,e={},...t){const n=document.createElement(i);for(const[a,s]of Object.entries(e))n.setAttribute(a,s);return n.append(...t),n}const RF=760,Qc=[{value:1,label:"settings_ui_scale_small"},{value:1.22,label:"settings_ui_scale_medium"},{value:1.5,label:"settings_ui_scale_large"},{value:1.82,label:"settings_ui_scale_extra_large"}],Hr=[{value:14,label:"settings_ui_scale_small"},{value:17,label:"settings_ui_scale_medium"},{value:20,label:"settings_ui_scale_large"},{value:24,label:"settings_ui_scale_extra_large"}];function qc(i){document.documentElement.style.setProperty("--code-size",`${i}px`)}const GF=/Mac|iPhone|iPad/.test(navigator.platform);function Ta(i){const e=Yn(),t=e==="pt-PT"?"pt":e==="de"?"de":"en",n=/\/app\/(index\.html)?$/.test(location.pathname)?"../":"https://visustruct.org/",a=Wn()?"visubot":"index";return`${n}${t}/${a}.html${i?`#${i}`:""}`}function Ct(i,e,t,n){const a=n?`${e} (${n})`:e;return``}function xn(i,e=!1){return GF?`${e?"⇧":""}⌘${i}`:[p("web_key_ctrl"),...e?[p("web_key_shift")]:[],i].join("+")}const L=eJ,Uc="visustruct.ui.scale.canvas",$c="visustruct.ui.scale.code",Yc="visustruct.learn.open",Xc="visustruct.files.open",HF="visustruct.files.width",VF="visustruct.learn.width",Kc="visustruct.live.open",QF="visustruct.live.width",ed="visustruct.robotPreview.open",td="visustruct.codeMain",nd="visustruct.palette.width",qF="visustruct.editor.width",id="visustruct.visubot.collapsedGroups",ad="visustruct.robotPreview.stacked",UF="visustruct.robotPreview.width",sd="visustruct.robotPreview.height",rd="visustruct.editor.hidden",Vr="visustruct.palette.compact",$F='',YF=80;class XF{constructor(e){y(this,"tabs",[]);y(this,"tabIndex",0);y(this,"nextTabSerial",1);y(this,"clipboard");y(this,"zoom",1);y(this,"simulating",!1);y(this,"exportButton");y(this,"closeExport");y(this,"learn");y(this,"shell");y(this,"railButton");y(this,"liveRailButton");y(this,"editorRailButton");y(this,"topbar",ae("div",{class:"topbar"}));y(this,"bottombar",ae("div",{class:"bottombar"}));y(this,"editorHidden",!1);y(this,"files");y(this,"filesRailButton");y(this,"closeSettings");y(this,"escapeSettings");y(this,"exerciseSaveTimer");y(this,"paletteObserver");y(this,"resizeObserver");y(this,"renderedHostSize",{width:-1,height:-1});y(this,"simPath");y(this,"sim");y(this,"simButton");y(this,"coding",!1);y(this,"code");y(this,"codeButton");y(this,"liveCoding",!1);y(this,"codeTyping");y(this,"live");y(this,"preview",new IF);y(this,"previewOpen",!1);y(this,"codeMain",!1);y(this,"previewStacked",!1);y(this,"previewResizer");y(this,"measure",e2());y(this,"metrics",t2());y(this,"engine",new bd(this.metrics,this.measure));y(this,"renderer",new wd(this.metrics,this.measure));y(this,"layout");y(this,"flat",[]);y(this,"canvasHost");y(this,"svg");y(this,"overlay");y(this,"inspector");y(this,"captionInput");y(this,"undoButton");y(this,"redoButton");y(this,"deleteButton");y(this,"statusLine");y(this,"drag");y(this,"downloads",null);y(this,"inViewer","claude"in window);y(this,"visuBot");y(this,"stopLinkListener");y(this,"tabStrip");this.root=e,this.tabs.push(this.makeTab());const t=new URLSearchParams(location.search);t.has("visubot")?cr("on"):t.has("visustruct")&&cr("off"),_u(ai()),this.learn=new dD(this.learnHost()),this.shell=document.createElement("div"),this.shell.className="shell",e.replaceWith(this.shell),this.live=new vF(()=>this.setLiveCoding(!1),l=>{this.selected=l,this.render()},(l,u)=>this.commitFromCode(l,u),l=>l?this.redo():this.undo()),this.live.onRobotRun=l=>this.runRobot(l),this.live.onSwap=()=>this.setCodeMain(!this.codeMain),this.live.onReference=()=>{this.learn.showReference(),this.setLearning(!0)},this.files=new TD({open:(l,u,m)=>this.openFromWorkspace(l,u,m),hide:()=>this.setFilesOpen(!1),message:l=>this.showMessage(l),progressLoaded:()=>this.learn.restore(),chooseWorld:l=>this.chooseWorld(l,!1)});const n=ae("div",{class:"columns"});n.append(this.filesRail(),this.files.element,this.panelResizer(this.files.element,"files-resizer",HF,p("web_files_resize"),1),this.learnRail(),this.learn.element,this.learnResizer(),this.editorRail(),e,this.panelResizer(e,"editor-resizer",qF,p("web_editor_resize"),1),this.liveResizer(),this.live.element,this.liveRail(),this.previewResizer=this.panelResizer(this.preview.element,"preview-resizer",UF,p("web_visubot_preview_resize"),-1),this.preview.element,this.preview.rail),this.setupPreview(),this.shell.append(this.topbar,n,this.bottombar);const a=Xe(Yc),s=new URLSearchParams(location.search).has("learn");this.showWorldInURL(),this.setLearning(s||(a===null?window.innerWidth>1100:a==="1"),s),this.setFilesOpen(Xe(Xc)==="1");const r=Number(Xe(Uc));Qc.some(l=>l.value===r)&&(this.zoom=r),this.setLiveCoding(Xe(Kc)==="1"),this.setEditorHidden(Xe(rd)==="1"),this.buildUI(),this.setCodeMain(Xe(td)==="1"),this.render(),window.addEventListener("pointermove",l=>this.onPointerMove(l)),window.addEventListener("pointerup",l=>this.onPointerUp(l)),window.addEventListener("pointercancel",()=>this.endDrag()),window.addEventListener("keydown",l=>this.onKeyDown(l)),window.addEventListener("beforeunload",l=>{(this.tabs.some(u=>u.dirty&&!u.exerciseId)||!this.files.ready&&ce.hasContent())&&l.preventDefault()}),this.setupFileDrop();const o=window.claude;typeof(o==null?void 0:o.use)=="function"&&o.use("downloads").then(l=>this.downloads=l).catch(()=>{})}get tab(){return this.tabs[this.tabIndex]}get doc(){return this.tab.doc}set doc(e){this.tab.doc=e}get fileName(){return this.tab.fileName??`${an(this.tab)}.visustruct`}get fileHandle(){return this.tab.fileHandle}set fileHandle(e){this.tab.fileHandle=e}get dirty(){return this.tab.dirty}set dirty(e){this.tab.dirty=e}get undoStack(){return this.tab.undoStack}get redoStack(){return this.tab.redoStack}get selected(){return this.tab.selected}set selected(e){this.tab.selected=e}buildUI(){var R,ne,ge,jt;this.root.className="app",this.root.innerHTML=` +`));return e==="input"?'int age "Enter age"':e==="output"?'"Your age: " + age':p("inspector_placeholder_statement")}case z.verzweigung:case z.whileSchleife:case z.doUntilSchleife:case z.endlosschleife:return p("inspector_placeholder_condition");case z.fallauswahl:return p("inspector_placeholder_selector");case z.aufruf:return p("inspector_placeholder_call");case z.aussprung:return p("inspector_placeholder_break");default:return""}}function ae(i,e={},...t){const n=document.createElement(i);for(const[a,s]of Object.entries(e))n.setAttribute(a,s);return n.append(...t),n}const RF=760,Qc=[{value:1,label:"settings_ui_scale_small"},{value:1.22,label:"settings_ui_scale_medium"},{value:1.5,label:"settings_ui_scale_large"},{value:1.82,label:"settings_ui_scale_extra_large"}],Hr=[{value:14,label:"settings_ui_scale_small"},{value:17,label:"settings_ui_scale_medium"},{value:20,label:"settings_ui_scale_large"},{value:24,label:"settings_ui_scale_extra_large"}];function qc(i){document.documentElement.style.setProperty("--code-size",`${i}px`)}const GF=/Mac|iPhone|iPad/.test(navigator.platform);function Ta(i){const e=Xn(),t=e==="pt-PT"?"pt":e==="de"?"de":"en",n=/\/app\/(index\.html)?$/.test(location.pathname)?"../":"https://visustruct.org/",a=En()?"visubot":"index";return`${n}${t}/${a}.html${i?`#${i}`:""}`}function Ct(i,e,t,n){const a=n?`${e} (${n})`:e;return``}function xn(i,e=!1){return GF?`${e?"⇧":""}⌘${i}`:[p("web_key_ctrl"),...e?[p("web_key_shift")]:[],i].join("+")}const L=eJ,Uc="visustruct.ui.scale.canvas",$c="visustruct.ui.scale.code",Yc="visustruct.learn.open",Xc="visustruct.files.open",HF="visustruct.files.width",VF="visustruct.learn.width",Kc="visustruct.live.open",QF="visustruct.live.width",ed="visustruct.robotPreview.open",td="visustruct.codeMain",nd="visustruct.palette.width",qF="visustruct.editor.width",id="visustruct.visubot.collapsedGroups",ad="visustruct.robotPreview.stacked",UF="visustruct.robotPreview.width",sd="visustruct.robotPreview.height",rd="visustruct.editor.hidden",Vr="visustruct.palette.compact",$F='',YF=80;class XF{constructor(e){y(this,"tabs",[]);y(this,"tabIndex",0);y(this,"nextTabSerial",1);y(this,"clipboard");y(this,"zoom",1);y(this,"simulating",!1);y(this,"exportButton");y(this,"closeExport");y(this,"learn");y(this,"shell");y(this,"railButton");y(this,"liveRailButton");y(this,"editorRailButton");y(this,"topbar",ae("div",{class:"topbar"}));y(this,"bottombar",ae("div",{class:"bottombar"}));y(this,"editorHidden",!1);y(this,"files");y(this,"filesRailButton");y(this,"closeSettings");y(this,"escapeSettings");y(this,"exerciseSaveTimer");y(this,"paletteObserver");y(this,"resizeObserver");y(this,"renderedHostSize",{width:-1,height:-1});y(this,"simPath");y(this,"sim");y(this,"simButton");y(this,"coding",!1);y(this,"code");y(this,"codeButton");y(this,"liveCoding",!1);y(this,"codeTyping");y(this,"live");y(this,"preview",new IF);y(this,"previewOpen",!1);y(this,"codeMain",!1);y(this,"previewStacked",!1);y(this,"previewResizer");y(this,"measure",e2());y(this,"metrics",t2());y(this,"engine",new bd(this.metrics,this.measure));y(this,"renderer",new wd(this.metrics,this.measure));y(this,"layout");y(this,"flat",[]);y(this,"canvasHost");y(this,"svg");y(this,"overlay");y(this,"inspector");y(this,"captionInput");y(this,"undoButton");y(this,"redoButton");y(this,"deleteButton");y(this,"statusLine");y(this,"drag");y(this,"downloads",null);y(this,"inViewer","claude"in window);y(this,"visuBot");y(this,"stopLinkListener");y(this,"tabStrip");this.root=e,this.tabs.push(this.makeTab());const t=new URLSearchParams(location.search);t.has("visubot")?cr("on"):t.has("visustruct")&&cr("off"),_u(ai()),this.learn=new dD(this.learnHost()),this.shell=document.createElement("div"),this.shell.className="shell",e.replaceWith(this.shell),this.live=new vF(()=>this.setLiveCoding(!1),l=>{this.selected=l,this.render()},(l,u)=>this.commitFromCode(l,u),l=>l?this.redo():this.undo()),this.live.onRobotRun=l=>this.runRobot(l),this.live.onSwap=()=>this.setCodeMain(!this.codeMain),this.live.onReference=()=>{this.learn.showReference(),this.setLearning(!0)},this.files=new TD({open:(l,u,m)=>this.openFromWorkspace(l,u,m),hide:()=>this.setFilesOpen(!1),message:l=>this.showMessage(l),progressLoaded:()=>this.learn.restore(),chooseWorld:l=>this.chooseWorld(l,!1)});const n=ae("div",{class:"columns"});n.append(this.filesRail(),this.files.element,this.panelResizer(this.files.element,"files-resizer",HF,p("web_files_resize"),1),this.learnRail(),this.learn.element,this.learnResizer(),this.editorRail(),e,this.panelResizer(e,"editor-resizer",qF,p("web_editor_resize"),1),this.liveResizer(),this.live.element,this.liveRail(),this.previewResizer=this.panelResizer(this.preview.element,"preview-resizer",UF,p("web_visubot_preview_resize"),-1),this.preview.element,this.preview.rail),this.setupPreview(),this.shell.append(this.topbar,n,this.bottombar);const a=Xe(Yc),s=new URLSearchParams(location.search).has("learn");this.showWorldInURL(),this.setLearning(s||(a===null?window.innerWidth>1100:a==="1"),s),this.setFilesOpen(Xe(Xc)==="1");const r=Number(Xe(Uc));Qc.some(l=>l.value===r)&&(this.zoom=r),this.setLiveCoding(Xe(Kc)==="1"),this.setEditorHidden(Xe(rd)==="1"),this.buildUI(),this.setCodeMain(Xe(td)==="1"),this.render(),window.addEventListener("pointermove",l=>this.onPointerMove(l)),window.addEventListener("pointerup",l=>this.onPointerUp(l)),window.addEventListener("pointercancel",()=>this.endDrag()),window.addEventListener("keydown",l=>this.onKeyDown(l)),window.addEventListener("beforeunload",l=>{(this.tabs.some(u=>u.dirty&&!u.exerciseId)||!this.files.ready&&ce.hasContent())&&l.preventDefault()}),this.setupFileDrop();const o=window.claude;typeof(o==null?void 0:o.use)=="function"&&o.use("downloads").then(l=>this.downloads=l).catch(()=>{})}get tab(){return this.tabs[this.tabIndex]}get doc(){return this.tab.doc}set doc(e){this.tab.doc=e}get fileName(){return this.tab.fileName??`${an(this.tab)}.visustruct`}get fileHandle(){return this.tab.fileHandle}set fileHandle(e){this.tab.fileHandle=e}get dirty(){return this.tab.dirty}set dirty(e){this.tab.dirty=e}get undoStack(){return this.tab.undoStack}get redoStack(){return this.tab.redoStack}get selected(){return this.tab.selected}set selected(e){this.tab.selected=e}buildUI(){var R,ne,ge,jt;this.root.className="app",this.root.innerHTML=`
- ${Wn()?pD:'VisuStruct'} ${L(p("web_brand_suffix"))} + ${En()?pD:'VisuStruct'} ${L(p("web_brand_suffix"))}
${Ct("new",p("toolbar_new"),ee.newFile)} ${Ct("open",p("menu_open"),ee.open,xn("O"))} @@ -60708,13 +60724,13 @@ ${c}

${L(p("web_settings_display"))}

@@ -60787,7 +60803,7 @@ ${c} - +
@@ -60804,7 +60820,7 @@ ${c} - `,this.topbar.replaceChildren(this.root.querySelector(".toolbar")),this.bottombar.replaceChildren(this.root.querySelector(".statusbar"));const e=D=>this.root.querySelector(D)??this.topbar.querySelector(D)??this.bottombar.querySelector(D);this.canvasHost=e(".canvas"),this.inspector=e(".inspector"),this.captionInput=e(".caption"),this.undoButton=e("[data-action=undo]"),this.redoButton=e("[data-action=redo]"),this.deleteButton=e("[data-action=delete]"),this.statusLine=e(".status"),this.simButton=e("[data-action=simulate]"),e("[data-action=hide-editor]").addEventListener("click",()=>this.setEditorHidden(!0)),e("[data-action=swap-main]").addEventListener("click",()=>this.setCodeMain(!this.codeMain)),this.labelSwap(),this.sim=new EB(()=>this.doc,D=>{this.simPath=D,this.simulating&&this.renderDiagramOnly(),this.scrollToSimPath()},D=>this.findSubprogram(D),()=>this.setSimulating(!1),D=>{this.simulating&&this.liveCoding&&this.live.showTranscript(D)}),this.root.append(this.sim.element),Wn()?(this.visuBot??(this.visuBot=new fD),this.sim.setRobot(this.visuBot)):((R=this.visuBot)==null||R.dispose(),this.visuBot=void 0),this.simButton.addEventListener("click",()=>this.setSimulating(!this.simulating)),this.codeButton=e("[data-action=code]"),this.code=new K3(()=>this.doc,(D,X)=>this.offerDownload(D,new Blob([X],{type:"text/plain"})),()=>this.setCoding(!1),D=>this.commit({...this.doc,pseudocode:D||void 0}),()=>this.tabs.filter(D=>D!==this.tab&&pt(D.doc.caption)).map(D=>D.doc)),this.root.append(this.code.element),this.codeButton.addEventListener("click",()=>this.setCoding(!this.coding)),(ne=this.paletteObserver)==null||ne.disconnect();const t=()=>Number(Xe(nd))||0,n=()=>this.root.classList.toggle("compact-palette",Xe(Vr)==="1"||(t()>0?t()<150:this.root.getBoundingClientRect().width{const ze=D===void 0?void 0:Math.round(Math.max(80,Math.min(360,D)));ze===void 0?this.root.style.removeProperty("--palette-width"):this.root.style.setProperty("--palette-width",`${ze}px`),X&&at(nd,ze===void 0?"":String(ze)),n()};t()>0&&a(t(),!1);const s=e(".palette-resizer"),r=e(".palette"),o=()=>getComputedStyle(this.shell).direction==="rtl"?-1:1;s.addEventListener("pointerdown",D=>{if(D.button!==0)return;D.preventDefault(),s.setPointerCapture(D.pointerId);const X=D.clientX,ze=r.getBoundingClientRect().width,De=o();this.shell.classList.add("resizing");const Ie=le=>a(ze+De*(le.clientX-X),!1),U=le=>{s.removeEventListener("pointermove",Ie),s.removeEventListener("pointerup",U),s.removeEventListener("pointercancel",U),this.shell.classList.remove("resizing"),a(ze+De*(le.clientX-X),!0)};s.addEventListener("pointermove",Ie),s.addEventListener("pointerup",U),s.addEventListener("pointercancel",U)}),s.addEventListener("dblclick",()=>a(void 0,!0)),s.addEventListener("keydown",D=>{const X=D.key==="ArrowRight"?20:D.key==="ArrowLeft"?-20:0;X&&(D.preventDefault(),a(r.getBoundingClientRect().width+o()*X,!0))}),this.paletteObserver=new ResizeObserver(n),this.paletteObserver.observe(this.root);const l=e("[data-action=compact-palette]");l.checked=Xe(Vr)==="1",l.addEventListener("change",()=>{at(Vr,l.checked?"1":"0"),n()});const u=(D,X,ze,De,Ie)=>{const U=document.createElement("li");U.className="palette-item",U.dataset.item=Ie,U.append(this.paletteIcon(X),document.createTextNode(ze)),U.addEventListener("pointerdown",le=>this.beginDrag(le,{kind:"palette",make:De,label:ze})),U.tabIndex=0,U.addEventListener("keydown",le=>{(le.key==="Enter"||le.key===" ")&&this.insertNearSelection(De())}),D.append(U)},m=e(".palette-basic");for(const{item:D}of i2)u(m,D,Gr(E0(D).type),()=>E0(D),D);const c=Wn();this.root.classList.toggle("visubot-mode",c),this.shell.classList.toggle("robot-world",c),c||this.preview.pause(),document.documentElement.classList.toggle("visubot-theme",c);const d=e(".palette-visubot");if(d.hidden=!c,e(".palette-visubot-title").hidden=!c,c){const D={[z.verzweigung]:"verzweigung",[z.whileSchleife]:"whileSchleife"},X=new Set((Xe(id)??"").split(",").filter(Boolean)),ze=(U,le)=>{const be=document.createElement("li");be.className="palette-group";const Ze=document.createElement("button");Ze.type="button",Ze.textContent=p(`web_visubot_group_${le}`);const Ye=Rt=>{Ze.setAttribute("aria-expanded",String(Rt));for(const Ks of U.querySelectorAll(`[data-group="${le}"]`))Ks.hidden=!Rt};return Ze.addEventListener("click",()=>{const Rt=Ze.getAttribute("aria-expanded")!=="true";Rt?X.delete(le):X.add(le),at(id,[...X].join(",")),Ye(Rt)}),be.append(Ze),U.append(be),()=>Ye(!X.has(le))},De=(U,le,be)=>{for(const Ze of new Set(le.map(Ye=>Ye.group))){const Ye=ze(U,Ze);for(const Rt of le.filter(Ks=>Ks.group===Ze))be(Rt).dataset.group=Ze;Ye()}};De(d,yD,U=>(u(d,D[U.type]??"anweisung",p(U.key),U.make,U.key),d.lastElementChild));const Ie=e(".palette-visubot-sensors");Ie.replaceChildren(),De(Ie,Wh,U=>{const le=p(U.key),be=document.createElement("li");be.className="palette-item palette-sensor",be.dataset.item=U.key,be.title=U.text;const Ze=document.createElement("code");return Ze.textContent=U.text,be.append(document.createTextNode(le),Ze),be.addEventListener("pointerdown",Ye=>this.beginDrag(Ye,{kind:"sensor",text:U.text,label:U.text})),be.tabIndex=0,be.addEventListener("keydown",Ye=>{(Ye.key==="Enter"||Ye.key===" ")&&this.insertSensor(U.text)}),Ie.append(be),be})}e(".palette-visubot-sensors").hidden=!c,e(".palette-visubot-sensors-title").hidden=!c,this.tabStrip=e(".tabs"),this.exportButton=e("[data-action=export]");const h=e(".export-menu");this.exportButton.setAttribute("aria-haspopup","menu"),this.exportButton.addEventListener("click",()=>{var D;h.hidden=!h.hidden,h.hidden||(D=h.querySelector("button"))==null||D.focus()}),h.addEventListener("click",D=>{var ze;const X=(ze=D.target.closest("[data-export]"))==null?void 0:ze.dataset.export;X&&(h.hidden=!0,this.exportDiagram(X))}),h.addEventListener("keydown",D=>{D.key==="Escape"&&(h.hidden=!0,this.exportButton.focus())}),this.closeExport&&document.removeEventListener("pointerdown",this.closeExport),this.closeExport=D=>{!h.hidden&&!h.parentElement.contains(D.target)&&(h.hidden=!0)},document.addEventListener("pointerdown",this.closeExport);const g=e("[data-action=language]");g.value=Yn(),g.addEventListener("change",()=>void this.changeLanguage(()=>Ad(g.value),"language"));const f=[e("[data-action=mbot-link]"),e("[data-action=mbot-link-settings]")],x=e(".settings-mbot-link small"),b=()=>{const D=oe.connected,X=oe.connecting?p("web_visubot_connecting"):p(D?"web_visubot_disconnect":"web_visubot_connect");f[0].hidden=!Wn()||!sr(),v.hidden=f[0].hidden,f[0].classList.toggle("connected",D);const ze=oe.connecting?"⏳":D?"🟢":"🔌";f[0].textContent=`${ze} mBot2`,f[0].title=X,f[1].textContent=`${ze} ${X}`,f[1].disabled=!sr(),f[1].parentElement.hidden=!Wn(),x.textContent=sr()?Lh():p("web_visubot_no_serial")};for(const D of f)D.addEventListener("click",()=>void vD());const v=e("[data-action=mbot-upload]");v.addEventListener("click",()=>EF(this.doc,this.tabs.filter(D=>D!==this.tab).map(D=>D.doc))),(ge=this.stopLinkListener)==null||ge.call(this),this.stopLinkListener=oe.listen(b),b();for(const D of this.topbar.querySelectorAll("[data-action=visubot] [data-world]"))D.addEventListener("click",()=>void this.chooseWorld(D.dataset.world,!0));const w=e("[data-action=keywords]");w.checked=p2(),w.addEventListener("change",()=>void this.changeLanguage(()=>Od(w.checked),"keywords"));const k=e("[data-action=live-language]");k.value=this.live.language;const I=e("[data-action=java-class]"),T=e("[data-action=java-main]"),S=e("[data-action=java-swing]");S.checked=this.live.swingSupport,S.addEventListener("change",()=>this.live.setSwingSupport(S.checked));const _=()=>{I.checked=this.live.javaForm.asClass,T.checked=this.live.javaForm.withMain,e(".settings-menu .java-only").hidden=this.live.language!=="java"};_(),k.addEventListener("change",()=>{this.live.setTarget(k.value),_()});for(const D of[I,T])D.addEventListener("change",()=>this.live.setJavaForm({asClass:I.checked,withMain:T.checked}));const C=e("[data-action=zoom]");C.value=String(this.zoom),C.addEventListener("change",()=>{this.zoom=Number(C.value),at(Uc,C.value),this.renderDiagramOnly()});const B=e("[data-action=code-size]"),P=Number(Xe($c));B.value=String(Hr.some(D=>D.value===P)?P:Hr[0].value),qc(Number(B.value)),B.addEventListener("change",()=>{at($c,B.value),qc(Number(B.value))}),this.setupSettingsMenu(e("[data-action=settings]"),e(".settings-menu")),e("[data-action=about]").addEventListener("click",()=>{e(".settings-menu").hidden=!0,this.showAbout()}),e("[data-action=cut]").addEventListener("click",()=>this.cutSelection()),e("[data-action=copy]").addEventListener("click",()=>this.copySelection()),e("[data-action=paste]").addEventListener("click",()=>this.paste());const A=e("input[type=file]");A.addEventListener("change",async()=>{var X;const D=(X=A.files)==null?void 0:X[0];A.value="",D&&this.loadXML(await D.text(),D.name)}),e("[data-action=new]").addEventListener("click",()=>this.addTab()),e("[data-action=open]").addEventListener("click",()=>this.open(A)),e("[data-action=save]").addEventListener("click",()=>this.save()),this.undoButton.addEventListener("click",()=>this.undo()),this.redoButton.addEventListener("click",()=>this.redo()),this.deleteButton.addEventListener("click",()=>this.deleteSelection());let W;this.captionInput.addEventListener("focus",()=>W=this.doc),this.captionInput.addEventListener("input",()=>{this.doc={...this.doc,caption:this.captionInput.value},this.dirty=!0,this.updateStatus(),this.refreshLive()}),this.captionInput.addEventListener("change",()=>{W&&W.caption!==this.doc.caption&&this.pushUndo(W),W=this.doc}),this.canvasHost.addEventListener("pointerdown",D=>this.onCanvasPointerDown(D)),(jt=this.resizeObserver)==null||jt.disconnect(),this.resizeObserver=new ResizeObserver(()=>{const{clientWidth:D,clientHeight:X}=this.canvasHost;D===this.renderedHostSize.width&&X===this.renderedHostSize.height||this.renderDiagramOnly()}),this.resizeObserver.observe(this.canvasHost)}showWorldInURL(){const e=new URLSearchParams(location.search);for(const a of["learn","visubot","visustruct","visuobject"])e.delete(a);const t=e.toString(),n=ai()==="on"?"visubot":"visustruct";history.replaceState(history.state,"",`${location.pathname}?${n}${t?`&${t}`:""}${location.hash}`)}async chooseWorld(e,t){if(e==="object"){Zh(),location.href=`${location.pathname}?visuobject${location.hash}`;return}e===ai()&&gD()||await this.changeLanguage(async()=>{cr(e),_u(e),this.showWorldInURL()},t?`visubot] [data-world=${e}`:void 0)}async changeLanguage(e,t){var n,a;this.setSimulating(!1),this.setCoding(!1),await e(),_f(),this.sim.end(),this.live.build(),this.preview.relabel(),this.placePreview(),this.files.build(),this.buildUI(),this.render(),this.learn.render(),this.labelLearnRail(),this.labelLiveRail(),this.labelEditorRail(),this.labelFilesRail(),t!==void 0&&((n=this.topbar.querySelector("[data-action=settings]"))==null||n.click(),(a=this.topbar.querySelector(`[data-action=${t}]`))==null||a.focus())}setFilesOpen(e){this.shell.classList.toggle("files-open",e),at(Xc,e?"1":"0"),this.keepAColumnOpen(),this.canvasHost&&this.renderDiagramOnly()}filesRail(){return this.filesRailButton=ae("button",{class:"learn-rail files-rail"}),this.labelFilesRail(),this.filesRailButton.addEventListener("click",()=>this.setFilesOpen(!0)),this.filesRailButton}labelFilesRail(){this.filesRailButton&&(this.filesRailButton.title=p("web_files_show"),this.filesRailButton.innerHTML=`${$t}📁 ${L(p("web_files_title"))}`)}openFromWorkspace(e,t,n){const a=this.tabs.find(s=>{var r;return((r=s.workspace)==null?void 0:r.dir)===t.dir&&s.workspace.base===t.base});if(a){this.tabIndex=this.tabs.indexOf(a),this.render();return}e?this.loadXML(e,`${t.base}.visustruct`):n!==void 0&&((this.dirty||this.tab.fileName||this.tab.exerciseId)&&this.addTab(),this.doc=this.live.documentFromJavaText(n),this.tab.fileName=`${t.base}.visustruct`,this.resetHistory()),this.tab.workspace=t,this.tab.fileHandle=void 0,n!==void 0&&(this.live.adoptJava(this.doc,n),this.setLiveCoding(!0)),this.render()}async saveToWorkspace(){if(!this.files.ready||this.tab.fileHandle&&!this.tab.workspace)return!1;const e=this.doc.caption.trim()||an(this.tab),t=this.live.language==="java"?this.live.javaFor(this.doc,this.tab):void 0;try{const n=await this.files.save(e,n1(this.doc),t,this.tab.workspace);if(!n)return this.setFilesOpen(!0),!0;this.tab.workspace=n,this.tab.fileName=`${n.base}.visustruct`,this.dirty=!1,this.render(),this.showMessage(p("web_files_saved_fmt",n.path))}catch(n){this.showMessage(n.message)}return!0}setLearning(e,t=!0){this.shell.classList.toggle("learning",e),t&&at(Yc,e?"1":"0"),this.keepAColumnOpen(),this.canvasHost&&this.renderDiagramOnly()}setEditorHidden(e){this.editorHidden=e,this.shell.classList.toggle("editor-hidden",e),at(rd,e?"1":"0"),e&&!this.liveCoding&&!this.shell.classList.contains("learning")&&this.setLiveCoding(!0),!e&&this.canvasHost&&this.render()}keepAColumnOpen(){this.editorHidden&&!this.liveCoding&&!this.shell.classList.contains("learning")&&!this.shell.classList.contains("files-open")&&this.setEditorHidden(!1)}editorRail(){return this.editorRailButton=ae("button",{class:"learn-rail editor-rail"}),this.labelEditorRail(),this.editorRailButton.addEventListener("click",()=>this.setEditorHidden(!1)),this.editorRailButton}labelEditorRail(){this.editorRailButton&&(this.editorRailButton.title=p("web_editor_show"),this.editorRailButton.innerHTML=`${$t}✎ ${L(p("web_editor_title"))}`)}showAbout(){const e=(n,a,s)=>``,t=ae("dialog",{class:"about","aria-labelledby":"about-title"});t.innerHTML=` + `,this.topbar.replaceChildren(this.root.querySelector(".toolbar")),this.bottombar.replaceChildren(this.root.querySelector(".statusbar"));const e=Z=>this.root.querySelector(Z)??this.topbar.querySelector(Z)??this.bottombar.querySelector(Z);this.canvasHost=e(".canvas"),this.inspector=e(".inspector"),this.captionInput=e(".caption"),this.undoButton=e("[data-action=undo]"),this.redoButton=e("[data-action=redo]"),this.deleteButton=e("[data-action=delete]"),this.statusLine=e(".status"),this.simButton=e("[data-action=simulate]"),e("[data-action=hide-editor]").addEventListener("click",()=>this.setEditorHidden(!0)),e("[data-action=swap-main]").addEventListener("click",()=>this.setCodeMain(!this.codeMain)),this.labelSwap(),this.sim=new EB(()=>this.doc,Z=>{this.simPath=Z,this.simulating&&this.renderDiagramOnly(),this.scrollToSimPath()},Z=>this.findSubprogram(Z),()=>this.setSimulating(!1),Z=>{this.simulating&&this.liveCoding&&this.live.showTranscript(Z)}),this.root.append(this.sim.element),En()?(this.visuBot??(this.visuBot=new fD),this.sim.setRobot(this.visuBot)):((R=this.visuBot)==null||R.dispose(),this.visuBot=void 0),this.simButton.addEventListener("click",()=>this.setSimulating(!this.simulating)),this.codeButton=e("[data-action=code]"),this.code=new K3(()=>this.doc,(Z,X)=>this.offerDownload(Z,new Blob([X],{type:"text/plain"})),()=>this.setCoding(!1),Z=>this.commit({...this.doc,pseudocode:Z||void 0}),()=>this.tabs.filter(Z=>Z!==this.tab&&pt(Z.doc.caption)).map(Z=>Z.doc)),this.root.append(this.code.element),this.codeButton.addEventListener("click",()=>this.setCoding(!this.coding)),(ne=this.paletteObserver)==null||ne.disconnect();const t=()=>Number(Xe(nd))||0,n=()=>this.root.classList.toggle("compact-palette",Xe(Vr)==="1"||(t()>0?t()<150:this.root.getBoundingClientRect().width{const ze=Z===void 0?void 0:Math.round(Math.max(80,Math.min(360,Z)));ze===void 0?this.root.style.removeProperty("--palette-width"):this.root.style.setProperty("--palette-width",`${ze}px`),X&&at(nd,ze===void 0?"":String(ze)),n()};t()>0&&a(t(),!1);const s=e(".palette-resizer"),r=e(".palette"),o=()=>getComputedStyle(this.shell).direction==="rtl"?-1:1;s.addEventListener("pointerdown",Z=>{if(Z.button!==0)return;Z.preventDefault(),s.setPointerCapture(Z.pointerId);const X=Z.clientX,ze=r.getBoundingClientRect().width,De=o();this.shell.classList.add("resizing");const Ie=le=>a(ze+De*(le.clientX-X),!1),U=le=>{s.removeEventListener("pointermove",Ie),s.removeEventListener("pointerup",U),s.removeEventListener("pointercancel",U),this.shell.classList.remove("resizing"),a(ze+De*(le.clientX-X),!0)};s.addEventListener("pointermove",Ie),s.addEventListener("pointerup",U),s.addEventListener("pointercancel",U)}),s.addEventListener("dblclick",()=>a(void 0,!0)),s.addEventListener("keydown",Z=>{const X=Z.key==="ArrowRight"?20:Z.key==="ArrowLeft"?-20:0;X&&(Z.preventDefault(),a(r.getBoundingClientRect().width+o()*X,!0))}),this.paletteObserver=new ResizeObserver(n),this.paletteObserver.observe(this.root);const l=e("[data-action=compact-palette]");l.checked=Xe(Vr)==="1",l.addEventListener("change",()=>{at(Vr,l.checked?"1":"0"),n()});const u=(Z,X,ze,De,Ie)=>{const U=document.createElement("li");U.className="palette-item",U.dataset.item=Ie,U.append(this.paletteIcon(X),document.createTextNode(ze)),U.addEventListener("pointerdown",le=>this.beginDrag(le,{kind:"palette",make:De,label:ze})),U.tabIndex=0,U.addEventListener("keydown",le=>{(le.key==="Enter"||le.key===" ")&&this.insertNearSelection(De())}),Z.append(U)},m=e(".palette-basic");for(const{item:Z}of i2)u(m,Z,Gr(E0(Z).type),()=>E0(Z),Z);const c=En();this.root.classList.toggle("visubot-mode",c),this.shell.classList.toggle("robot-world",c),c||this.preview.pause(),document.documentElement.classList.toggle("visubot-theme",c);const d=e(".palette-visubot");if(d.hidden=!c,e(".palette-visubot-title").hidden=!c,c){const Z={[z.verzweigung]:"verzweigung",[z.whileSchleife]:"whileSchleife"},X=new Set((Xe(id)??"").split(",").filter(Boolean)),ze=(U,le)=>{const be=document.createElement("li");be.className="palette-group";const Ze=document.createElement("button");Ze.type="button",Ze.textContent=p(`web_visubot_group_${le}`);const Ye=Gt=>{Ze.setAttribute("aria-expanded",String(Gt));for(const Ks of U.querySelectorAll(`[data-group="${le}"]`))Ks.hidden=!Gt};return Ze.addEventListener("click",()=>{const Gt=Ze.getAttribute("aria-expanded")!=="true";Gt?X.delete(le):X.add(le),at(id,[...X].join(",")),Ye(Gt)}),be.append(Ze),U.append(be),()=>Ye(!X.has(le))},De=(U,le,be)=>{for(const Ze of new Set(le.map(Ye=>Ye.group))){const Ye=ze(U,Ze);for(const Gt of le.filter(Ks=>Ks.group===Ze))be(Gt).dataset.group=Ze;Ye()}};De(d,yD,U=>(u(d,Z[U.type]??"anweisung",p(U.key),U.make,U.key),d.lastElementChild));const Ie=e(".palette-visubot-sensors");Ie.replaceChildren(),De(Ie,Wh,U=>{const le=p(U.key),be=document.createElement("li");be.className="palette-item palette-sensor",be.dataset.item=U.key,be.title=U.text;const Ze=document.createElement("code");return Ze.textContent=U.text,be.append(document.createTextNode(le),Ze),be.addEventListener("pointerdown",Ye=>this.beginDrag(Ye,{kind:"sensor",text:U.text,label:U.text})),be.tabIndex=0,be.addEventListener("keydown",Ye=>{(Ye.key==="Enter"||Ye.key===" ")&&this.insertSensor(U.text)}),Ie.append(be),be})}e(".palette-visubot-sensors").hidden=!c,e(".palette-visubot-sensors-title").hidden=!c,this.tabStrip=e(".tabs"),this.exportButton=e("[data-action=export]");const h=e(".export-menu");this.exportButton.setAttribute("aria-haspopup","menu"),this.exportButton.addEventListener("click",()=>{var Z;h.hidden=!h.hidden,h.hidden||(Z=h.querySelector("button"))==null||Z.focus()}),h.addEventListener("click",Z=>{var ze;const X=(ze=Z.target.closest("[data-export]"))==null?void 0:ze.dataset.export;X&&(h.hidden=!0,this.exportDiagram(X))}),h.addEventListener("keydown",Z=>{Z.key==="Escape"&&(h.hidden=!0,this.exportButton.focus())}),this.closeExport&&document.removeEventListener("pointerdown",this.closeExport),this.closeExport=Z=>{!h.hidden&&!h.parentElement.contains(Z.target)&&(h.hidden=!0)},document.addEventListener("pointerdown",this.closeExport);const g=e("[data-action=language]");g.value=Xn(),g.addEventListener("change",()=>void this.changeLanguage(()=>Ad(g.value),"language"));const f=[e("[data-action=mbot-link]"),e("[data-action=mbot-link-settings]")],x=e(".settings-mbot-link small"),b=()=>{const Z=oe.connected,X=oe.connecting?p("web_visubot_connecting"):p(Z?"web_visubot_disconnect":"web_visubot_connect");f[0].hidden=!En()||!sr(),v.hidden=f[0].hidden,f[0].classList.toggle("connected",Z);const ze=oe.connecting?"⏳":Z?"🟢":"🔌";f[0].textContent=`${ze} mBot2`,f[0].title=X,f[1].textContent=`${ze} ${X}`,f[1].disabled=!sr(),f[1].parentElement.hidden=!En(),x.textContent=sr()?Lh():p("web_visubot_no_serial")};for(const Z of f)Z.addEventListener("click",()=>void vD());const v=e("[data-action=mbot-upload]");v.addEventListener("click",()=>EF(this.doc,this.tabs.filter(Z=>Z!==this.tab).map(Z=>Z.doc))),(ge=this.stopLinkListener)==null||ge.call(this),this.stopLinkListener=oe.listen(b),b();for(const Z of this.topbar.querySelectorAll("[data-action=visubot] [data-world]"))Z.addEventListener("click",()=>void this.chooseWorld(Z.dataset.world,!0));const w=e("[data-action=keywords]");w.checked=p2(),w.addEventListener("change",()=>void this.changeLanguage(()=>Od(w.checked),"keywords"));const k=e("[data-action=live-language]");k.value=this.live.language;const I=e("[data-action=java-class]"),T=e("[data-action=java-main]"),S=e("[data-action=java-swing]");S.checked=this.live.swingSupport,S.addEventListener("change",()=>this.live.setSwingSupport(S.checked));const _=()=>{I.checked=this.live.javaForm.asClass,T.checked=this.live.javaForm.withMain,e(".settings-menu .java-only").hidden=this.live.language!=="java"};_(),k.addEventListener("change",()=>{this.live.setTarget(k.value),_()});for(const Z of[I,T])Z.addEventListener("change",()=>this.live.setJavaForm({asClass:I.checked,withMain:T.checked}));const C=e("[data-action=zoom]");C.value=String(this.zoom),C.addEventListener("change",()=>{this.zoom=Number(C.value),at(Uc,C.value),this.renderDiagramOnly()});const B=e("[data-action=code-size]"),P=Number(Xe($c));B.value=String(Hr.some(Z=>Z.value===P)?P:Hr[0].value),qc(Number(B.value)),B.addEventListener("change",()=>{at($c,B.value),qc(Number(B.value))}),this.setupSettingsMenu(e("[data-action=settings]"),e(".settings-menu")),e("[data-action=about]").addEventListener("click",()=>{e(".settings-menu").hidden=!0,this.showAbout()}),e("[data-action=cut]").addEventListener("click",()=>this.cutSelection()),e("[data-action=copy]").addEventListener("click",()=>this.copySelection()),e("[data-action=paste]").addEventListener("click",()=>this.paste());const A=e("input[type=file]");A.addEventListener("change",async()=>{var X;const Z=(X=A.files)==null?void 0:X[0];A.value="",Z&&this.loadXML(await Z.text(),Z.name)}),e("[data-action=new]").addEventListener("click",()=>this.addTab()),e("[data-action=open]").addEventListener("click",()=>this.open(A)),e("[data-action=save]").addEventListener("click",()=>this.save()),this.undoButton.addEventListener("click",()=>this.undo()),this.redoButton.addEventListener("click",()=>this.redo()),this.deleteButton.addEventListener("click",()=>this.deleteSelection());let W;this.captionInput.addEventListener("focus",()=>W=this.doc),this.captionInput.addEventListener("input",()=>{this.doc={...this.doc,caption:this.captionInput.value},this.dirty=!0,this.updateStatus(),this.refreshLive()}),this.captionInput.addEventListener("change",()=>{W&&W.caption!==this.doc.caption&&this.pushUndo(W),W=this.doc}),this.canvasHost.addEventListener("pointerdown",Z=>this.onCanvasPointerDown(Z)),(jt=this.resizeObserver)==null||jt.disconnect(),this.resizeObserver=new ResizeObserver(()=>{const{clientWidth:Z,clientHeight:X}=this.canvasHost;Z===this.renderedHostSize.width&&X===this.renderedHostSize.height||this.renderDiagramOnly()}),this.resizeObserver.observe(this.canvasHost)}showWorldInURL(){const e=new URLSearchParams(location.search);for(const a of["learn","visubot","visustruct","visuobject"])e.delete(a);const t=e.toString(),n=ai()==="on"?"visubot":"visustruct";history.replaceState(history.state,"",`${location.pathname}?${n}${t?`&${t}`:""}${location.hash}`)}async chooseWorld(e,t){if(e==="object"){Zh(),location.href=`${location.pathname}?visuobject${location.hash}`;return}e===ai()&&gD()||await this.changeLanguage(async()=>{cr(e),_u(e),this.showWorldInURL()},t?`visubot] [data-world=${e}`:void 0)}async changeLanguage(e,t){var n,a;this.setSimulating(!1),this.setCoding(!1),await e(),_f(),this.sim.end(),this.live.build(),this.preview.relabel(),this.placePreview(),this.files.build(),this.buildUI(),this.render(),this.learn.render(),this.labelLearnRail(),this.labelLiveRail(),this.labelEditorRail(),this.labelFilesRail(),t!==void 0&&((n=this.topbar.querySelector("[data-action=settings]"))==null||n.click(),(a=this.topbar.querySelector(`[data-action=${t}]`))==null||a.focus())}setFilesOpen(e){this.shell.classList.toggle("files-open",e),at(Xc,e?"1":"0"),this.keepAColumnOpen(),this.canvasHost&&this.renderDiagramOnly()}filesRail(){return this.filesRailButton=ae("button",{class:"learn-rail files-rail"}),this.labelFilesRail(),this.filesRailButton.addEventListener("click",()=>this.setFilesOpen(!0)),this.filesRailButton}labelFilesRail(){this.filesRailButton&&(this.filesRailButton.title=p("web_files_show"),this.filesRailButton.innerHTML=`${Yt}📁 ${L(p("web_files_title"))}`)}openFromWorkspace(e,t,n){const a=this.tabs.find(s=>{var r;return((r=s.workspace)==null?void 0:r.dir)===t.dir&&s.workspace.base===t.base});if(a){this.tabIndex=this.tabs.indexOf(a),this.render();return}e?this.loadXML(e,`${t.base}.visustruct`):n!==void 0&&((this.dirty||this.tab.fileName||this.tab.exerciseId)&&this.addTab(),this.doc=this.live.documentFromJavaText(n),this.tab.fileName=`${t.base}.visustruct`,this.resetHistory()),this.tab.workspace=t,this.tab.fileHandle=void 0,n!==void 0&&(this.live.adoptJava(this.doc,n),this.setLiveCoding(!0)),this.render()}async saveToWorkspace(){if(!this.files.ready||this.tab.fileHandle&&!this.tab.workspace)return!1;const e=this.doc.caption.trim()||an(this.tab),t=this.live.language==="java"?this.live.javaFor(this.doc,this.tab):void 0;try{const n=await this.files.save(e,n1(this.doc),t,this.tab.workspace);if(!n)return this.setFilesOpen(!0),!0;this.tab.workspace=n,this.tab.fileName=`${n.base}.visustruct`,this.dirty=!1,this.render(),this.showMessage(p("web_files_saved_fmt",n.path))}catch(n){this.showMessage(n.message)}return!0}setLearning(e,t=!0){this.shell.classList.toggle("learning",e),t&&at(Yc,e?"1":"0"),this.keepAColumnOpen(),this.canvasHost&&this.renderDiagramOnly()}setEditorHidden(e){this.editorHidden=e,this.shell.classList.toggle("editor-hidden",e),at(rd,e?"1":"0"),e&&!this.liveCoding&&!this.shell.classList.contains("learning")&&this.setLiveCoding(!0),!e&&this.canvasHost&&this.render()}keepAColumnOpen(){this.editorHidden&&!this.liveCoding&&!this.shell.classList.contains("learning")&&!this.shell.classList.contains("files-open")&&this.setEditorHidden(!1)}editorRail(){return this.editorRailButton=ae("button",{class:"learn-rail editor-rail"}),this.labelEditorRail(),this.editorRailButton.addEventListener("click",()=>this.setEditorHidden(!1)),this.editorRailButton}labelEditorRail(){this.editorRailButton&&(this.editorRailButton.title=p("web_editor_show"),this.editorRailButton.innerHTML=`${Yt}✎ ${L(p("web_editor_title"))}`)}showAbout(){const e=(n,a,s)=>``,t=ae("dialog",{class:"about","aria-labelledby":"about-title"});t.innerHTML=`

${L(p("about_nav_title"))}

@@ -60814,7 +60830,7 @@ ${c}

VisuStruct ${L(p("web_brand_suffix"))}

-

${L(p("web_about_version_fmt").replace("%@","0.12.2"))}

+

${L(p("web_about_version_fmt").replace("%@","0.12.3"))}

Holger Sebastiao

${e("about_web_label","https://www.visustruct.org","www.visustruct.org")} ${e("about_developer_label","https://www.sebastiao.org","www.sebastiao.org")} @@ -60827,13 +60843,13 @@ ${c}

${L(p("web_about_software"))}

${L(p("web_about_software_text"))} ${L(p("web_about_licenses"))}

${L(p("about_copyright"))}

-
`,t.querySelector("[data-action=about-done]").addEventListener("click",()=>t.close()),t.addEventListener("click",n=>n.target===t&&t.close()),t.addEventListener("close",()=>t.remove()),document.body.append(t),t.showModal()}setupSettingsMenu(e,t){const n=a=>{t.hidden=!a,e.setAttribute("aria-expanded",String(a))};e.addEventListener("click",()=>n(t.hidden)),this.closeSettings&&document.removeEventListener("pointerdown",this.closeSettings),this.escapeSettings&&document.removeEventListener("keydown",this.escapeSettings),this.closeSettings=a=>{!t.hidden&&!e.parentElement.contains(a.target)&&n(!1)},document.addEventListener("pointerdown",this.closeSettings),this.escapeSettings=a=>{a.key!=="Escape"||t.hidden||(n(!1),e.focus())},document.addEventListener("keydown",this.escapeSettings)}learnRail(){return this.railButton=ae("button",{class:"learn-rail"}),this.labelLearnRail(),this.railButton.addEventListener("click",()=>this.setLearning(!0)),this.railButton}liveRail(){return this.liveRailButton=ae("button",{class:"learn-rail live-rail"}),this.labelLiveRail(),this.liveRailButton.addEventListener("click",()=>this.setLiveCoding(!0)),this.liveRailButton}labelLiveRail(){this.liveRailButton&&(this.liveRailButton.title=p("web_live_show"),this.liveRailButton.innerHTML=`${$t}</> ${L(p("web_live_title"))}`)}labelLearnRail(){this.railButton&&(this.railButton.title=p("web_learn_show"),this.railButton.innerHTML=`${$t}🎓 ${L(p("web_learn_title"))}`)}learnHost(){return{collapse:()=>this.setLearning(!1),showEditor:()=>{this.editorHidden&&this.setEditorHidden(!1)},showLiveCode:()=>{this.liveCoding||this.setLiveCoding(!0)},showJava:()=>this.openJavaColumn(),showFiles:()=>{this.shell.classList.contains("files-open")||this.setFilesOpen(!0)},openExercise:(e,t)=>{e.code==="java"?this.openJavaColumn():this.setEditorHidden(!1);const n=this.tabs.findIndex(s=>s.exerciseId===e.id);if(n>=0){this.switchTab(n),this.setSimulating(!1);return}const a=this.makeTab();a.doc=t,a.exerciseId=e.id,a.selected=t.elements.length>0?[0]:void 0,this.isPristine(this.tab)?this.tabs[this.tabIndex]=a:this.tabs.push(a),this.tabIndex=this.tabs.indexOf(a),this.setSimulating(!1),this.render()},openDiagram:(e,t)=>{this.setEditorHidden(!1),this.loadXML(n1(e),e.caption.trim()?`${e.caption.trim()}.visustruct`:t)},exerciseDocument:e=>{const t=this.tabs.find(a=>a.exerciseId===e);if(t)return t.doc;const n=this.tab;if(!(n.exerciseId||this.isPristine(n)))return n.exerciseId=e,ce.updateExercise(e,{xml:n1(n.doc)}),n.doc},subprogramsFor:e=>{const t=this.tabs.find(n=>n.exerciseId===e);return n=>this.findSubprogram(n,t)},stopSimulation:()=>this.setSimulating(!1),resetExercise:(e,t)=>{const n=this.tabs.find(a=>a.exerciseId===e);n&&(n.undoStack.push(n.doc),n.doc=t,n.redoStack=[],n.selected=[0],n===this.tab&&this.render())},preview:e=>{const t=Ec(e,this.metrics,this.measure,0);if(!t)return;const n=t.svg.getAttribute("width");return n&&(t.svg.style.maxWidth=`${n}px`),t.svg.removeAttribute("width"),t.svg.removeAttribute("height"),t.svg}}}isPristine(e){return!e.dirty&&!e.fileName&&!e.exerciseId&&e.undoStack.length===0}rememberExercise(){const e=this.tab;e.exerciseId&&(clearTimeout(this.exerciseSaveTimer),this.exerciseSaveTimer=window.setTimeout(()=>{e.exerciseId&&ce.updateExercise(e.exerciseId,{xml:n1(e.doc)})},300))}paletteIcon(e){const t=fe("svg",{viewBox:"0 0 28 20",width:28,height:20,class:"icon"}),n={fill:"none",stroke:"currentColor","stroke-width":1.5};t.append(fe("rect",{x:1,y:1,width:26,height:18,...n}));const a=s=>t.append(fe("path",{d:s,...n}));switch(e){case"verzweigung":a("M1 1 L14 10 L27 1 M14 10 V19");break;case"fallauswahl":a("M1 1 L20 10 L27 1 M1 10 H27 M10 10 V19 M20 10 V19");break;case"forZaehlSchleife":case"whileSchleife":a("M7 7 H27 M7 7 V19");break;case"doUntilSchleife":a("M7 1 V13 H27");break;case"endlosschleife":a("M7 6 H27 M7 6 V14 H27");break;case"aufruf":a("M5 1 V19 M23 1 V19");break;case"aussprung":a("M6 1 L1 10 L6 19");break}return t}render(){const e={...this.doc,elements:this.doc.elements.map(Ha)};this.layout=this.engine.layout(e),this.flat=l2(this.layout.elements),this.selected&&!Dt(this.doc,this.selected)&&(this.selected=void 0);const t=this.zoom,n=this.canvasHost;this.renderedHostSize={width:n.clientWidth,height:n.clientHeight};const a={width:Math.max(320,this.layout.canvasSize.width,Math.floor(n.clientWidth/t)),height:Math.max(240,this.layout.canvasSize.height+60,Math.floor(n.clientHeight/t))};this.renderer.usesSimulationHighlight=this.simulating,this.renderer.fillsSelection=this.liveCoding,this.svg=this.renderer.render(this.layout,a,this.simulating?this.simPath:this.selected),this.svg.setAttribute("width",String(Math.floor(a.width*t))),this.svg.setAttribute("height",String(Math.floor(a.height*t))),this.overlay=fe("g",{class:"drop-overlay"}),this.svg.append(this.overlay),this.canvasHost.replaceChildren(this.svg),document.activeElement!==this.captionInput&&(this.captionInput.value=this.doc.caption),this.undoButton.disabled=this.simulating||this.undoStack.length===0,this.redoButton.disabled=this.simulating||this.redoStack.length===0,this.deleteButton.disabled=this.simulating||!this.selected||!er(this.doc,this.selected),this.captionInput.readOnly=this.simulating,this.codeButton.disabled=this.simulating,this.exportButton.disabled=this.simulating,this.coding&&this.code.refresh(),this.refreshLive(),this.refreshPreview(),this.renderTabs(),this.renderInspector(),this.updateStatus()}refreshLive(){this.liveCoding&&this.live.refresh(this.doc,this.simulating?this.simPath:this.selected,{owner:this.tab,subprograms:new Set(this.tabs.filter(e=>e!==this.tab).flatMap(e=>{var t;return((t=pt(e.doc.caption))==null?void 0:t.name)??[]})),editable:!this.simulating,resolve:e=>this.findSubprogram(e)})}updateStatus(){this.rememberExercise(),document.title=`${this.dirty?"• ":""}${this.fileName} – VisuStruct Web`,this.statusLine.textContent=`${this.fileName}${this.dirty?` (${p("web_status_modified")})`:""}`}renderInspector(){const e=this.selected,t=e?Dt(this.doc,e):void 0,n=this.inspector;if(!e||!t){n.replaceChildren(ae("h2",{},p("web_inspector_title")),ae("p",{class:"hint"},p("inspector_no_selection")),ae("p",{class:"hint"},p("web_inspector_help_drop")),ae("p",{class:"hint"},p("web_inspector_help_files")));return}if(n.replaceChildren(ae("h2",{},`${p("web_inspector_title")} · ${Gr(t.type)}`)),t.type===z.anweisung){const a=Ra(t.textLines.join(` + `,t.querySelector("[data-action=about-done]").addEventListener("click",()=>t.close()),t.addEventListener("click",n=>n.target===t&&t.close()),t.addEventListener("close",()=>t.remove()),document.body.append(t),t.showModal()}setupSettingsMenu(e,t){const n=a=>{t.hidden=!a,e.setAttribute("aria-expanded",String(a))};e.addEventListener("click",()=>n(t.hidden)),this.closeSettings&&document.removeEventListener("pointerdown",this.closeSettings),this.escapeSettings&&document.removeEventListener("keydown",this.escapeSettings),this.closeSettings=a=>{!t.hidden&&!e.parentElement.contains(a.target)&&n(!1)},document.addEventListener("pointerdown",this.closeSettings),this.escapeSettings=a=>{a.key!=="Escape"||t.hidden||(n(!1),e.focus())},document.addEventListener("keydown",this.escapeSettings)}learnRail(){return this.railButton=ae("button",{class:"learn-rail"}),this.labelLearnRail(),this.railButton.addEventListener("click",()=>this.setLearning(!0)),this.railButton}liveRail(){return this.liveRailButton=ae("button",{class:"learn-rail live-rail"}),this.labelLiveRail(),this.liveRailButton.addEventListener("click",()=>this.setLiveCoding(!0)),this.liveRailButton}labelLiveRail(){this.liveRailButton&&(this.liveRailButton.title=p("web_live_show"),this.liveRailButton.innerHTML=`${Yt}</> ${L(p("web_live_title"))}`)}labelLearnRail(){this.railButton&&(this.railButton.title=p("web_learn_show"),this.railButton.innerHTML=`${Yt}🎓 ${L(p("web_learn_title"))}`)}learnHost(){return{collapse:()=>this.setLearning(!1),showEditor:()=>{this.editorHidden&&this.setEditorHidden(!1)},showLiveCode:()=>{this.liveCoding||this.setLiveCoding(!0)},showJava:()=>this.openJavaColumn(),showFiles:()=>{this.shell.classList.contains("files-open")||this.setFilesOpen(!0)},openExercise:(e,t)=>{e.code==="java"?this.openJavaColumn():this.setEditorHidden(!1);const n=this.tabs.findIndex(s=>s.exerciseId===e.id);if(n>=0){this.switchTab(n),this.setSimulating(!1);return}const a=this.makeTab();a.doc=t,a.exerciseId=e.id,a.selected=t.elements.length>0?[0]:void 0,this.isPristine(this.tab)?this.tabs[this.tabIndex]=a:this.tabs.push(a),this.tabIndex=this.tabs.indexOf(a),this.setSimulating(!1),this.render()},openDiagram:(e,t)=>{this.setEditorHidden(!1),this.loadXML(n1(e),e.caption.trim()?`${e.caption.trim()}.visustruct`:t)},exerciseDocument:e=>{const t=this.tabs.find(a=>a.exerciseId===e);if(t)return t.doc;const n=this.tab;if(!(n.exerciseId||this.isPristine(n)))return n.exerciseId=e,ce.updateExercise(e,{xml:n1(n.doc)}),n.doc},subprogramsFor:e=>{const t=this.tabs.find(n=>n.exerciseId===e);return n=>this.findSubprogram(n,t)},stopSimulation:()=>this.setSimulating(!1),resetExercise:(e,t)=>{const n=this.tabs.find(a=>a.exerciseId===e);n&&(n.undoStack.push(n.doc),n.doc=t,n.redoStack=[],n.selected=[0],n===this.tab&&this.render())},preview:e=>{const t=Ec(e,this.metrics,this.measure,0);if(!t)return;const n=t.svg.getAttribute("width");return n&&(t.svg.style.maxWidth=`${n}px`),t.svg.removeAttribute("width"),t.svg.removeAttribute("height"),t.svg}}}isPristine(e){return!e.dirty&&!e.fileName&&!e.exerciseId&&e.undoStack.length===0}rememberExercise(){const e=this.tab;e.exerciseId&&(clearTimeout(this.exerciseSaveTimer),this.exerciseSaveTimer=window.setTimeout(()=>{e.exerciseId&&ce.updateExercise(e.exerciseId,{xml:n1(e.doc)})},300))}paletteIcon(e){const t=fe("svg",{viewBox:"0 0 28 20",width:28,height:20,class:"icon"}),n={fill:"none",stroke:"currentColor","stroke-width":1.5};t.append(fe("rect",{x:1,y:1,width:26,height:18,...n}));const a=s=>t.append(fe("path",{d:s,...n}));switch(e){case"verzweigung":a("M1 1 L14 10 L27 1 M14 10 V19");break;case"fallauswahl":a("M1 1 L20 10 L27 1 M1 10 H27 M10 10 V19 M20 10 V19");break;case"forZaehlSchleife":case"whileSchleife":a("M7 7 H27 M7 7 V19");break;case"doUntilSchleife":a("M7 1 V13 H27");break;case"endlosschleife":a("M7 6 H27 M7 6 V14 H27");break;case"aufruf":a("M5 1 V19 M23 1 V19");break;case"aussprung":a("M6 1 L1 10 L6 19");break}return t}render(){const e={...this.doc,elements:this.doc.elements.map(Ha)};this.layout=this.engine.layout(e),this.flat=l2(this.layout.elements),this.selected&&!Dt(this.doc,this.selected)&&(this.selected=void 0);const t=this.zoom,n=this.canvasHost;this.renderedHostSize={width:n.clientWidth,height:n.clientHeight};const a={width:Math.max(320,this.layout.canvasSize.width,Math.floor(n.clientWidth/t)),height:Math.max(240,this.layout.canvasSize.height+60,Math.floor(n.clientHeight/t))};this.renderer.usesSimulationHighlight=this.simulating,this.renderer.fillsSelection=this.liveCoding,this.svg=this.renderer.render(this.layout,a,this.simulating?this.simPath:this.selected),this.svg.setAttribute("width",String(Math.floor(a.width*t))),this.svg.setAttribute("height",String(Math.floor(a.height*t))),this.overlay=fe("g",{class:"drop-overlay"}),this.svg.append(this.overlay),this.canvasHost.replaceChildren(this.svg),document.activeElement!==this.captionInput&&(this.captionInput.value=this.doc.caption),this.undoButton.disabled=this.simulating||this.undoStack.length===0,this.redoButton.disabled=this.simulating||this.redoStack.length===0,this.deleteButton.disabled=this.simulating||!this.selected||!er(this.doc,this.selected),this.captionInput.readOnly=this.simulating,this.codeButton.disabled=this.simulating,this.exportButton.disabled=this.simulating,this.coding&&this.code.refresh(),this.refreshLive(),this.refreshPreview(),this.renderTabs(),this.renderInspector(),this.updateStatus()}refreshLive(){this.liveCoding&&this.live.refresh(this.doc,this.simulating?this.simPath:this.selected,{owner:this.tab,subprograms:new Set(this.tabs.filter(e=>e!==this.tab).flatMap(e=>{var t;return((t=pt(e.doc.caption))==null?void 0:t.name)??[]})),editable:!this.simulating,resolve:e=>this.findSubprogram(e)})}updateStatus(){this.rememberExercise(),document.title=`${this.dirty?"• ":""}${this.fileName} – VisuStruct Web`,this.statusLine.textContent=`${this.fileName}${this.dirty?` (${p("web_status_modified")})`:""}`}renderInspector(){const e=this.selected,t=e?Dt(this.doc,e):void 0,n=this.inspector;if(!e||!t){n.replaceChildren(ae("h2",{},p("web_inspector_title")),ae("p",{class:"hint"},p("inspector_no_selection")),ae("p",{class:"hint"},p("web_inspector_help_drop")),ae("p",{class:"hint"},p("web_inspector_help_files")));return}if(n.replaceChildren(ae("h2",{},`${p("web_inspector_title")} · ${Gr(t.type)}`)),t.type===z.anweisung){const a=Ra(t.textLines.join(` `)),s=ae("div",{class:"segmented",role:"group","aria-label":p("inspector_io_mode_title")});for(const[r,o]of[["statement",p("inspector_io_mode_statement")],["input",p("inspector_io_mode_input")],["output",p("inspector_io_mode_output")]]){const l=ae("button",{"aria-pressed":String(r===a)},o);l.addEventListener("click",()=>{var c,d;const u=((c=Dt(this.doc,e))==null?void 0:c.textLines.join(` `))??"";if(r===Ra(u))return;const m=qf(r,u);this.commit(Gi(this.doc,e,m.split(` `))),(d=this.inspector.querySelector("textarea"))==null||d.focus()}),s.append(l)}n.append(s,ae("p",{class:"hint mono-hint"},FF[a]))}if(t.type===z.forSchleife){const a=ae("div",{class:"for-fields"}),s=M0(t.textLines);[[p("inspector_for_init"),p("inspector_for_placeholder_init")],[p("inspector_for_condition"),p("inspector_for_placeholder_condition")],[p("inspector_for_step"),p("inspector_for_placeholder_step")]].forEach(([o,l],u)=>{const m=ae("input",{placeholder:l,spellcheck:"false",autocomplete:"off"});m.value=s[u],this.liveEdit(m,c=>{const d=Dt(this.doc,e);if(!d)return;const h=M0(d.textLines);return h[u]=Yf(c),Gi(this.doc,e,h)}),a.append(ae("label",{},o,m))}),n.append(a)}else if(t.type!==z.leerElement){const a=NF[t.type];a&&n.append(ae("p",{class:"hint mono-hint"},a));const s=Vc(t),r=ae("textarea",{rows:"3",spellcheck:"false"}),o=t.textLines.join(` `);r.value=s?Z0(s,o):o,r.placeholder=JF(t),r.addEventListener("focus",()=>{r.value.trim()==="ø"&&r.select()}),this.liveEdit(r,u=>{const m=Vc(Dt(this.doc,e)??t),c=m?$f(m,Z0(m,u)):u;return Gi(this.doc,e,c.split(` -`))});const l=ae("div",{class:"editor-row"});s&&l.append(ae("span",{class:"fixed-prefix"},s)),l.append(r),n.append(l)}this.renderCaseControls(e)}renderCaseControls(e){var l;const t=Hf(e,this.doc);if(!t)return;const n=((l=Dt(this.doc,t))==null?void 0:l.cases)??[],a=Vf(e,t),s=ae("div",{class:"case-controls"});if(a!==void 0&&n[a]){const u=ae("input",{placeholder:p("web_case_name_placeholder"),spellcheck:"false",autocomplete:"off"});u.value=n[a].name,this.liveEdit(u,m=>m.trim()===""?void 0:Gf(this.doc,t,a,m)),s.append(ae("label",{},p("web_case_name"),u))}const r=ae("button",{},`+ ${p("inspector_add_case")}`);r.addEventListener("click",()=>{const u=Jf(this.doc,t);this.commit(u.doc,u.path)});const o=ae("button",{class:"danger-text"},`- ${p("inspector_remove_case")}`);o.disabled=n.length<=2||a===void 0,o.addEventListener("click",()=>{if(a===void 0)return;const u=Rf(this.doc,t,a);this.commit(u.doc,u.path)}),s.append(ae("div",{class:"group"},r,o)),this.inspector.append(s)}liveEdit(e,t){let n;e.addEventListener("focus",()=>n=this.doc),e.addEventListener("input",()=>{const a=hd(e.value);if(a!==e.value){const r=e.selectionStart;e.value=a,e.setSelectionRange(r,r)}const s=t(a);s&&(this.doc=s,this.dirty=!0,this.renderDiagramOnly())}),e.addEventListener("blur",()=>{n&&n!==this.doc&&this.pushUndo(n),n=void 0,this.renderDiagramOnly()})}renderDiagramOnly(){const e=this.selected,t=this.inspector,n=document.createElement("aside");this.inspector=n,this.render(),this.inspector=t,this.selected=e}setSimulating(e){var t;e!==this.simulating&&(document.activeElement instanceof HTMLElement&&document.activeElement.blur(),this.endDrag(),this.simulating=e,this.root.classList.toggle("simulating",e),this.simButton.setAttribute("aria-pressed",String(e)),this.simButton.innerHTML=`${e?ee.stop:ee.play}${L(p(e?"web_simulation_end":"web_simulation_start"))}`,this.simButton.dataset.tip=p(e?"web_simulation_end_title":"web_simulation_start_title"),this.simButton.setAttribute("aria-label",p(e?"web_simulation_end":"web_simulation_start")),e?(this.setCoding(!1),this.setEditorHidden(!1),(t=this.visuBot)==null||t.setWorlds(od(this.tab.exerciseId)),this.sim.begin()):(this.sim.end(),this.simPath=void 0,!this.selected&&this.doc.elements.length>0&&(this.selected=[0])),this.render())}runRobot(e){return!this.visuBot||!/\bmbot\s*\./u.test(JSON.stringify(this.tabs.map(t=>t.doc)))?!1:(this.simulating?this.sim.reset():this.setSimulating(!0),e?this.sim.step():this.sim.play(),!0)}setCoding(e){e!==this.coding&&(e&&(this.setLiveCoding(!1),this.setEditorHidden(!1)),this.coding=e,this.root.classList.toggle("coding",e),this.codeButton.setAttribute("aria-pressed",String(e)),e?this.code.refresh():this.code.close(),this.renderDiagramOnly())}openJavaColumn(){if(this.live.language!=="java"){const e="[data-action=live-language]",t=this.topbar.querySelector(e)??this.root.querySelector(e);t?(t.value="java",t.dispatchEvent(new Event("change"))):this.live.setTarget("java")}this.liveCoding||this.setLiveCoding(!0)}setCodeMain(e){this.codeMain=e,at(td,e?"1":"0"),e&&!this.liveCoding&&this.setLiveCoding(!0),e&&this.editorHidden&&this.setEditorHidden(!1),this.shell.classList.toggle("code-main",e),this.labelSwap(),this.canvasHost&&this.render()}labelSwap(){const e=p(this.codeMain?"web_swap_to_editor":"web_swap_to_code");for(const t of this.shell.querySelectorAll("[data-action=swap-main]"))t.dataset.tip=e,t.setAttribute("aria-label",e),t.setAttribute("aria-pressed",String(this.codeMain))}setupPreview(){this.preview.onHide=()=>this.setPreviewOpen(!1),this.preview.rail.addEventListener("click",()=>this.setPreviewOpen(!0)),this.preview.onToggleStacked=()=>{this.previewStacked=!this.previewStacked,at(ad,this.previewStacked?"1":"0"),this.previewStacked&&!this.liveCoding&&this.setLiveCoding(!0),this.placePreview()},this.previewStacked=Xe(ad)==="1";const e=Xe(ed);this.previewOpen=e===null||e==="1";const t=this.preview.heightBar,n=this.preview.element,a=(r,o)=>{var m;const l=Math.max(160,(((m=n.parentElement)==null?void 0:m.getBoundingClientRect().height)??600)-120),u=r===void 0?void 0:Math.round(Math.max(160,Math.min(r,l)));n.style.height=u===void 0?"":`${u}px`,o&&at(sd,u===void 0?"":String(u))},s=Number(Xe(sd));s>0&&(n.style.height=`${s}px`),t.addEventListener("pointerdown",r=>{if(r.button!==0)return;r.preventDefault(),t.setPointerCapture(r.pointerId);const o=r.clientY,l=n.getBoundingClientRect().height;this.shell.classList.add("resizing");const u=c=>a(l-(c.clientY-o),!1),m=c=>{t.removeEventListener("pointermove",u),t.removeEventListener("pointerup",m),t.removeEventListener("pointercancel",m),this.shell.classList.remove("resizing"),a(l-(c.clientY-o),!0)};t.addEventListener("pointermove",u),t.addEventListener("pointerup",m),t.addEventListener("pointercancel",m)}),t.addEventListener("dblclick",()=>a(void 0,!0)),t.addEventListener("keydown",r=>{const o=r.key==="ArrowUp"?20:r.key==="ArrowDown"?-20:0;o&&(r.preventDefault(),a(n.getBoundingClientRect().height+o,!0))}),this.placePreview()}setPreviewOpen(e){this.previewOpen=e,at(ed,e?"1":"0"),e||this.preview.pause(),this.placePreview(),this.canvasHost&&this.render()}placePreview(){const e=this.previewStacked&&this.liveCoding;this.preview.setStacked(this.previewStacked),this.shell.classList.toggle("preview",this.previewOpen),this.shell.classList.toggle("preview-stacked",e),e?this.preview.element.parentElement!==this.live.element&&this.live.element.append(this.preview.element):this.preview.element.previousElementSibling!==this.previewResizer&&this.previewResizer.after(this.preview.element)}refreshPreview(){!this.previewOpen||!Wn()||this.preview.update(this.doc,e=>this.findSubprogram(e),od(this.tab.exerciseId),this.tab.exerciseId??"",this.tabs.map(e=>e.doc))}setLiveCoding(e){e&&this.coding&&this.setCoding(!1),this.liveCoding=e,this.shell.classList.toggle("live",e),this.placePreview(),e||this.live.hideConsole(),at(Kc,e?"1":"0"),this.keepAColumnOpen(),this.canvasHost&&this.render()}learnResizer(){return this.panelResizer(this.learn.element,"learn-resizer",VF,p("web_learn_resize"),1)}liveResizer(){return this.panelResizer(this.live.element,"live-resizer",QF,p("web_live_resize"),-1)}panelResizer(e,t,n,a,s){const r=ae("div",{class:t,role:"separator","aria-orientation":"vertical",tabindex:"0",title:a}),o=c=>{var f;const d=((f=e.parentElement)==null?void 0:f.getBoundingClientRect().width)??0;if(d===0)return KF(c);const h=[this.files.element,this.learn.element,this.live.element,this.preview.element].filter(x=>x!==e&&x.offsetParent!==null&&getComputedStyle(x).flexGrow==="0").reduce((x,b)=>x+b.getBoundingClientRect().width,0),g=parseFloat(getComputedStyle(e).minWidth)||200;return Math.round(Math.max(g,Math.min(c,d-h-240)))},l=(c,d)=>{e.style.width=c===void 0?"":`${o(c)}px`,d&&at(n,c===void 0?"":String(o(c)))},u=Number(Xe(n));u>0&&l(u,!1);const m=()=>getComputedStyle(this.shell).direction==="rtl"?-s:s;return r.addEventListener("pointerdown",c=>{if(c.button!==0)return;c.preventDefault(),r.setPointerCapture(c.pointerId);const d=c.clientX,h=e.getBoundingClientRect().width,g=m();this.shell.classList.add("resizing");const f=b=>l(h+g*(b.clientX-d),!1),x=b=>{r.removeEventListener("pointermove",f),r.removeEventListener("pointerup",x),r.removeEventListener("pointercancel",x),this.shell.classList.remove("resizing"),l(h+g*(b.clientX-d),!0)};r.addEventListener("pointermove",f),r.addEventListener("pointerup",x),r.addEventListener("pointercancel",x)}),r.addEventListener("dblclick",()=>l(void 0,!0)),r.addEventListener("keydown",c=>{const d=c.key==="ArrowRight"?20:c.key==="ArrowLeft"?-20:0;d&&(c.preventDefault(),l(e.getBoundingClientRect().width+m()*d,!0))}),r}findSubprogram(e,t=this.tab){const n=Qr(e);if(n==="")return;const a=this.tabs.find(s=>s!==t&&(Qr(s.doc.caption)===n||Qr(an(s))===n));return a==null?void 0:a.doc}scrollToSimPath(){const e=this.simPath;if(!this.simulating||!e)return;const t=this.flat.find(o=>eo(o.idPath,e));if(!t)return;const n=this.canvasHost,a=this.zoom,s={x:t.frame.x*a,y:t.frame.y*a,width:t.frame.width*a,height:t.frame.height*a},r=24;s.yn.scrollTop+n.clientHeight&&(n.scrollTop=s.y-r),(s.xn.scrollLeft+n.clientWidth-r)&&(n.scrollLeft=Math.max(0,s.x-r))}commit(e,t){this.codeTyping=void 0,this.pushUndo(this.doc),this.doc=e,this.dirty=!0,t&&(this.selected=t),this.render()}commitFromCode(e,t){const n=Date.now(),a=this.codeTyping;!a||a.tab!==this.tab||n-a.last>1e3||n-a.start>5e3?(this.pushUndo(this.doc),this.codeTyping={tab:this.tab,start:n,last:n}):a.last=n,this.doc=e,this.dirty=!0,this.selected=tr(t??this.selected,e),this.render()}pushUndo(e){for(this.undoStack.push(e);this.undoStack.length>YF;)this.undoStack.shift();this.tab.redoStack=[]}undo(){const e=this.undoStack.pop();e&&(this.codeTyping=void 0,this.redoStack.push(this.doc),this.doc=e,this.dirty=!0,this.selected=tr(this.selected,this.doc),this.render())}redo(){const e=this.redoStack.pop();e&&(this.codeTyping=void 0,this.undoStack.push(this.doc),this.doc=e,this.dirty=!0,this.selected=tr(this.selected,this.doc),this.render())}resetHistory(){this.setSimulating(!1),this.tab.undoStack=[],this.tab.redoStack=[],this.selected=void 0,this.dirty=!1,this.render()}makeTab(){return{doc:Wf(),serial:this.nextTabSerial++,dirty:!1,undoStack:[],redoStack:[],selected:[0]}}addTab(e=this.makeTab()){this.setSimulating(!1),this.tabs.push(e),this.tabIndex=this.tabs.length-1,this.render()}switchTab(e){e===this.tabIndex||!this.tabs[e]||(document.activeElement instanceof HTMLElement&&document.activeElement.blur(),this.setSimulating(!1),this.tabIndex=e,this.render())}async closeTab(e){if(this.tabs.length<=1)return;const t=this.tabs[e];t.dirty&&!t.exerciseId&&(this.switchTab(e),!await this.confirmDiscard())||(this.setSimulating(!1),this.tabs.splice(e,1),(this.tabIndex>e||this.tabIndex>=this.tabs.length)&&(this.tabIndex=Math.max(0,this.tabIndex-1)),this.render())}renderTabs(){const e=this.tabStrip;e.replaceChildren(),this.tabs.forEach((n,a)=>{const s=document.createElement("div");s.className="tab"+(a===this.tabIndex?" active":""),s.setAttribute("role","tab"),s.setAttribute("aria-selected",String(a===this.tabIndex));const r=document.createElement("button");r.className="tab-label",r.textContent=an(n),r.title=n.fileName??an(n),r.addEventListener("click",()=>this.switchTab(a)),s.append(r);const o=n.dirty&&!n.exerciseId;if(this.tabs.length>1){const l=document.createElement("button");l.className="tab-close"+(o?" unsaved":""),l.innerHTML='✕',l.title=p("a11y_close_tab"),l.setAttribute("aria-label",`${p("a11y_close_tab")}: ${an(n)}`),l.addEventListener("click",()=>this.closeTab(a)),s.append(l)}else o&&s.append(Object.assign(document.createElement("span"),{className:"tab-close unsaved",innerHTML:'●'}));o&&r.setAttribute("aria-label",`${an(n)} (${p("web_status_modified")})`),e.append(s)});const t=document.createElement("button");t.className="tab-add",t.textContent="+",t.title=p("a11y_new_diagram_tab"),t.setAttribute("aria-label",p("a11y_new_diagram_tab")),t.addEventListener("click",()=>this.addTab()),e.append(t)}copySelection(){const e=this.selected&&Dt(this.doc,this.selected);return e?(this.clipboard=structuredClone(e),this.showMessage(p("web_copied")),!0):!1}cutSelection(){this.selected&&er(this.doc,this.selected)&&this.copySelection()&&this.deleteSelection()}paste(){this.clipboard&&this.insertNearSelection(structuredClone(this.clipboard))}deleteSelection(){!this.selected||!er(this.doc,this.selected)||(this.commit(gi(this.doc,this.selected)),this.selected=void 0,this.render())}insertSensor(e,t=this.selected){if(!t||vn(this.doc,t))return;const n=kt(this.doc,t);if(!Gc.includes(n.type))return;const a=(n.textLines??[]).join(" ").trim();this.commit(Gi(this.doc,t,[a?`${a} ${e}`:e]),t);const s=this.inspector.querySelector("textarea");s&&(s.focus(),s.setSelectionRange(s.value.length,s.value.length))}insertNearSelection(e){const t=this.selected;if(t&&vn(this.doc,t))return this.commit(Tn(this.doc,t,e),t);if(t){const n=[...t.slice(0,-1),t[t.length-1]+1];return this.commit(Ur(this.doc,e,t),n)}if(this.doc.elements.length===1&&vn(this.doc,[0]))return this.commit(Tn(this.doc,[0],e),[0]);this.commit(X1(this.doc,[],this.doc.elements.length,e),[this.doc.elements.length])}confirmDiscard(){return this.dirty?new Promise(e=>{const t=document.createElement("div");t.className="confirm",t.innerHTML=`
+`))});const l=ae("div",{class:"editor-row"});s&&l.append(ae("span",{class:"fixed-prefix"},s)),l.append(r),n.append(l)}this.renderCaseControls(e)}renderCaseControls(e){var l;const t=Hf(e,this.doc);if(!t)return;const n=((l=Dt(this.doc,t))==null?void 0:l.cases)??[],a=Vf(e,t),s=ae("div",{class:"case-controls"});if(a!==void 0&&n[a]){const u=ae("input",{placeholder:p("web_case_name_placeholder"),spellcheck:"false",autocomplete:"off"});u.value=n[a].name,this.liveEdit(u,m=>m.trim()===""?void 0:Gf(this.doc,t,a,m)),s.append(ae("label",{},p("web_case_name"),u))}const r=ae("button",{},`+ ${p("inspector_add_case")}`);r.addEventListener("click",()=>{const u=Jf(this.doc,t);this.commit(u.doc,u.path)});const o=ae("button",{class:"danger-text"},`- ${p("inspector_remove_case")}`);o.disabled=n.length<=2||a===void 0,o.addEventListener("click",()=>{if(a===void 0)return;const u=Rf(this.doc,t,a);this.commit(u.doc,u.path)}),s.append(ae("div",{class:"group"},r,o)),this.inspector.append(s)}liveEdit(e,t){let n;e.addEventListener("focus",()=>n=this.doc),e.addEventListener("input",()=>{const a=hd(e.value);if(a!==e.value){const r=e.selectionStart;e.value=a,e.setSelectionRange(r,r)}const s=t(a);s&&(this.doc=s,this.dirty=!0,this.renderDiagramOnly())}),e.addEventListener("blur",()=>{n&&n!==this.doc&&this.pushUndo(n),n=void 0,this.renderDiagramOnly()})}renderDiagramOnly(){const e=this.selected,t=this.inspector,n=document.createElement("aside");this.inspector=n,this.render(),this.inspector=t,this.selected=e}setSimulating(e){var t;e!==this.simulating&&(document.activeElement instanceof HTMLElement&&document.activeElement.blur(),this.endDrag(),this.simulating=e,this.root.classList.toggle("simulating",e),this.simButton.setAttribute("aria-pressed",String(e)),this.simButton.innerHTML=`${e?ee.stop:ee.play}${L(p(e?"web_simulation_end":"web_simulation_start"))}`,this.simButton.dataset.tip=p(e?"web_simulation_end_title":"web_simulation_start_title"),this.simButton.setAttribute("aria-label",p(e?"web_simulation_end":"web_simulation_start")),e?(this.setCoding(!1),this.setEditorHidden(!1),(t=this.visuBot)==null||t.setWorlds(od(this.tab.exerciseId)),this.sim.begin()):(this.sim.end(),this.simPath=void 0,!this.selected&&this.doc.elements.length>0&&(this.selected=[0])),this.render())}runRobot(e){return!this.visuBot||!/\bmbot\s*\./u.test(JSON.stringify(this.tabs.map(t=>t.doc)))?!1:(this.simulating?this.sim.reset():this.setSimulating(!0),e?this.sim.step():this.sim.play(),!0)}setCoding(e){e!==this.coding&&(e&&(this.setLiveCoding(!1),this.setEditorHidden(!1)),this.coding=e,this.root.classList.toggle("coding",e),this.codeButton.setAttribute("aria-pressed",String(e)),e?this.code.refresh():this.code.close(),this.renderDiagramOnly())}openJavaColumn(){if(this.live.language!=="java"){const e="[data-action=live-language]",t=this.topbar.querySelector(e)??this.root.querySelector(e);t?(t.value="java",t.dispatchEvent(new Event("change"))):this.live.setTarget("java")}this.liveCoding||this.setLiveCoding(!0)}setCodeMain(e){this.codeMain=e,at(td,e?"1":"0"),e&&!this.liveCoding&&this.setLiveCoding(!0),e&&this.editorHidden&&this.setEditorHidden(!1),this.shell.classList.toggle("code-main",e),this.labelSwap(),this.canvasHost&&this.render()}labelSwap(){const e=p(this.codeMain?"web_swap_to_editor":"web_swap_to_code");for(const t of this.shell.querySelectorAll("[data-action=swap-main]"))t.dataset.tip=e,t.setAttribute("aria-label",e),t.setAttribute("aria-pressed",String(this.codeMain))}setupPreview(){this.preview.onHide=()=>this.setPreviewOpen(!1),this.preview.rail.addEventListener("click",()=>this.setPreviewOpen(!0)),this.preview.onToggleStacked=()=>{this.previewStacked=!this.previewStacked,at(ad,this.previewStacked?"1":"0"),this.previewStacked&&!this.liveCoding&&this.setLiveCoding(!0),this.placePreview()},this.previewStacked=Xe(ad)==="1";const e=Xe(ed);this.previewOpen=e===null||e==="1";const t=this.preview.heightBar,n=this.preview.element,a=(r,o)=>{var m;const l=Math.max(160,(((m=n.parentElement)==null?void 0:m.getBoundingClientRect().height)??600)-120),u=r===void 0?void 0:Math.round(Math.max(160,Math.min(r,l)));n.style.height=u===void 0?"":`${u}px`,o&&at(sd,u===void 0?"":String(u))},s=Number(Xe(sd));s>0&&(n.style.height=`${s}px`),t.addEventListener("pointerdown",r=>{if(r.button!==0)return;r.preventDefault(),t.setPointerCapture(r.pointerId);const o=r.clientY,l=n.getBoundingClientRect().height;this.shell.classList.add("resizing");const u=c=>a(l-(c.clientY-o),!1),m=c=>{t.removeEventListener("pointermove",u),t.removeEventListener("pointerup",m),t.removeEventListener("pointercancel",m),this.shell.classList.remove("resizing"),a(l-(c.clientY-o),!0)};t.addEventListener("pointermove",u),t.addEventListener("pointerup",m),t.addEventListener("pointercancel",m)}),t.addEventListener("dblclick",()=>a(void 0,!0)),t.addEventListener("keydown",r=>{const o=r.key==="ArrowUp"?20:r.key==="ArrowDown"?-20:0;o&&(r.preventDefault(),a(n.getBoundingClientRect().height+o,!0))}),this.placePreview()}setPreviewOpen(e){this.previewOpen=e,at(ed,e?"1":"0"),e||this.preview.pause(),this.placePreview(),this.canvasHost&&this.render()}placePreview(){const e=this.previewStacked&&this.liveCoding;this.preview.setStacked(this.previewStacked),this.shell.classList.toggle("preview",this.previewOpen),this.shell.classList.toggle("preview-stacked",e),e?this.preview.element.parentElement!==this.live.element&&this.live.element.append(this.preview.element):this.preview.element.previousElementSibling!==this.previewResizer&&this.previewResizer.after(this.preview.element)}refreshPreview(){!this.previewOpen||!En()||this.preview.update(this.doc,e=>this.findSubprogram(e),od(this.tab.exerciseId),this.tab.exerciseId??"",this.tabs.map(e=>e.doc))}setLiveCoding(e){e&&this.coding&&this.setCoding(!1),this.liveCoding=e,this.shell.classList.toggle("live",e),this.placePreview(),e||this.live.hideConsole(),at(Kc,e?"1":"0"),this.keepAColumnOpen(),this.canvasHost&&this.render()}learnResizer(){return this.panelResizer(this.learn.element,"learn-resizer",VF,p("web_learn_resize"),1)}liveResizer(){return this.panelResizer(this.live.element,"live-resizer",QF,p("web_live_resize"),-1)}panelResizer(e,t,n,a,s){const r=ae("div",{class:t,role:"separator","aria-orientation":"vertical",tabindex:"0",title:a}),o=c=>{var f;const d=((f=e.parentElement)==null?void 0:f.getBoundingClientRect().width)??0;if(d===0)return KF(c);const h=[this.files.element,this.learn.element,this.live.element,this.preview.element].filter(x=>x!==e&&x.offsetParent!==null&&getComputedStyle(x).flexGrow==="0").reduce((x,b)=>x+b.getBoundingClientRect().width,0),g=parseFloat(getComputedStyle(e).minWidth)||200;return Math.round(Math.max(g,Math.min(c,d-h-240)))},l=(c,d)=>{e.style.width=c===void 0?"":`${o(c)}px`,d&&at(n,c===void 0?"":String(o(c)))},u=Number(Xe(n));u>0&&l(u,!1);const m=()=>getComputedStyle(this.shell).direction==="rtl"?-s:s;return r.addEventListener("pointerdown",c=>{if(c.button!==0)return;c.preventDefault(),r.setPointerCapture(c.pointerId);const d=c.clientX,h=e.getBoundingClientRect().width,g=m();this.shell.classList.add("resizing");const f=b=>l(h+g*(b.clientX-d),!1),x=b=>{r.removeEventListener("pointermove",f),r.removeEventListener("pointerup",x),r.removeEventListener("pointercancel",x),this.shell.classList.remove("resizing"),l(h+g*(b.clientX-d),!0)};r.addEventListener("pointermove",f),r.addEventListener("pointerup",x),r.addEventListener("pointercancel",x)}),r.addEventListener("dblclick",()=>l(void 0,!0)),r.addEventListener("keydown",c=>{const d=c.key==="ArrowRight"?20:c.key==="ArrowLeft"?-20:0;d&&(c.preventDefault(),l(e.getBoundingClientRect().width+m()*d,!0))}),r}findSubprogram(e,t=this.tab){const n=Qr(e);if(n==="")return;const a=this.tabs.find(s=>s!==t&&(Qr(s.doc.caption)===n||Qr(an(s))===n));return a==null?void 0:a.doc}scrollToSimPath(){const e=this.simPath;if(!this.simulating||!e)return;const t=this.flat.find(o=>eo(o.idPath,e));if(!t)return;const n=this.canvasHost,a=this.zoom,s={x:t.frame.x*a,y:t.frame.y*a,width:t.frame.width*a,height:t.frame.height*a},r=24;s.yn.scrollTop+n.clientHeight&&(n.scrollTop=s.y-r),(s.xn.scrollLeft+n.clientWidth-r)&&(n.scrollLeft=Math.max(0,s.x-r))}commit(e,t){this.codeTyping=void 0,this.pushUndo(this.doc),this.doc=e,this.dirty=!0,t&&(this.selected=t),this.render()}commitFromCode(e,t){const n=Date.now(),a=this.codeTyping;!a||a.tab!==this.tab||n-a.last>1e3||n-a.start>5e3?(this.pushUndo(this.doc),this.codeTyping={tab:this.tab,start:n,last:n}):a.last=n,this.doc=e,this.dirty=!0,this.selected=tr(t??this.selected,e),this.render()}pushUndo(e){for(this.undoStack.push(e);this.undoStack.length>YF;)this.undoStack.shift();this.tab.redoStack=[]}undo(){const e=this.undoStack.pop();e&&(this.codeTyping=void 0,this.redoStack.push(this.doc),this.doc=e,this.dirty=!0,this.selected=tr(this.selected,this.doc),this.render())}redo(){const e=this.redoStack.pop();e&&(this.codeTyping=void 0,this.undoStack.push(this.doc),this.doc=e,this.dirty=!0,this.selected=tr(this.selected,this.doc),this.render())}resetHistory(){this.setSimulating(!1),this.tab.undoStack=[],this.tab.redoStack=[],this.selected=void 0,this.dirty=!1,this.render()}makeTab(){return{doc:Wf(),serial:this.nextTabSerial++,dirty:!1,undoStack:[],redoStack:[],selected:[0]}}addTab(e=this.makeTab()){this.setSimulating(!1),this.tabs.push(e),this.tabIndex=this.tabs.length-1,this.render()}switchTab(e){e===this.tabIndex||!this.tabs[e]||(document.activeElement instanceof HTMLElement&&document.activeElement.blur(),this.setSimulating(!1),this.tabIndex=e,this.render())}async closeTab(e){if(this.tabs.length<=1)return;const t=this.tabs[e];t.dirty&&!t.exerciseId&&(this.switchTab(e),!await this.confirmDiscard())||(this.setSimulating(!1),this.tabs.splice(e,1),(this.tabIndex>e||this.tabIndex>=this.tabs.length)&&(this.tabIndex=Math.max(0,this.tabIndex-1)),this.render())}renderTabs(){const e=this.tabStrip;e.replaceChildren(),this.tabs.forEach((n,a)=>{const s=document.createElement("div");s.className="tab"+(a===this.tabIndex?" active":""),s.setAttribute("role","tab"),s.setAttribute("aria-selected",String(a===this.tabIndex));const r=document.createElement("button");r.className="tab-label",r.textContent=an(n),r.title=n.fileName??an(n),r.addEventListener("click",()=>this.switchTab(a)),s.append(r);const o=n.dirty&&!n.exerciseId;if(this.tabs.length>1){const l=document.createElement("button");l.className="tab-close"+(o?" unsaved":""),l.innerHTML='✕',l.title=p("a11y_close_tab"),l.setAttribute("aria-label",`${p("a11y_close_tab")}: ${an(n)}`),l.addEventListener("click",()=>this.closeTab(a)),s.append(l)}else o&&s.append(Object.assign(document.createElement("span"),{className:"tab-close unsaved",innerHTML:'●'}));o&&r.setAttribute("aria-label",`${an(n)} (${p("web_status_modified")})`),e.append(s)});const t=document.createElement("button");t.className="tab-add",t.textContent="+",t.title=p("a11y_new_diagram_tab"),t.setAttribute("aria-label",p("a11y_new_diagram_tab")),t.addEventListener("click",()=>this.addTab()),e.append(t)}copySelection(){const e=this.selected&&Dt(this.doc,this.selected);return e?(this.clipboard=structuredClone(e),this.showMessage(p("web_copied")),!0):!1}cutSelection(){this.selected&&er(this.doc,this.selected)&&this.copySelection()&&this.deleteSelection()}paste(){this.clipboard&&this.insertNearSelection(structuredClone(this.clipboard))}deleteSelection(){!this.selected||!er(this.doc,this.selected)||(this.commit(gi(this.doc,this.selected)),this.selected=void 0,this.render())}insertSensor(e,t=this.selected){if(!t||vn(this.doc,t))return;const n=kt(this.doc,t);if(!Gc.includes(n.type))return;const a=(n.textLines??[]).join(" ").trim();this.commit(Gi(this.doc,t,[a?`${a} ${e}`:e]),t);const s=this.inspector.querySelector("textarea");s&&(s.focus(),s.setSelectionRange(s.value.length,s.value.length))}insertNearSelection(e){const t=this.selected;if(t&&vn(this.doc,t))return this.commit(Tn(this.doc,t,e),t);if(t){const n=[...t.slice(0,-1),t[t.length-1]+1];return this.commit(Ur(this.doc,e,t),n)}if(this.doc.elements.length===1&&vn(this.doc,[0]))return this.commit(Tn(this.doc,[0],e),[0]);this.commit(X1(this.doc,[],this.doc.elements.length,e),[this.doc.elements.length])}confirmDiscard(){return this.dirty?new Promise(e=>{const t=document.createElement("div");t.className="confirm",t.innerHTML=`

${L(p("close_unsaved_title"))}

${L(p("web_discard_message_fmt",this.fileName))}

-
`,t.addEventListener("click",n=>{const a=n.target.dataset.r;a===void 0&&n.target!==t||(t.remove(),e(a==="1"))}),document.body.append(t),t.querySelector('[data-r="0"]').focus()}):Promise.resolve(!0)}showMessage(e){this.statusLine.textContent=e,this.statusLine.classList.add("message"),setTimeout(()=>{this.statusLine.classList.remove("message"),this.updateStatus()},6e3)}loadXML(e,t,n){let a;try{a=Il(e)}catch(s){this.showMessage(p("web_err_unreadable_fmt",t,s.message));return}(this.dirty||this.tab.fileName||this.tab.exerciseId)&&this.addTab(),this.doc=a,this.tab.fileName=t.replace(/\.(strk|xml)$/i,".visustruct"),this.fileHandle=n&&/\.visustruct$/i.test(t)?n:void 0,this.resetHistory()}async open(e){const t=window;if(!t.showOpenFilePicker||this.inViewer)return e.click();try{const[n]=await t.showOpenFilePicker({types:Hc()}),a=await n.getFile();this.loadXML(await a.text(),a.name,n)}catch{}}async save(){var n,a;if(!this.downloads&&await this.saveToWorkspace())return;const e=new Blob([n1(this.doc)],{type:"application/xml"}),t=window;try{if(this.downloads){const s=this.fileName+".txt";await this.downloads.save({filename:s,data:e}),(n=this.tab).fileName??(n.fileName=this.fileName),this.dirty=!1,this.render(),this.showMessage(p("web_saved_txt_fmt",s));return}if(!this.fileHandle&&t.showSaveFilePicker&&!this.inViewer&&(this.fileHandle=await t.showSaveFilePicker({suggestedName:this.fileName,types:Hc()}),this.tab.fileName=this.fileHandle.name),this.fileHandle){const s=await this.fileHandle.createWritable();await s.write(e),await s.close()}else{const s=document.createElement("a");s.href=URL.createObjectURL(e),s.download=this.fileName,s.click(),setTimeout(()=>URL.revokeObjectURL(s.href),1e3)}(a=this.tab).fileName??(a.fileName=this.fileName),this.dirty=!1,this.render()}catch{}}async exportDiagram(e){if(e==="visustruct"){const s=Wc(this.doc,an(this.tab));return this.offerDownload(`${s}.visustruct`,new Blob([n1(this.doc)],{type:"application/xml"}))}const t=Ec(this.doc,this.metrics,this.measure);if(!t){this.showMessage(p(e==="print"?"err_diagram_too_small_print":"err_diagram_too_small_export"));return}const n=Wc(this.doc,an(this.tab)),a=Math.max(2,window.devicePixelRatio||1)*this.zoom;try{switch(e){case"svg":{t.svg.setAttribute("width",String(t.width*this.zoom)),t.svg.setAttribute("height",String(t.height*this.zoom)),await this.offerDownload(`${n}.svg`,new Blob([If(t)],{type:"image/svg+xml"}));break}case"png":{const s=await Nc(t,a);await this.offerDownload(`${n}.png`,await TF(s));break}case"pdf":{const s=await Nc(t,Math.max(a,3)),r=await PF(jF(s),s.width,s.height,t,zf(this.doc));await this.offerDownload(`${n}.pdf`,r);break}case"print":this.printDiagram(t);break}}catch(s){this.showMessage(p("web_export_failed_fmt",s instanceof Error?s.message:String(s)))}}printDiagram(e){const t=document.createElement("div");t.className="print-sheet",e.svg.removeAttribute("width"),e.svg.removeAttribute("height"),t.append(e.svg),document.body.append(t);const n=()=>t.remove();window.addEventListener("afterprint",n,{once:!0});try{window.print()}catch{n(),this.showMessage(`${p("err_print_unavailable")} ${p("web_print_hint")}`);return}setTimeout(n,6e4)}async offerDownload(e,t){try{if(this.downloads){try{await this.downloads.save({filename:e,data:t}),this.showMessage(p("web_saved_fmt",e))}catch{await this.downloads.save({filename:e+".txt",data:t}),this.showMessage(p("web_saved_txt_fmt",e+".txt"))}return}const n=document.createElement("a");n.href=URL.createObjectURL(t),n.download=e,n.click(),setTimeout(()=>URL.revokeObjectURL(n.href),1e3)}catch{this.showMessage(p("err_save_failed_fmt",e))}}setupFileDrop(){window.addEventListener("dragover",e=>{var t;(t=e.dataTransfer)!=null&&t.types.includes("Files")&&(e.preventDefault(),this.root.classList.add("file-drag"))}),window.addEventListener("dragleave",e=>{e.relatedTarget===null&&this.root.classList.remove("file-drag")}),window.addEventListener("drop",async e=>{var n;this.root.classList.remove("file-drag");const t=(n=e.dataTransfer)==null?void 0:n.files[0];t&&(e.preventDefault(),this.loadXML(await t.text(),t.name))})}onKeyDown(e){var a,s;const t=e.metaKey||e.ctrlKey,n=e.target instanceof HTMLTextAreaElement||e.target instanceof HTMLInputElement||((a=e.target)==null?void 0:a.isContentEditable)===!0;if(t&&e.key.toLowerCase()==="s")e.preventDefault(),this.save();else if(t&&e.key.toLowerCase()==="p")e.preventDefault(),this.simulating||this.exportDiagram("print");else if(t&&e.key.toLowerCase()==="o")e.preventDefault(),this.open(this.root.querySelector("input[type=file]"));else{if(n||this.simulating)return;t&&e.key.toLowerCase()==="z"?(e.preventDefault(),e.shiftKey?this.redo():this.undo()):t&&e.key.toLowerCase()==="c"&&!((s=getSelection())!=null&&s.toString())?this.copySelection()&&e.preventDefault():t&&e.key.toLowerCase()==="x"?(e.preventDefault(),this.cutSelection()):t&&e.key.toLowerCase()==="v"?(e.preventDefault(),this.paste()):t&&e.key.toLowerCase()==="y"?(e.preventDefault(),this.redo()):e.key==="Delete"||e.key==="Backspace"?(e.preventDefault(),this.deleteSelection()):e.key==="Escape"&&(this.drag?this.endDrag():(this.selected=void 0,this.render()))}}svgPoint(e,t){if(!this.svg)return;const n=this.svg.getBoundingClientRect(),a=e-n.left,s=t-n.top;if(!(a<0||s<0||a>n.width||s>n.height))return{x:a/this.zoom,y:s/this.zoom}}nodeAt(e,t){for(let n=this.flat.length-1;n>=0;n--){const a=this.flat[n].frame;if(e>=a.x&&e<=a.x+a.width&&t>=a.y&&t<=a.y+a.height)return this.flat[n]}}onCanvasPointerDown(e){if(this.simulating)return;const t=this.svgPoint(e.clientX,e.clientY);if(!t)return;document.activeElement instanceof HTMLElement&&document.activeElement.blur();const n=this.nodeAt(t.x,t.y),a=n&&this.selected&&eo(n.idPath,this.selected);this.selected=n==null?void 0:n.idPath,this.render(),n&&e.pointerType!=="touch"&&!(vn(this.doc,n.idPath)&&!a)&&this.beginDrag(e,{kind:"move",path:n.idPath})}beginDrag(e,t){e.button!==0||this.simulating||(e.preventDefault(),this.drag={source:t,pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,active:!1})}onPointerMove(e){const t=this.drag;if(!t||e.pointerId!==t.pointerId)return;if(!t.active){if(Math.hypot(e.clientX-t.startX,e.clientY-t.startY)<5)return;t.active=!0,t.ghost=this.makeGhost(t.source),document.body.append(t.ghost),this.root.classList.add("dragging")}t.ghost.style.transform=`translate(${e.clientX+12}px, ${e.clientY+12}px)`,this.autoScroll(e.clientX,e.clientY);const n=this.svgPoint(e.clientX,e.clientY);t.target=n?this.dropTargetAt(n.x,n.y,t.source):void 0,this.showDropTarget(t.target)}onPointerUp(e){const t=this.drag;!t||e.pointerId!==t.pointerId||(t.active&&t.target?this.applyDrop(t.source,t.target):!t.active&&t.source.kind==="palette"?this.insertNearSelection(t.source.make()):!t.active&&t.source.kind==="sensor"&&this.insertSensor(t.source.text),this.endDrag())}endDrag(){var e,t;(t=(e=this.drag)==null?void 0:e.ghost)==null||t.remove(),this.drag=void 0,this.root.classList.remove("dragging"),this.showDropTarget(void 0)}makeGhost(e){const t=document.createElement("div");if(t.className="drag-ghost",e.kind==="palette"||e.kind==="sensor")t.textContent=e.label;else{const n=kt(this.doc,e.path);t.textContent=`${Gr(n.type)}: ${bl(n)[0]}`}return t}autoScroll(e,t){const n=this.canvasHost.getBoundingClientRect(),a=40,s=12;t>n.bottom-a&&tn.top-a&&(this.canvasHost.scrollTop-=s),e>n.right-a&&en.left-a&&(this.canvasHost.scrollLeft-=s)}dropTargetAt(e,t,n){var l;const a=((l=this.layout)==null?void 0:l.elements)??[],s=this.nodeAt(e,t);if(n.kind==="sensor")return!s||vn(this.doc,s.idPath)?void 0:Gc.includes(kt(this.doc,s.idPath).type)?{kind:"condition",path:s.idPath,frame:s.frame}:void 0;if(!s){const u=a[a.length-1];if(!u)return;const m=u.frame.y+u.frame.height;return t>m?n.kind==="move"&&n.path.length===1&&n.path[0]===a.length-1?void 0:{kind:"rootAppend",frame:{x:u.frame.x,y:m,width:u.frame.width,height:0}}:t=n.path.length&&n.path.every((u,m)=>r[m]===u)?void 0:vn(this.doc,r)?{kind:"replace",path:r,frame:s.frame}:{kind:t"]/g,e=>({"&":"&","<":"<",">":">",'"':"""})[e])}function od(i){if(!i)return[];for(const e of[...Zt.flatMap(t=>t.steps.flatMap(n=>n.blocks)),...x1.flatMap(t=>t.blocks)])if(!(e.kind!=="exercise"||e.exercise.id!==i))return e.exercise.tests.flatMap(t=>{const n=t.world?Za(t.world):void 0;return n?[n]:[]});return[]}let Bt,pl,fl;function ld(i){const e=i.dataset.tip;if(!e)return;Bt??(Bt=Object.assign(document.createElement("div"),{className:"tooltip",role:"tooltip"})),Bt.isConnected||document.body.append(Bt),Bt.textContent=e,Bt.hidden=!1;const t=i.getBoundingClientRect(),n=Bt.offsetWidth,a=Bt.offsetHeight,s=Math.min(Math.max(8,t.left+t.width/2-n/2),window.innerWidth-n-8),r=t.bottom+6+a{if(i.pointerType==="touch")return;const e=i.target.closest("[data-tip]");e!==fl&&(qr(),e&&(fl=e,pl=window.setTimeout(()=>ld(e),350)))}),document.addEventListener("focusin",i=>{const e=i.target.closest("[data-tip]");qr(),e!=null&&e.matches(":focus-visible")&&ld(e)});for(const i of["pointerdown","focusout","scroll","keydown"])document.addEventListener(i,qr,!0)}const xl="visustruct.reloadedAfterError";function Tf(){try{const i=Number(sessionStorage.getItem(xl));if(i&&Date.now()-i<3e4)return!1;sessionStorage.setItem(xl,String(Date.now()))}catch{return!1}return location.reload(),!0}function nJ(i){console.error(i);const e=(navigator.language||"").toLowerCase().startsWith("de"),t=document.createElement("div");t.className="startup-error";const n=document.createElement("h1");n.textContent=e?"VisuStruct konnte nicht starten":"VisuStruct could not start";const a=document.createElement("p");a.textContent=e?"Wahrscheinlich gibt es gerade eine neue Version. Lade die Seite neu. Hilft das nicht, drücke Strg+Umschalt+R (Mac: ⌘⇧R).":"There is probably a new version. Reload the page. If that does not help, press Ctrl+Shift+R (Mac: ⌘⇧R).";const s=document.createElement("button");s.textContent=e?"Neu laden":"Reload",s.addEventListener("click",()=>location.reload());const r=document.createElement("pre");r.textContent=String(i instanceof Error?i.message:i),t.append(n,a,s,r),(document.getElementById("app")??document.body).replaceWith(t)}window.addEventListener("vite:preloadError",i=>{Tf()&&i.preventDefault()});const iJ=f2();Promise.all([Ad(iJ,!1),Od(g2(),!1)]).then(()=>{_f(),tJ();const i=new URLSearchParams(location.search);i.has("visuobject")&&Zh();const e=document.getElementById("app");if(Dh()&&!i.has("visustruct")&&!i.has("visubot"))return Q(async()=>{const{ObjectApp:t}=await import("./objectApp-Dzw8stpM.js").then(n=>n.g);return{ObjectApp:t}},[],import.meta.url).then(({ObjectApp:t})=>new t(e));new XF(e)}).then(()=>{try{sessionStorage.removeItem(xl)}catch{}}).catch(i=>{/dynamically imported module|Importing a module script failed|error loading dynamically/i.test(String(i))&&Tf()||nJ(i)});export{Fn as C,tF as J,dx as L,Q as _,uJ as a,na as b,mF as c,kD as d,ID as e,Yn as f,$F as g,ee as i,lJ as m,sF as p,Gu as r,cr as s,p as t,wo as w}; +
`,t.addEventListener("click",n=>{const a=n.target.dataset.r;a===void 0&&n.target!==t||(t.remove(),e(a==="1"))}),document.body.append(t),t.querySelector('[data-r="0"]').focus()}):Promise.resolve(!0)}showMessage(e){this.statusLine.textContent=e,this.statusLine.classList.add("message"),setTimeout(()=>{this.statusLine.classList.remove("message"),this.updateStatus()},6e3)}loadXML(e,t,n){let a;try{a=Il(e)}catch(s){this.showMessage(p("web_err_unreadable_fmt",t,s.message));return}(this.dirty||this.tab.fileName||this.tab.exerciseId)&&this.addTab(),this.doc=a,this.tab.fileName=t.replace(/\.(strk|xml)$/i,".visustruct"),this.fileHandle=n&&/\.visustruct$/i.test(t)?n:void 0,this.resetHistory()}async open(e){const t=window;if(!t.showOpenFilePicker||this.inViewer)return e.click();try{const[n]=await t.showOpenFilePicker({types:Hc()}),a=await n.getFile();this.loadXML(await a.text(),a.name,n)}catch{}}async save(){var n,a;if(!this.downloads&&await this.saveToWorkspace())return;const e=new Blob([n1(this.doc)],{type:"application/xml"}),t=window;try{if(this.downloads){const s=this.fileName+".txt";await this.downloads.save({filename:s,data:e}),(n=this.tab).fileName??(n.fileName=this.fileName),this.dirty=!1,this.render(),this.showMessage(p("web_saved_txt_fmt",s));return}if(!this.fileHandle&&t.showSaveFilePicker&&!this.inViewer&&(this.fileHandle=await t.showSaveFilePicker({suggestedName:this.fileName,types:Hc()}),this.tab.fileName=this.fileHandle.name),this.fileHandle){const s=await this.fileHandle.createWritable();await s.write(e),await s.close()}else{const s=document.createElement("a");s.href=URL.createObjectURL(e),s.download=this.fileName,s.click(),setTimeout(()=>URL.revokeObjectURL(s.href),1e3)}(a=this.tab).fileName??(a.fileName=this.fileName),this.dirty=!1,this.render()}catch{}}async exportDiagram(e){if(e==="visustruct"){const s=Wc(this.doc,an(this.tab));return this.offerDownload(`${s}.visustruct`,new Blob([n1(this.doc)],{type:"application/xml"}))}const t=Ec(this.doc,this.metrics,this.measure);if(!t){this.showMessage(p(e==="print"?"err_diagram_too_small_print":"err_diagram_too_small_export"));return}const n=Wc(this.doc,an(this.tab)),a=Math.max(2,window.devicePixelRatio||1)*this.zoom;try{switch(e){case"svg":{t.svg.setAttribute("width",String(t.width*this.zoom)),t.svg.setAttribute("height",String(t.height*this.zoom)),await this.offerDownload(`${n}.svg`,new Blob([If(t)],{type:"image/svg+xml"}));break}case"png":{const s=await Nc(t,a);await this.offerDownload(`${n}.png`,await TF(s));break}case"pdf":{const s=await Nc(t,Math.max(a,3)),r=await PF(jF(s),s.width,s.height,t,zf(this.doc));await this.offerDownload(`${n}.pdf`,r);break}case"print":this.printDiagram(t);break}}catch(s){this.showMessage(p("web_export_failed_fmt",s instanceof Error?s.message:String(s)))}}printDiagram(e){const t=document.createElement("div");t.className="print-sheet",e.svg.removeAttribute("width"),e.svg.removeAttribute("height"),t.append(e.svg),document.body.append(t);const n=()=>t.remove();window.addEventListener("afterprint",n,{once:!0});try{window.print()}catch{n(),this.showMessage(`${p("err_print_unavailable")} ${p("web_print_hint")}`);return}setTimeout(n,6e4)}async offerDownload(e,t){try{if(this.downloads){try{await this.downloads.save({filename:e,data:t}),this.showMessage(p("web_saved_fmt",e))}catch{await this.downloads.save({filename:e+".txt",data:t}),this.showMessage(p("web_saved_txt_fmt",e+".txt"))}return}const n=document.createElement("a");n.href=URL.createObjectURL(t),n.download=e,n.click(),setTimeout(()=>URL.revokeObjectURL(n.href),1e3)}catch{this.showMessage(p("err_save_failed_fmt",e))}}setupFileDrop(){window.addEventListener("dragover",e=>{var t;(t=e.dataTransfer)!=null&&t.types.includes("Files")&&(e.preventDefault(),this.root.classList.add("file-drag"))}),window.addEventListener("dragleave",e=>{e.relatedTarget===null&&this.root.classList.remove("file-drag")}),window.addEventListener("drop",async e=>{var n;this.root.classList.remove("file-drag");const t=(n=e.dataTransfer)==null?void 0:n.files[0];t&&(e.preventDefault(),this.loadXML(await t.text(),t.name))})}onKeyDown(e){var a,s;const t=e.metaKey||e.ctrlKey,n=e.target instanceof HTMLTextAreaElement||e.target instanceof HTMLInputElement||((a=e.target)==null?void 0:a.isContentEditable)===!0;if(t&&e.key.toLowerCase()==="s")e.preventDefault(),this.save();else if(t&&e.key.toLowerCase()==="p")e.preventDefault(),this.simulating||this.exportDiagram("print");else if(t&&e.key.toLowerCase()==="o")e.preventDefault(),this.open(this.root.querySelector("input[type=file]"));else{if(n||this.simulating)return;t&&e.key.toLowerCase()==="z"?(e.preventDefault(),e.shiftKey?this.redo():this.undo()):t&&e.key.toLowerCase()==="c"&&!((s=getSelection())!=null&&s.toString())?this.copySelection()&&e.preventDefault():t&&e.key.toLowerCase()==="x"?(e.preventDefault(),this.cutSelection()):t&&e.key.toLowerCase()==="v"?(e.preventDefault(),this.paste()):t&&e.key.toLowerCase()==="y"?(e.preventDefault(),this.redo()):e.key==="Delete"||e.key==="Backspace"?(e.preventDefault(),this.deleteSelection()):e.key==="Escape"&&(this.drag?this.endDrag():(this.selected=void 0,this.render()))}}svgPoint(e,t){if(!this.svg)return;const n=this.svg.getBoundingClientRect(),a=e-n.left,s=t-n.top;if(!(a<0||s<0||a>n.width||s>n.height))return{x:a/this.zoom,y:s/this.zoom}}nodeAt(e,t){for(let n=this.flat.length-1;n>=0;n--){const a=this.flat[n].frame;if(e>=a.x&&e<=a.x+a.width&&t>=a.y&&t<=a.y+a.height)return this.flat[n]}}onCanvasPointerDown(e){if(this.simulating)return;const t=this.svgPoint(e.clientX,e.clientY);if(!t)return;document.activeElement instanceof HTMLElement&&document.activeElement.blur();const n=this.nodeAt(t.x,t.y),a=n&&this.selected&&eo(n.idPath,this.selected);this.selected=n==null?void 0:n.idPath,this.render(),n&&e.pointerType!=="touch"&&!(vn(this.doc,n.idPath)&&!a)&&this.beginDrag(e,{kind:"move",path:n.idPath})}beginDrag(e,t){e.button!==0||this.simulating||(e.preventDefault(),this.drag={source:t,pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,active:!1})}onPointerMove(e){const t=this.drag;if(!t||e.pointerId!==t.pointerId)return;if(!t.active){if(Math.hypot(e.clientX-t.startX,e.clientY-t.startY)<5)return;t.active=!0,t.ghost=this.makeGhost(t.source),document.body.append(t.ghost),this.root.classList.add("dragging")}t.ghost.style.transform=`translate(${e.clientX+12}px, ${e.clientY+12}px)`,this.autoScroll(e.clientX,e.clientY);const n=this.svgPoint(e.clientX,e.clientY);t.target=n?this.dropTargetAt(n.x,n.y,t.source):void 0,this.showDropTarget(t.target)}onPointerUp(e){const t=this.drag;!t||e.pointerId!==t.pointerId||(t.active&&t.target?this.applyDrop(t.source,t.target):!t.active&&t.source.kind==="palette"?this.insertNearSelection(t.source.make()):!t.active&&t.source.kind==="sensor"&&this.insertSensor(t.source.text),this.endDrag())}endDrag(){var e,t;(t=(e=this.drag)==null?void 0:e.ghost)==null||t.remove(),this.drag=void 0,this.root.classList.remove("dragging"),this.showDropTarget(void 0)}makeGhost(e){const t=document.createElement("div");if(t.className="drag-ghost",e.kind==="palette"||e.kind==="sensor")t.textContent=e.label;else{const n=kt(this.doc,e.path);t.textContent=`${Gr(n.type)}: ${bl(n)[0]}`}return t}autoScroll(e,t){const n=this.canvasHost.getBoundingClientRect(),a=40,s=12;t>n.bottom-a&&tn.top-a&&(this.canvasHost.scrollTop-=s),e>n.right-a&&en.left-a&&(this.canvasHost.scrollLeft-=s)}dropTargetAt(e,t,n){var l;const a=((l=this.layout)==null?void 0:l.elements)??[],s=this.nodeAt(e,t);if(n.kind==="sensor")return!s||vn(this.doc,s.idPath)?void 0:Gc.includes(kt(this.doc,s.idPath).type)?{kind:"condition",path:s.idPath,frame:s.frame}:void 0;if(!s){const u=a[a.length-1];if(!u)return;const m=u.frame.y+u.frame.height;return t>m?n.kind==="move"&&n.path.length===1&&n.path[0]===a.length-1?void 0:{kind:"rootAppend",frame:{x:u.frame.x,y:m,width:u.frame.width,height:0}}:t=n.path.length&&n.path.every((u,m)=>r[m]===u)?void 0:vn(this.doc,r)?{kind:"replace",path:r,frame:s.frame}:{kind:t"]/g,e=>({"&":"&","<":"<",">":">",'"':"""})[e])}function od(i){if(!i)return[];for(const e of[...Zt.flatMap(t=>t.steps.flatMap(n=>n.blocks)),...x1.flatMap(t=>t.blocks)])if(!(e.kind!=="exercise"||e.exercise.id!==i))return e.exercise.tests.flatMap(t=>{const n=t.world?Za(t.world):void 0;return n?[n]:[]});return[]}let Bt,pl,fl;function ld(i){const e=i.dataset.tip;if(!e)return;Bt??(Bt=Object.assign(document.createElement("div"),{className:"tooltip",role:"tooltip"})),Bt.isConnected||document.body.append(Bt),Bt.textContent=e,Bt.hidden=!1;const t=i.getBoundingClientRect(),n=Bt.offsetWidth,a=Bt.offsetHeight,s=Math.min(Math.max(8,t.left+t.width/2-n/2),window.innerWidth-n-8),r=t.bottom+6+a{if(i.pointerType==="touch")return;const e=i.target.closest("[data-tip]");e!==fl&&(qr(),e&&(fl=e,pl=window.setTimeout(()=>ld(e),350)))}),document.addEventListener("focusin",i=>{const e=i.target.closest("[data-tip]");qr(),e!=null&&e.matches(":focus-visible")&&ld(e)});for(const i of["pointerdown","focusout","scroll","keydown"])document.addEventListener(i,qr,!0)}const xl="visustruct.reloadedAfterError";function Tf(){try{const i=Number(sessionStorage.getItem(xl));if(i&&Date.now()-i<3e4)return!1;sessionStorage.setItem(xl,String(Date.now()))}catch{return!1}return location.reload(),!0}function nJ(i){console.error(i);const e=(navigator.language||"").toLowerCase().startsWith("de"),t=document.createElement("div");t.className="startup-error";const n=document.createElement("h1");n.textContent=e?"VisuStruct konnte nicht starten":"VisuStruct could not start";const a=document.createElement("p");a.textContent=e?"Wahrscheinlich gibt es gerade eine neue Version. Lade die Seite neu. Hilft das nicht, drücke Strg+Umschalt+R (Mac: ⌘⇧R).":"There is probably a new version. Reload the page. If that does not help, press Ctrl+Shift+R (Mac: ⌘⇧R).";const s=document.createElement("button");s.textContent=e?"Neu laden":"Reload",s.addEventListener("click",()=>location.reload());const r=document.createElement("pre");r.textContent=String(i instanceof Error?i.message:i),t.append(n,a,s,r),(document.getElementById("app")??document.body).replaceWith(t)}window.addEventListener("vite:preloadError",i=>{Tf()&&i.preventDefault()});const iJ=f2();Promise.all([Ad(iJ,!1),Od(g2(),!1)]).then(()=>{_f(),tJ();const i=new URLSearchParams(location.search);i.has("visuobject")&&Zh();const e=document.getElementById("app");if(Dh()&&!i.has("visustruct")&&!i.has("visubot"))return Q(async()=>{const{ObjectApp:t}=await import("./objectApp-Cl7eAHYv.js").then(n=>n.g);return{ObjectApp:t}},[],import.meta.url).then(({ObjectApp:t})=>new t(e));new XF(e)}).then(()=>{try{sessionStorage.removeItem(xl)}catch{}}).catch(i=>{/dynamically imported module|Importing a module script failed|error loading dynamically/i.test(String(i))&&Tf()||nJ(i)});export{Jn as C,tF as J,dx as L,Q as _,uJ as a,na as b,mF as c,kD as d,ID as e,Xn as f,$F as g,ee as i,lJ as m,sF as p,Gu as r,cr as s,p as t,wo as w}; diff --git a/website/app/assets/objectApp-Dzw8stpM.js b/website/app/assets/objectApp-Cl7eAHYv.js similarity index 99% rename from website/app/assets/objectApp-Dzw8stpM.js rename to website/app/assets/objectApp-Cl7eAHYv.js index 45e43081..e477648c 100644 --- a/website/app/assets/objectApp-Dzw8stpM.js +++ b/website/app/assets/objectApp-Cl7eAHYv.js @@ -1,5 +1,5 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./projectZip-hYmaJ0X8.js","./index-BZrdbqtU.js","./index-BbTafmqq.css"])))=>i.map(i=>d[i]); -var Ns=Object.defineProperty;var Os=(a,e,t)=>e in a?Ns(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var E=(a,e,t)=>Os(a,typeof e!="symbol"?e+"":e,t);import{t as d,i as ie,m as Ps,g as Is,w as Ds,J as Rs,c as Ye,p as Hs,a as Bs,s as Ws,_ as yt,b as wt,d as zs,r as $t,e as Vs,f as ct}from"./index-BZrdbqtU.js";function Us(a){const e=[];let t=0;for(;ti.map(i=>d[i]); +var Ns=Object.defineProperty;var Os=(a,e,t)=>e in a?Ns(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var E=(a,e,t)=>Os(a,typeof e!="symbol"?e+"":e,t);import{t as d,i as ie,m as Ps,g as Is,w as Ds,J as Rs,c as Ye,p as Hs,a as Bs,s as Ws,_ as yt,b as wt,d as zs,r as $t,e as Vs,f as ct}from"./index-D4MtCuvD.js";function Us(a){const e=[];let t=0;for(;te.text===","?", ":e.text).join("")}function fs(a){const e=[[]];let t=0;for(const s of a)s.text==="<"||s.text==="("||s.text==="["||s.text==="{"?t++:(s.text===">"||s.text===")"||s.text==="]"||s.text==="}")&&t--,s.text===","&&t===0?e.push([]):e[e.length-1].push(s);return e.filter(s=>s.length>0)}function ft(a){var t,s;const e=[];for(let i=0;i{const t=ft(e).filter(i=>i.text!=="final"),s=t[t.length-1];return{name:s!=null&&s.word?s.text:"",type:lt(t.slice(0,-1))}})}function xt(a,e,t,s){var x,L;const i=ft(a),n=new Set;let o=0;for(;o"));const r=i.slice(o);if(r.length===0||a.length===0)return[];const c=a[0].from,l=r.findIndex(S=>S.text==="("),h=r.findIndex(S=>S.text==="="),u=l>0&&(h<0||lS.text==="="),w=_<0?g:g.slice(0,_);let $=w.length-1;for(;$>0&&!w[$].word;)$--;if($<1)return[];const b=lt(w.slice(0,$)),m=f.length>1,y=[];return f.forEach((S,k)=>{var C;const j=S.findIndex(q=>q.text==="="),M=j<0?S:S.slice(0,j),A=k===0?w[$]:M.find(q=>q.word);if(!A)return;const R=M.filter(q=>q.from>A.from&&q.text==="[").length;y.push({kind:"field",name:A.text,type:b+"[]".repeat(R),params:[],visibility:_t(n,p),isStatic:n.has("static"),isAbstract:!1,from:c,to:s,headerFrom:c,headerTo:k===0?((C=M[M.length-1])==null?void 0:C.to)??A.to:A.to,shared:m,nameFrom:A.from,nameTo:A.to})}),y}function Ks(a,e,t){var n;let s=[],i=e;for(;ih.text==="="),c=ye(a,i,"{","}");if(r){s.push(...a.slice(i,c)),i=c;continue}const l=s.map(h=>h.text);l.includes("class")||l.includes("interface")||l.includes("enum")||s.length>0&&t.members.push(...xt(s,t.name,t.kind==="interface",((n=a[c-1])==null?void 0:n.to)??o.to)),s=[],i=c;continue}s.push(o),i++}return t.bodyEnd=a.length>0?a[a.length-1].to:0,i}function oe(a){var n,o,r,c;const e=Us(a),t=[];let s=[],i=0;for(;i$.text==="class"||$.text==="interface"),p=u>=0?h[u+1]:void 0;if(!(p!=null&&p.word)){i=ye(e,i,"{","}"),s=[];continue}let f=u;for(;f>0&&(ps.has(h[f-1].text)||h[f-1].text==="@");)f--;const g={name:p.text,kind:h[u].text==="interface"?"interface":"class",isAbstract:h.slice(f,u).some($=>$.text==="abstract"),interfaces:[],members:[],from:((n=s[s.indexOf(h[f])])==null?void 0:n.from)??h[f].from,to:0,headerFrom:((o=s[s.indexOf(h[f])])==null?void 0:o.from)??h[f].from,headerTo:h[h.length-1].to,nameFrom:p.from,nameTo:p.to,bodyEnd:0};let _=u+2;((r=h[_])==null?void 0:r.text)==="<"&&(_=ye(h,_,"<",">"));let w="";for(;_")-1:$.word&&w==="extends"&&g.kind==="class"?g.superclass??(g.superclass=$.text):$.word&&w&&g.interfaces.push($.text)}i=Ks(e,i+1,g),g.to=((c=e[i-1])==null?void 0:c.to)??a.length,t.push(g),s=[]}return t}function Fe(a){const e=/^([\p{L}_$][\p{L}\p{N}_$]*)(\[\])+$/u.exec(a);if(e)return{name:e[1],many:!0};const t=/^(?:ArrayList|LinkedList|List|Set|HashSet|TreeSet|Collection|Queue|Deque|ArrayDeque|Stack|Vector)<([\p{L}_$][\p{L}\p{N}_$]*)>$/u.exec(a);return t?{name:t[1],many:!0}:{name:a,many:!1}}function Xs(a){const e=new Set(a.map(s=>s.name)),t=[];for(const s of a){s.superclass&&e.has(s.superclass)&&t.push({kind:"extends",from:s.name,to:s.superclass});for(const i of s.interfaces)e.has(i)&&t.push({kind:s.kind==="interface"?"extends":"implements",from:s.name,to:i});for(const i of s.members){if(i.kind!=="field")continue;const n=Fe(i.type);e.has(n.name)&&t.push({kind:"association",from:s.name,to:n.name,role:i.name,multiplicity:n.many?"0..*":"1"})}}return t}function Ge(a){const e=a.params.map(t=>`${t.name}: ${t.type}`).join(", ");return a.kind==="field"?`${a.visibility} ${a.name}: ${a.type}`:a.kind==="constructor"?`${a.visibility} ${a.name}(${e})`:`${a.visibility} ${a.name}(${e}): ${a.type}`}const Ys=/^[\p{L}_$][\p{L}\p{N}_$]*$/u;function Ve(a){var c;let e=a.trim().replace(/;$/,"").trim();if(!e)return;let t;/^[+\-#~]/.test(e)&&(t=e[0],e=e.slice(1).trim());let s=!1;const i=e.split(/\s+/);for(;["static","public","private","protected"].includes(i[0]);){const l=i.shift();l==="static"?s=!0:t??(t=l==="public"?"+":l==="private"?"-":"#")}e=i.join(" ");const n=e.indexOf("(");if(n>=0){const l=e.lastIndexOf(")");if(lg.trim()).filter(Boolean).map(g=>{const _=/^([\p{L}_$][\p{L}\p{N}_$]*)\s*:\s*(.+)$/u.exec(g);if(_)return{name:_[1],type:_[2].replace(/\s+/g,"")};const w=/^(.+)\s+([\p{L}_$][\p{L}\p{N}_$]*)$/u.exec(g);return w?{name:w[2],type:w[1].replace(/\s+/g,"")}:{name:g,type:"int"}});return{kind:"method",visibility:t,name:h,type:u==null?void 0:u.replace(/\s+/g,""),params:f,isStatic:s}}const o=/^([\p{L}_$][\p{L}\p{N}_$]*)\s*(?::\s*(.+))?$/u.exec(e);if(o)return{kind:"field",visibility:t,name:o[1],type:(c=o[2])==null?void 0:c.replace(/\s+/g,""),params:[],isStatic:s};const r=/^(.+?)\s+([\p{L}_$][\p{L}\p{N}_$]*)$/u.exec(e);if(r)return{kind:"field",visibility:t,name:r[2],type:r[1].replace(/\s+/g,""),params:[],isStatic:s}}const Gs={"+":"public ","-":"private ","#":"protected ","~":""};function Zs(a){return/^(int|long|short|byte)$/.test(a)?"0":/^(double|float)$/.test(a)?"0.0":a==="boolean"?"false":a==="char"?"' '":"null"}function ms(a,e,t){const s=e.kind==="interface",i=s?"":Gs[a.visibility??(a.kind==="field"?"-":"+")],n=a.isStatic?"static ":"";if(a.kind==="field")return`${i}${n}${a.type??"int"} ${a.name}`;const o=a.params.map(r=>`${r.type} ${r.name}`).join(", ");return a.name===e.name?`${i}${a.name}(${o})`:`${i}${n}${t&&!s?"abstract ":""}${a.type??"void"} ${a.name}(${o})`}const Ue=(a,e)=>a.lastIndexOf(` `,e-1)+1;function mt(a,e,t){const s=Ue(a,e),i=a.slice(s,e);let n=t;for(;n
- ${v(d("web_about_version_fmt").replace("%@","0.12.2"))} + ${v(d("web_about_version_fmt").replace("%@","0.12.3"))}
@@ -308,7 +308,7 @@ public String toString() { `,"in"),this.consolePane().input.hidden=!0,t.vm.input(e),this.debugRun())}debugError(e){var o;const t=e.pos?String(e.pos.line+1):"",s=((o=e.pos)==null?void 0:o.file.split("/").pop())??"",i=e.detail.replace(/^expected:/,""),n={syntax:"web_visuobject_dbg_err_syntax",symbol:"web_visuobject_dbg_err_symbol",unsupported:"web_visuobject_dbg_err_unsupported",nomain:"web_visuobject_no_main",type:"web_visuobject_dbg_err_type",import:"web_visuobject_dbg_err_import"}[e.code];e.pos&&this.showLine(e.pos.file,e.pos.line),this.stopDebug(),this.debugStatus(d(n,s,t,i),!0)}showDebugButtons(){const e=this.dbg,t=(e==null?void 0:e.state)==="paused";for(const s of this.shell.querySelectorAll("[data-dbg]"))s.disabled=!e||(s.dataset.dbg==="pause"?e.state!=="running":!t)}showLine(e,t){this.project.files.some(s=>s.path===e)&&e!==this.active&&this.openFile(e),this.editor.setMarks({placeholders:[],problems:[],current:t},!0)}showDebugState(){const e=this.dbg;if(!e)return;e.frames=e.vm.stack();const t=e.vm.heap(),s=e.frames[e.frame];s&&this.showLine(s.pos.file,s.pos.line);const i=e.values.size===0&&e.vars.size===0,n=new Set,o=new Map;for(const h of t)for(const u of h.fields){const p=`dbg${h.id}.${u.name}`;o.set(p,u.value),!i&&e.values.get(p)!==u.value&&n.add(p)}e.values=o;const r=new Set,c=new Map;e.frames.forEach((h,u)=>{for(const p of h.vars){const f=`${e.frames.length-u}|${h.title}|${p.name}`;c.set(f,p.value),!i&&e.vars.get(f)!==p.value&&r.add(`${h.title}|${p.name}`)}}),e.vars=c;const l={objects:this.liveObjects(t),changed:n,frames:e.frames,frame:e.frame,changedVars:r,onFrame:h=>{e.frame=h,l.frame=h;const u=e.frames[h];u&&this.showLine(u.pos.file,u.pos.line),this.objectDiagram.renderInspector()},move:(h,u)=>e.places.set(h,u)};this.objectDiagram.live=l,this.sequence=e.vm.sequence(),this.diagramMode==="object"&&this.objectDiagram.render(),this.diagramMode==="sequence"&&this.renderSequence()}renderSequence(){var n,o,r;const e=this.shell.querySelector(".vo-seqcanvas"),t=e.querySelector(".vo-seq"),s=e.querySelector(".vo-empty"),i=this.sequence;if(s.hidden=!!i&&i.events.length>0,s.textContent=d(i?"web_visuobject_seq_no_calls":"web_visuobject_seq_empty"),!i||!i.events.length)t.innerHTML="",t.setAttribute("width","0");else{const c=((n=this.dbg)==null?void 0:n.state)==="paused"||((o=this.dbg)==null?void 0:o.state)==="input",{svg:l,width:h,height:u}=Li(i,c?i.events.length-1:void 0);t.innerHTML=l+(i.truncated?`${v(d("web_visuobject_seq_truncated"))}`:""),t.setAttribute("width",String(h)),t.setAttribute("height",String(u)),c&&((r=t.querySelector(".vo-seq-msg.current"))==null||r.scrollIntoView({block:"nearest",inline:"nearest"}))}this.renderSequenceInspector()}renderSequenceInspector(){if(this.objectDiagram.live)return this.objectDiagram.renderInspector();this.inspector.innerHTML=`

${v(d("web_visuobject_seq_hint"))}

`}liveObjects(e){const t=this.dbg,s=this.project.objects??[],i=c=>40+c.fields.length*20,n=[],o=[],r=[];for(const c of e){const l=`dbg${c.id}`,h=t.places.get(l)??s.find(u=>u.name===c.name&&u.cls===c.cls);if(!h){r.push(c);continue}t.places.set(l,{x:h.x,y:h.y}),n.push({x:h.x,y:h.y,w:260,h:i(c)})}for(const c of r){const l=i(c);let h={x:24,y:24};e:for(let u=24;u<6e3;u+=30)for(let p=24;p<=24+3*320;p+=320)if(n.every(f=>p+260+30<=f.x||f.x+f.w+30<=p||u+l+30<=f.y||f.y+f.h+30<=u)){h={x:p,y:u};break e}t.places.set(`dbg${c.id}`,h),n.push({...h,w:260,h:l})}for(const c of e){const l=`dbg${c.id}`;o.push({id:l,name:c.name,cls:c.cls,...t.places.get(l),values:Object.fromEntries(c.fields.map(h=>[h.name,h.value]))})}return o}stopDebug(e,t=!1){const s=this.dbg;s&&clearTimeout(s.timer),this.dbg=void 0,s&&(this.sequence=s.vm.sequence()),this.objectDiagram.live=void 0,this.consolePane().input.hidden=!0,this.shell.querySelector(".vo-dbg-controls").hidden=!0,this.shell.querySelector("[data-action=stop]").disabled=!0,this.shell.querySelector("[data-action=run]").disabled=!1,t||this.editor.setMarks({placeholders:[],problems:[]},!1),e&&this.debugStatus(d(e),t),this.diagramMode==="object"&&this.objectDiagram.render(),this.diagramMode==="sequence"&&this.renderSequence()}chooseWorld(e){e!=="object"&&(Ws(e),location.href=`${location.pathname}?${e==="on"?"visubot":"visustruct"}${location.hash}`)}get activeFile(){return this.project.files.find(e=>e.path===this.active)}showActive(){const e=this.activeFile;this.editor.setText((e==null?void 0:e.text)??""),this.editor.setBreakpoints(e?this.breakpoints.get(e.path)??[]:[]),this.editor.setReadOnly(!e),e&&!this.openTabs.includes(e.path)&&this.openTabs.push(e.path),this.renderTabs(),J(ot,this.active??"")}renderTabs(){if(this.openTabs=this.openTabs.filter(e=>this.project.files.some(t=>t.path===e)),J(rs,JSON.stringify(this.openTabs)),this.openTabs.length===0){this.tabs.innerHTML=`${v(d("web_visuobject_no_file"))}`;return}this.tabs.innerHTML=this.openTabs.map(e=>{const t=e===this.active,s=this.isDirty(e);return`
-
`}).join("")}onTabClick(e){var i;const t=e.target,s=(i=t.closest("[data-tab]"))==null?void 0:i.dataset.tab;if(s){if(t.closest("[data-close]"))return this.closeTab(s);this.treeSelection=`file:${s}`,this.openFile(s)}}closeTab(e){const t=this.openTabs.indexOf(e);t<0||(this.openTabs.splice(t,1),e===this.active?(this.active=this.openTabs[Math.min(t,this.openTabs.length-1)],this.lastTyping=0,this.showActive(),this.refresh()):this.renderTabs())}snapshot(){return JSON.stringify({project:this.project,active:this.active})}remember(){this.history.push(this.snapshot()),this.history.length>yn&&this.history.shift(),this.future=[]}setProject(e,t=this.active){var s;this.remember(),this.lastTyping=0,this.project=e,this.active=e.files.some(i=>i.path===t)?t:(s=e.files[0])==null?void 0:s.path,this.showActive(),this.refresh()}openFile(e){if(e===this.active)return;this.active=e,this.lastTyping=0,this.showActive();const t=D(e);this.currentPackage=t,this.open.set(`pkg:${t}`,!0),this.refresh()}typed(){const e=this.activeFile;if(!e)return;const t=Date.now();t-this.lastTyping>1500&&this.remember(),this.lastTyping=t,this.project=$e(this.project,e.path,this.editor.text),this.saveBreakpoints(),this.dbg&&this.stopDebug("web_visuobject_dbg_code_changed"),this.refresh(),clearTimeout(this.renameTimer),this.renameTimer=window.setTimeout(()=>this.syncFileName(),700)}syncFileName(){var c;const e=this.activeFile;if(!e||this.editing)return;const t=Q(e.path).replace(/\.java$/i,""),s=this.classes.filter(l=>l.path===e.path);if(s.length===0||s.some(l=>l.name===t))return;const i=((c=/\bpublic\s+(?:abstract\s+|final\s+)*(?:class|interface|enum)\s+(\w+)/.exec(e.text))==null?void 0:c[1])??s[0].name;if(!pe.test(i)||s.filter(l=>l.name===i).length!==1)return;const n=le(D(e.path),`${i}.java`);if(this.project.files.some(l=>l.path===n))return;let o=Oe(this.project,e.path,n);const r=this.positions.get(t);r&&!this.positions.has(i)&&this.positions.set(i,r);for(const l of Object.keys(o.uml??{}))l.startsWith(`${t}.`)&&(o={...o,uml:ke(o.uml,l,i+l.slice(t.length))});this.openTabs=this.openTabs.map(l=>l===e.path?n:l),this.treeSelection===`file:${e.path}`&&(this.treeSelection=`file:${n}`),this.isOpen(`file:${e.path}`)&&this.open.set(`file:${n}`,!0),this.project=o,this.active=n,J(ot,n),this.savePositions(),this.refresh()}undo(e){const t=e?this.future:this.history,s=e?this.history:this.future,i=t.pop();if(i===void 0)return;s.push(this.snapshot());const n=JSON.parse(i);this.project=n.project,this.active=n.active,this.lastTyping=0,this.showActive(),this.refresh()}refresh(){J(ns,Pe(this.project)),this.renderTabs(),this.classes=Mt(this.project),this.selection&&!this.findClass(this.selection.cls)&&(this.selection=void 0),this.relSelection&&!this.findRelation(this.relSelection)&&!this.findDependency(this.relSelection)&&(this.relSelection=void 0),this.editing||(this.render(),this.renderTree())}ownTypesAt(e){const t=this.activeFile;if(!t)return;const s=this.editor.view.state.doc.toString(),i=X(D(t.path)),n=oe(s).map(l=>({...l,pkg:i})),o=new Set(n.map(l=>l.name)),r=n.find(l=>l.headerFrom<=e&&e<=l.bodyEnd),c=ct()==="de"?"de":ct()==="pt-PT"?"pt":"en";return Bi([...n,...this.classes.filter(l=>l.path!==t.path&&!o.has(l.name))],{cls:r==null?void 0:r.name,pkg:i},c)}findClass(e){return this.classes.find(t=>t.name===e)}caretMoved(){var n,o;const e=this.editor.caret,t=this.classes.find(r=>r.path===this.active&&e>=r.from&&e<=r.to),s=t==null?void 0:t.members.findIndex(r=>e>=r.from&&e<=r.to),i=t?{cls:t.name,member:s!==void 0&&s>=0?s:void 0}:void 0;(i==null?void 0:i.cls)===((n=this.selection)==null?void 0:n.cls)&&(i==null?void 0:i.member)===((o=this.selection)==null?void 0:o.member)||(this.selection=i,this.editing||(this.render(),this.renderTree()))}showInCode(e,t){e.path!==this.active&&(this.active=e.path,this.lastTyping=0,this.showActive());const s=this.editor.view,[i,n]=t?[t.headerFrom,t.headerTo]:[e.nameFrom,e.nameTo],o=Math.min(n,s.state.doc.length);s.dispatch({selection:{anchor:Math.min(i,o),head:o},scrollIntoView:!0})}message(e,t=!1){this.status.textContent=e,this.status.classList.toggle("hint",t)}openFiles(){const e=document.createElement("input");e.type="file",e.multiple=!0,e.accept=".zip,.java,.visuobject,application/zip,text/plain",e.addEventListener("change",()=>void this.readFiles([...e.files??[]])),e.click()}async readFiles(e){var t;if(e.length!==0)try{const s=e.find(r=>/\.zip$/i.test(r.name));if(s){const{projectFromZip:r}=await yt(async()=>{const{projectFromZip:l}=await import("./projectZip-hYmaJ0X8.js");return{projectFromZip:l}},__vite__mapDeps([0,1,2]),import.meta.url),c=r(new Uint8Array(await s.arrayBuffer()),s.name.replace(/\.zip$/i,""));await this.newProject(c);return}const i=e.find(r=>/\.visuobject$/i.test(r.name));if(i){const r=At(await i.text());if(!r)throw new Error("format");await this.newProject(r);return}const n=Tt(this.project.name,await Promise.all(e.map(async r=>({name:r.name,text:await r.text()}))));let o=this.project;for(const r of n.files)o=et(o,r.path,r.text);this.setProject(o,(t=n.files[0])==null?void 0:t.path)}catch{this.message(d("web_visuobject_open_failed"))}}async save(){this.workspace?await this.writeCurrent():await this.downloadZip()}async downloadZip(){const{projectToZip:e}=await yt(async()=>{const{projectToZip:s}=await import("./projectZip-hYmaJ0X8.js");return{projectToZip:s}},__vite__mapDeps([0,1,2]),import.meta.url),t=e(this.project);$n(`${this.project.name||"Projekt"}.zip`,t.slice().buffer,"application/zip")}isDirty(e){var t;return!this.workspace||this.saved===void 0?!1:e===void 0?this.saved!==Pe(this.project):this.savedFiles.get(e)!==((t=this.project.files.find(s=>s.path===e))==null?void 0:t.text)}markSaved(){this.saved=Pe(this.project),this.savedFiles=new Map(this.project.files.map(e=>[e.path,e.text]))}async restoreWorkspace(){if(!wt())return;const e=await zs(ds);if(e!=null&&e.ready){const t=await $t(e.handle);if(t)return this.useWorkspace(t.root,!0)}this.pendingFolder=e==null?void 0:e.handle,this.renderWorkspace()}async useWorkspace(e,t=!1){var s;this.workspace=e,this.pendingFolder=void 0,J(rt,"0");try{this.projects=await ss(e);const i=se(We),n=this.project;if(t&&i&&this.projects.includes(i)){const o={active:this.active,tabs:[...this.openTabs],positions:new Map(this.positions)};await this.loadProject(i),this.positions=o.positions,this.savePositions(),Pe(n)!==this.saved&&(this.project=n),this.openTabs=o.tabs.filter(r=>this.project.files.some(c=>c.path===r)),this.active=this.project.files.some(r=>r.path===o.active)?o.active:(s=this.project.files[0])==null?void 0:s.path,this.showActive(),this.refresh()}else!this.projects.some(o=>o.toLowerCase()===ge(n.name).toLowerCase())&&n.files.length?(this.folder=ge(n.name),await this.writeCurrent(!1)):this.projects.length?await this.loadProject(this.projects.includes(i??"")?i:this.projects[0]):(this.folder=ge(n.name),await this.writeCurrent(!1))}catch(i){this.message(d("web_visuobject_ws_failed",String((i==null?void 0:i.message)??i)))}this.renderWorkspace(),this.refresh()}async loadProject(e){var i;const{project:t,positions:s}=await fn(this.workspace,e);this.folder=e,this.project=t,this.markSaved(),this.message(""),this.history=[],this.future=[],this.lastTyping=0,this.selection=void 0,this.relSelection=void 0,this.treeSelection=void 0,this.currentPackage=void 0,this.positions=new Map(Object.entries(s)),this.savePositions(),this.openTabs=[],this.active=(i=t.files[0])==null?void 0:i.path,J(We,e),this.showActive(),this.refresh()}async writeCurrent(e=!0){const t=this.workspace;if(!t)return!1;const s=ge(this.project.name),i=this.folder,n=new Set(this.classes.map(r=>r.name)),o=Object.fromEntries([...this.positions].filter(([r])=>n.has(r)));if(s!==i&&this.projects.some(r=>r!==i&&r.toLowerCase()===s.toLowerCase()))return this.message(d("web_visuobject_ws_taken",this.project.name)),!1;try{return await vn(t,s,this.project,o),i&&i!==s&&this.projects.includes(i)&&await t.remove(i),this.folder=s,this.projects=await ss(t),J(We,s),this.markSaved(),e&&this.message(d("web_visuobject_ws_saved",t.name,s),!0),this.refresh(),!0}catch(r){return this.message(d("web_visuobject_ws_failed",String((r==null?void 0:r.message)??r))),!1}}async switchProject(e){if(!(!this.workspace||e===this.folder)&&!(this.isDirty()&&!await this.writeCurrent(!1)))try{await this.loadProject(e)}catch(t){this.message(d("web_visuobject_ws_failed",String((t==null?void 0:t.message)??t)))}}async newProject(e,t,s=!1){var n,o;if(!this.workspace){this.setProject(e,t??((n=e.files[0])==null?void 0:n.path)),e.files.length===0&&!s&&this.editProjectName();return}if(this.isDirty()&&!await this.writeCurrent(!1))return;const i=is(ge(e.name),this.projects);this.project={...e,name:i},this.folder=i,this.history=[],this.future=[],this.openTabs=[],this.positions.clear(),this.savePositions(),this.active=e.files.some(r=>r.path===t)?t:(o=e.files[0])==null?void 0:o.path,this.showActive(),this.refresh(),await this.writeCurrent(!1)&&(this.message(d("web_visuobject_ws_created",i),!0),e.files.length===0&&!s&&this.editProjectName())}get currentPlace(){const e=this.currentPackage??(this.active?D(this.active):ce(this.project)[0]??"");return{root:U(e),pkg:X(e)}}async newFromWizard(e){var u;const t=this.currentPlace,s=(p,f)=>{let g=p;for(let _=2;f(g);_++)g=p+_;return g},i=await Qi(e,{roots:ue(this.project),packagesIn:p=>ce(this.project,p).map(X),classes:this.classes,root:t.root,pkg:t.pkg,suggest:p=>p==="project"?is(d("web_visuobject_project_name"),this.workspace?[...this.projects,this.folder??""]:[]):p==="folder"?s("test",f=>ue(this.project).includes(f)):p==="package"?s(d("web_visuobject_new_package_name"),f=>ce(this.project).includes(re(t.root,f))):this.uniqueClassName(d(p==="class"?"web_visuobject_new_class_name":"web_visuobject_new_interface_name")),check:(p,f,g,_)=>{if(!f)return d("web_visuobject_new_name_missing");if(p==="project")return this.workspace&&this.projects.some(w=>w!==this.folder&&w.toLowerCase()===ge(f).toLowerCase())?d("web_visuobject_ws_taken",f):void 0;if(p==="folder")return!Je(f)||ue(this.project).includes(f)?d("web_visuobject_bad_folder",f):void 0;if(p==="package")return!Et(f)||ce(this.project).includes(re(g,f))?d("web_visuobject_bad_package",f):void 0;if(!pe.test(f))return d("web_visuobject_bad_name",f);if(this.findClass(f)||this.project.files.some(w=>w.path===le(re(g,_),`${f}.java`)))return d("web_visuobject_new_exists",f);if(f.charAt(0)!==f.charAt(0).toUpperCase())return d("web_visuobject_new_upper")}});if(!i)return;const{name:n,root:o,pkg:r}=i;if(e==="project")return this.newProject({name:n,files:[],packages:[]},void 0,!0);if(this.message(""),e==="folder")return this.currentPackage=re(n,""),this.treeSelection=`root:${n}`,this.open.set(`root:${n}`,!0),this.setProject(ui(this.project,n));if(e==="package"){const p=re(o,n);return this.currentPackage=p,this.treeSelection=`pkg:${p}`,this.open.set(`root:${o}`,!0),this.setProject(hi(this.project,p))}const c=re(o,r),l=le(c,`${n}.java`);this.currentPackage=c,this.selection={cls:n},this.open.set(`root:${o}`,!0),this.open.set(`pkg:${c}`,!0),this.setProject(et(this.project,l,this.sectioned(Gi(i.options),n)),l);const h=this.findClass(n);h&&this.showInCode(h),(u=this.canvas.querySelector(`.uml-class[data-class="${CSS.escape(n)}"]`))==null||u.scrollIntoView({block:"nearest",inline:"nearest"})}editProjectName(){this.treeSelection="project",this.renderTree(),this.startEditing(this.tree.querySelector('[data-node="project"] > .vo-row .vo-label'))}renderWorkspace(){const e=this.wsBox;e.hidden=!wt();const t=this.shell.querySelector("[data-action=save]");if(t.dataset.tip=d(this.workspace?"web_visuobject_save_ws_tip":"web_visuobject_save_tip"),e.hidden)return;const s=(i,n,o="text-button",r)=>``;this.workspace?(e.className="vo-ws",e.innerHTML=`${v(this.workspace.name)} + `}).join("")}onTabClick(e){var i;const t=e.target,s=(i=t.closest("[data-tab]"))==null?void 0:i.dataset.tab;if(s){if(t.closest("[data-close]"))return this.closeTab(s);this.treeSelection=`file:${s}`,this.openFile(s)}}closeTab(e){const t=this.openTabs.indexOf(e);t<0||(this.openTabs.splice(t,1),e===this.active?(this.active=this.openTabs[Math.min(t,this.openTabs.length-1)],this.lastTyping=0,this.showActive(),this.refresh()):this.renderTabs())}snapshot(){return JSON.stringify({project:this.project,active:this.active})}remember(){this.history.push(this.snapshot()),this.history.length>yn&&this.history.shift(),this.future=[]}setProject(e,t=this.active){var s;this.remember(),this.lastTyping=0,this.project=e,this.active=e.files.some(i=>i.path===t)?t:(s=e.files[0])==null?void 0:s.path,this.showActive(),this.refresh()}openFile(e){if(e===this.active)return;this.active=e,this.lastTyping=0,this.showActive();const t=D(e);this.currentPackage=t,this.open.set(`pkg:${t}`,!0),this.refresh()}typed(){const e=this.activeFile;if(!e)return;const t=Date.now();t-this.lastTyping>1500&&this.remember(),this.lastTyping=t,this.project=$e(this.project,e.path,this.editor.text),this.saveBreakpoints(),this.dbg&&this.stopDebug("web_visuobject_dbg_code_changed"),this.refresh(),clearTimeout(this.renameTimer),this.renameTimer=window.setTimeout(()=>this.syncFileName(),700)}syncFileName(){var c;const e=this.activeFile;if(!e||this.editing)return;const t=Q(e.path).replace(/\.java$/i,""),s=this.classes.filter(l=>l.path===e.path);if(s.length===0||s.some(l=>l.name===t))return;const i=((c=/\bpublic\s+(?:abstract\s+|final\s+)*(?:class|interface|enum)\s+(\w+)/.exec(e.text))==null?void 0:c[1])??s[0].name;if(!pe.test(i)||s.filter(l=>l.name===i).length!==1)return;const n=le(D(e.path),`${i}.java`);if(this.project.files.some(l=>l.path===n))return;let o=Oe(this.project,e.path,n);const r=this.positions.get(t);r&&!this.positions.has(i)&&this.positions.set(i,r);for(const l of Object.keys(o.uml??{}))l.startsWith(`${t}.`)&&(o={...o,uml:ke(o.uml,l,i+l.slice(t.length))});this.openTabs=this.openTabs.map(l=>l===e.path?n:l),this.treeSelection===`file:${e.path}`&&(this.treeSelection=`file:${n}`),this.isOpen(`file:${e.path}`)&&this.open.set(`file:${n}`,!0),this.project=o,this.active=n,J(ot,n),this.savePositions(),this.refresh()}undo(e){const t=e?this.future:this.history,s=e?this.history:this.future,i=t.pop();if(i===void 0)return;s.push(this.snapshot());const n=JSON.parse(i);this.project=n.project,this.active=n.active,this.lastTyping=0,this.showActive(),this.refresh()}refresh(){J(ns,Pe(this.project)),this.renderTabs(),this.classes=Mt(this.project),this.selection&&!this.findClass(this.selection.cls)&&(this.selection=void 0),this.relSelection&&!this.findRelation(this.relSelection)&&!this.findDependency(this.relSelection)&&(this.relSelection=void 0),this.editing||(this.render(),this.renderTree())}ownTypesAt(e){const t=this.activeFile;if(!t)return;const s=this.editor.view.state.doc.toString(),i=X(D(t.path)),n=oe(s).map(l=>({...l,pkg:i})),o=new Set(n.map(l=>l.name)),r=n.find(l=>l.headerFrom<=e&&e<=l.bodyEnd),c=ct()==="de"?"de":ct()==="pt-PT"?"pt":"en";return Bi([...n,...this.classes.filter(l=>l.path!==t.path&&!o.has(l.name))],{cls:r==null?void 0:r.name,pkg:i},c)}findClass(e){return this.classes.find(t=>t.name===e)}caretMoved(){var n,o;const e=this.editor.caret,t=this.classes.find(r=>r.path===this.active&&e>=r.from&&e<=r.to),s=t==null?void 0:t.members.findIndex(r=>e>=r.from&&e<=r.to),i=t?{cls:t.name,member:s!==void 0&&s>=0?s:void 0}:void 0;(i==null?void 0:i.cls)===((n=this.selection)==null?void 0:n.cls)&&(i==null?void 0:i.member)===((o=this.selection)==null?void 0:o.member)||(this.selection=i,this.editing||(this.render(),this.renderTree()))}showInCode(e,t){e.path!==this.active&&(this.active=e.path,this.lastTyping=0,this.showActive());const s=this.editor.view,[i,n]=t?[t.headerFrom,t.headerTo]:[e.nameFrom,e.nameTo],o=Math.min(n,s.state.doc.length);s.dispatch({selection:{anchor:Math.min(i,o),head:o},scrollIntoView:!0})}message(e,t=!1){this.status.textContent=e,this.status.classList.toggle("hint",t)}openFiles(){const e=document.createElement("input");e.type="file",e.multiple=!0,e.accept=".zip,.java,.visuobject,application/zip,text/plain",e.addEventListener("change",()=>void this.readFiles([...e.files??[]])),e.click()}async readFiles(e){var t;if(e.length!==0)try{const s=e.find(r=>/\.zip$/i.test(r.name));if(s){const{projectFromZip:r}=await yt(async()=>{const{projectFromZip:l}=await import("./projectZip-C0Wt4zQg.js");return{projectFromZip:l}},__vite__mapDeps([0,1,2]),import.meta.url),c=r(new Uint8Array(await s.arrayBuffer()),s.name.replace(/\.zip$/i,""));await this.newProject(c);return}const i=e.find(r=>/\.visuobject$/i.test(r.name));if(i){const r=At(await i.text());if(!r)throw new Error("format");await this.newProject(r);return}const n=Tt(this.project.name,await Promise.all(e.map(async r=>({name:r.name,text:await r.text()}))));let o=this.project;for(const r of n.files)o=et(o,r.path,r.text);this.setProject(o,(t=n.files[0])==null?void 0:t.path)}catch{this.message(d("web_visuobject_open_failed"))}}async save(){this.workspace?await this.writeCurrent():await this.downloadZip()}async downloadZip(){const{projectToZip:e}=await yt(async()=>{const{projectToZip:s}=await import("./projectZip-C0Wt4zQg.js");return{projectToZip:s}},__vite__mapDeps([0,1,2]),import.meta.url),t=e(this.project);$n(`${this.project.name||"Projekt"}.zip`,t.slice().buffer,"application/zip")}isDirty(e){var t;return!this.workspace||this.saved===void 0?!1:e===void 0?this.saved!==Pe(this.project):this.savedFiles.get(e)!==((t=this.project.files.find(s=>s.path===e))==null?void 0:t.text)}markSaved(){this.saved=Pe(this.project),this.savedFiles=new Map(this.project.files.map(e=>[e.path,e.text]))}async restoreWorkspace(){if(!wt())return;const e=await zs(ds);if(e!=null&&e.ready){const t=await $t(e.handle);if(t)return this.useWorkspace(t.root,!0)}this.pendingFolder=e==null?void 0:e.handle,this.renderWorkspace()}async useWorkspace(e,t=!1){var s;this.workspace=e,this.pendingFolder=void 0,J(rt,"0");try{this.projects=await ss(e);const i=se(We),n=this.project;if(t&&i&&this.projects.includes(i)){const o={active:this.active,tabs:[...this.openTabs],positions:new Map(this.positions)};await this.loadProject(i),this.positions=o.positions,this.savePositions(),Pe(n)!==this.saved&&(this.project=n),this.openTabs=o.tabs.filter(r=>this.project.files.some(c=>c.path===r)),this.active=this.project.files.some(r=>r.path===o.active)?o.active:(s=this.project.files[0])==null?void 0:s.path,this.showActive(),this.refresh()}else!this.projects.some(o=>o.toLowerCase()===ge(n.name).toLowerCase())&&n.files.length?(this.folder=ge(n.name),await this.writeCurrent(!1)):this.projects.length?await this.loadProject(this.projects.includes(i??"")?i:this.projects[0]):(this.folder=ge(n.name),await this.writeCurrent(!1))}catch(i){this.message(d("web_visuobject_ws_failed",String((i==null?void 0:i.message)??i)))}this.renderWorkspace(),this.refresh()}async loadProject(e){var i;const{project:t,positions:s}=await fn(this.workspace,e);this.folder=e,this.project=t,this.markSaved(),this.message(""),this.history=[],this.future=[],this.lastTyping=0,this.selection=void 0,this.relSelection=void 0,this.treeSelection=void 0,this.currentPackage=void 0,this.positions=new Map(Object.entries(s)),this.savePositions(),this.openTabs=[],this.active=(i=t.files[0])==null?void 0:i.path,J(We,e),this.showActive(),this.refresh()}async writeCurrent(e=!0){const t=this.workspace;if(!t)return!1;const s=ge(this.project.name),i=this.folder,n=new Set(this.classes.map(r=>r.name)),o=Object.fromEntries([...this.positions].filter(([r])=>n.has(r)));if(s!==i&&this.projects.some(r=>r!==i&&r.toLowerCase()===s.toLowerCase()))return this.message(d("web_visuobject_ws_taken",this.project.name)),!1;try{return await vn(t,s,this.project,o),i&&i!==s&&this.projects.includes(i)&&await t.remove(i),this.folder=s,this.projects=await ss(t),J(We,s),this.markSaved(),e&&this.message(d("web_visuobject_ws_saved",t.name,s),!0),this.refresh(),!0}catch(r){return this.message(d("web_visuobject_ws_failed",String((r==null?void 0:r.message)??r))),!1}}async switchProject(e){if(!(!this.workspace||e===this.folder)&&!(this.isDirty()&&!await this.writeCurrent(!1)))try{await this.loadProject(e)}catch(t){this.message(d("web_visuobject_ws_failed",String((t==null?void 0:t.message)??t)))}}async newProject(e,t,s=!1){var n,o;if(!this.workspace){this.setProject(e,t??((n=e.files[0])==null?void 0:n.path)),e.files.length===0&&!s&&this.editProjectName();return}if(this.isDirty()&&!await this.writeCurrent(!1))return;const i=is(ge(e.name),this.projects);this.project={...e,name:i},this.folder=i,this.history=[],this.future=[],this.openTabs=[],this.positions.clear(),this.savePositions(),this.active=e.files.some(r=>r.path===t)?t:(o=e.files[0])==null?void 0:o.path,this.showActive(),this.refresh(),await this.writeCurrent(!1)&&(this.message(d("web_visuobject_ws_created",i),!0),e.files.length===0&&!s&&this.editProjectName())}get currentPlace(){const e=this.currentPackage??(this.active?D(this.active):ce(this.project)[0]??"");return{root:U(e),pkg:X(e)}}async newFromWizard(e){var u;const t=this.currentPlace,s=(p,f)=>{let g=p;for(let _=2;f(g);_++)g=p+_;return g},i=await Qi(e,{roots:ue(this.project),packagesIn:p=>ce(this.project,p).map(X),classes:this.classes,root:t.root,pkg:t.pkg,suggest:p=>p==="project"?is(d("web_visuobject_project_name"),this.workspace?[...this.projects,this.folder??""]:[]):p==="folder"?s("test",f=>ue(this.project).includes(f)):p==="package"?s(d("web_visuobject_new_package_name"),f=>ce(this.project).includes(re(t.root,f))):this.uniqueClassName(d(p==="class"?"web_visuobject_new_class_name":"web_visuobject_new_interface_name")),check:(p,f,g,_)=>{if(!f)return d("web_visuobject_new_name_missing");if(p==="project")return this.workspace&&this.projects.some(w=>w!==this.folder&&w.toLowerCase()===ge(f).toLowerCase())?d("web_visuobject_ws_taken",f):void 0;if(p==="folder")return!Je(f)||ue(this.project).includes(f)?d("web_visuobject_bad_folder",f):void 0;if(p==="package")return!Et(f)||ce(this.project).includes(re(g,f))?d("web_visuobject_bad_package",f):void 0;if(!pe.test(f))return d("web_visuobject_bad_name",f);if(this.findClass(f)||this.project.files.some(w=>w.path===le(re(g,_),`${f}.java`)))return d("web_visuobject_new_exists",f);if(f.charAt(0)!==f.charAt(0).toUpperCase())return d("web_visuobject_new_upper")}});if(!i)return;const{name:n,root:o,pkg:r}=i;if(e==="project")return this.newProject({name:n,files:[],packages:[]},void 0,!0);if(this.message(""),e==="folder")return this.currentPackage=re(n,""),this.treeSelection=`root:${n}`,this.open.set(`root:${n}`,!0),this.setProject(ui(this.project,n));if(e==="package"){const p=re(o,n);return this.currentPackage=p,this.treeSelection=`pkg:${p}`,this.open.set(`root:${o}`,!0),this.setProject(hi(this.project,p))}const c=re(o,r),l=le(c,`${n}.java`);this.currentPackage=c,this.selection={cls:n},this.open.set(`root:${o}`,!0),this.open.set(`pkg:${c}`,!0),this.setProject(et(this.project,l,this.sectioned(Gi(i.options),n)),l);const h=this.findClass(n);h&&this.showInCode(h),(u=this.canvas.querySelector(`.uml-class[data-class="${CSS.escape(n)}"]`))==null||u.scrollIntoView({block:"nearest",inline:"nearest"})}editProjectName(){this.treeSelection="project",this.renderTree(),this.startEditing(this.tree.querySelector('[data-node="project"] > .vo-row .vo-label'))}renderWorkspace(){const e=this.wsBox;e.hidden=!wt();const t=this.shell.querySelector("[data-action=save]");if(t.dataset.tip=d(this.workspace?"web_visuobject_save_ws_tip":"web_visuobject_save_tip"),e.hidden)return;const s=(i,n,o="text-button",r)=>``;this.workspace?(e.className="vo-ws",e.innerHTML=`${v(this.workspace.name)} ${s("zip",d("web_visuobject_ws_zip"),"text-button",d("web_visuobject_ws_zip_tip"))} ${s("switch",d("web_visuobject_ws_switch"),"text-button")}`):this.pendingFolder?(e.className="vo-ws",e.innerHTML=`${s("reopen",d("web_visuobject_ws_reopen",this.pendingFolder.name),"text-button primary")}${s("switch",d("web_visuobject_ws_switch"),"text-button")}`):se(rt)==="1"?(e.className="vo-ws",e.innerHTML=s("open",d("web_visuobject_ws_choose"),"text-button",d("web_visuobject_ws_hint"))):(e.className="vo-ws ask",e.innerHTML=`

${v(d("web_visuobject_ws_question"))}

${v(d("web_visuobject_ws_hint"))}

diff --git a/website/app/assets/projectZip-hYmaJ0X8.js b/website/app/assets/projectZip-C0Wt4zQg.js similarity index 99% rename from website/app/assets/projectZip-hYmaJ0X8.js rename to website/app/assets/projectZip-C0Wt4zQg.js index 4b7f80cc..969a435b 100644 --- a/website/app/assets/projectZip-hYmaJ0X8.js +++ b/website/app/assets/projectZip-C0Wt4zQg.js @@ -1 +1 @@ -import{p as Br,d as Er,a as mr,i as Gr,b as Qr,c as Vr,u as Lr,n as _r,o as pr,e as br,r as dr,f as re,s as ee}from"./objectApp-Dzw8stpM.js";import"./index-BZrdbqtU.js";var M=Uint8Array,K=Uint16Array,Tr=Int32Array,hr=new M([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),gr=new M([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Sr=new M([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Wr=function(r,e){for(var n=new K(31),a=0;a<31;++a)n[a]=e+=1<>1|(F&21845)<<1;b=(b&52428)>>2|(b&13107)<<2,b=(b&61680)>>4|(b&3855)<<4,Cr[F]=((b&65280)>>8|(b&255)<<8)>>1}var V=(function(r,e,n){for(var a=r.length,f=0,v=new K(e);f>l]=c}else for(s=new K(a),f=0;f>15-r[f]);return s}),d=new M(288);for(var F=0;F<144;++F)d[F]=8;for(var F=144;F<256;++F)d[F]=9;for(var F=256;F<280;++F)d[F]=7;for(var F=280;F<288;++F)d[F]=8;var ir=new M(32);for(var F=0;F<32;++F)ir[F]=5;var ae=V(d,9,0),fe=V(d,9,1),ve=V(ir,5,0),te=V(ir,5,1),xr=function(r){for(var e=r[0],n=1;ne&&(e=r[n]);return e},X=function(r,e,n){var a=e/8|0;return(r[a]|r[a+1]<<8)>>(e&7)&n},yr=function(r,e){var n=e/8|0;return(r[n]|r[n+1]<<8|r[n+2]<<16)>>(e&7)},Ur=function(r){return(r+7)/8|0},lr=function(r,e,n){return(e==null||e<0)&&(e=0),(n==null||n>r.length)&&(n=r.length),new M(r.subarray(e,n))},oe=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],I=function(r,e,n){var a=new Error(e||oe[r]);if(a.code=r,Error.captureStackTrace&&Error.captureStackTrace(a,I),!n)throw a;return a},ie=function(r,e,n,a){var f=r.length,v=a?a.length:0;if(!f||e.f&&!e.l)return n||new M(0);var i=!n,s=i||e.i!=2,l=e.i;i&&(n=new M(f*3));var c=function(fr){var vr=n.length;if(fr>vr){var nr=new M(Math.max(vr*2,fr));nr.set(n),n=nr}},t=e.f||0,o=e.p||0,u=e.b||0,h=e.l,y=e.d,w=e.m,x=e.n,T=f*8;do{if(!h){t=X(r,o,1);var z=X(r,o+1,3);if(o+=3,z)if(z==1)h=fe,y=te,w=9,x=5;else if(z==2){var U=X(r,o,31)+257,A=X(r,o+10,15)+4,m=U+X(r,o+5,31)+1;o+=14;for(var g=new M(m),B=new M(19),j=0;j>4;if(C<16)g[j++]=C;else{var E=0,k=0;for(C==16?(k=3+X(r,o,3),o+=2,E=g[j-1]):C==17?(k=3+X(r,o,7),o+=3):C==18&&(k=11+X(r,o,127),o+=7);k--;)g[j++]=E}}var W=g.subarray(0,U),J=g.subarray(U);w=xr(W),x=xr(J),h=V(W,w,1),y=V(J,x,1)}else I(1);else{var C=Ur(o)+4,O=r[C-4]|r[C-3]<<8,$=C+O;if($>f){l&&I(0);break}s&&c(u+O),n.set(r.subarray(C,$),u),e.b=u+=O,e.p=o=$*8,e.f=t;continue}if(o>T){l&&I(0);break}}s&&c(u+131072);for(var ar=(1<>4;if(o+=E&15,o>T){l&&I(0);break}if(E||I(2),q<256)n[u++]=q;else if(q==256){L=o,h=null;break}else{var H=q-254;if(q>264){var j=q-257,S=hr[j];H=X(r,o,(1<>4;G||I(3),o+=G&15;var J=ne[rr];if(rr>3){var S=gr[rr];J+=yr(r,o)&(1<T){l&&I(0);break}s&&c(u+131072);var er=u+H;if(u>8},tr=function(r,e,n){n<<=e&7;var a=e/8|0;r[a]|=n,r[a+1]|=n>>8,r[a+2]|=n>>16},Fr=function(r,e){for(var n=[],a=0;au&&(u=v[a].s);var h=new K(u+1),y=Or(n[t-1],h,0);if(y>e){var a=0,w=0,x=y-e,T=1<e)w+=T-(1<>=x;w>0;){var C=v[a].s;h[C]=0&&w;--a){var O=v[a].s;h[O]==e&&(--h[O],++w)}y=e}return{t:new M(h),l:y}},Or=function(r,e,n){return r.s==-1?Math.max(Or(r.l,e,n+1),Or(r.r,e,n+1)):e[r.s]=n},Nr=function(r){for(var e=r.length;e&&!r[--e];);for(var n=new K(++e),a=0,f=r[0],v=1,i=function(l){n[a++]=l},s=1;s<=e;++s)if(r[s]==f&&s!=e)++v;else{if(!f&&v>2){for(;v>138;v-=138)i(32754);v>2&&(i(v>10?v-11<<5|28690:v-3<<5|12305),v=0)}else if(v>3){for(i(f),--v;v>6;v-=6)i(8304);v>2&&(i(v-3<<5|8208),v=0)}for(;v--;)i(f);v=1,f=r[s]}return{c:n.subarray(0,a),n:e}},or=function(r,e){for(var n=0,a=0;a>8,r[f+2]=r[f]^255,r[f+3]=r[f+1]^255;for(var v=0;v4&&!B[Sr[D-1]];--D);var p=c+5<<3,Z=or(f,d)+or(v,ir)+i,P=or(f,u)+or(v,w)+i+14+3*D+or(A,B)+2*A[16]+3*A[17]+7*A[18];if(l>=0&&p<=Z&&p<=P)return Kr(e,t,r.subarray(l,l+c));var E,k,W,J;if(_(e,t,1+(P15&&(_(e,t,q[m]>>5&127),t+=q[m]>>12)}}else E=ae,k=d,W=ve,J=ir;for(var m=0;m255){var H=S>>18&31;tr(e,t,E[H+257]),t+=k[H+257],H>7&&(_(e,t,S>>23&31),t+=hr[H]);var G=S&31;tr(e,t,W[G]),t+=J[G],G>3&&(tr(e,t,S>>5&8191),t+=gr[G])}else tr(e,t,E[S]),t+=k[S]}return tr(e,t,E[256]),t+k[256]},le=new Tr([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Rr=new M(0),se=function(r,e,n,a,f,v){var i=v.z||r.length,s=new M(a+i+5*(1+Math.ceil(i/7e3))+f),l=s.subarray(a,s.length-f),c=v.l,t=(v.r||0)&7;if(e){t&&(l[0]=v.r>>3);for(var o=le[e-1],u=o>>13,h=o&8191,y=(1<7e3||B>24576)&&(E>423||!c)){t=Dr(r,l,0,O,$,U,m,B,D,g-D,t),B=A=m=0,D=g;for(var k=0;k<286;++k)$[k]=0;for(var k=0;k<30;++k)U[k]=0}var W=2,J=0,ar=h,R=Z-P&32767;if(E>2&&p==C(g-R))for(var L=Math.min(u,E)-1,q=Math.min(32767,g),H=Math.min(258,E);R<=q&&--ar&&Z!=P;){if(r[g+W]==r[g+W-R]){for(var S=0;SW){if(W=S,J=R,S>L)break;for(var G=Math.min(R,S-2),rr=0,k=0;krr&&(rr=ur,P=er)}}}Z=P,P=w[Z],R+=Z-P&32767}if(J){O[B++]=268435456|Mr[W]<<18|Jr[J];var fr=Mr[W]&31,vr=Jr[J]&31;m+=hr[fr]+gr[vr],++$[257+fr],++U[vr],j=g+W,++A}else O[B++]=r[g],++$[r[g]]}}for(g=Math.max(g,j);g=i&&(l[t/8|0]=c,nr=i),t=Kr(l,t+1,r.subarray(g,nr))}v.i=i}return lr(s,0,a+Ur(t)+f)},ue=(function(){for(var r=new Int32Array(256),e=0;e<256;++e){for(var n=e,a=9;--a;)n=(n&1&&-306674912)^n>>>1;r[e]=n}return r})(),ce=function(){var r=-1;return{p:function(e){for(var n=r,a=0;a>>8;r=n},d:function(){return~r}}},he=function(r,e,n,a,f){if(!f&&(f={l:1},e.dictionary)){var v=e.dictionary.subarray(-32768),i=new M(v.length+r.length);i.set(v),i.set(r,v.length),r=i,f.w=v.length}return se(r,e.level==null?6:e.level,e.mem==null?f.l?Math.ceil(Math.max(8,Math.min(13,Math.log(r.length)))*1.5):20:12+e.mem,n,a,f)},Xr=function(r,e){var n={};for(var a in r)n[a]=r[a];for(var a in e)n[a]=e[a];return n},Q=function(r,e){return r[e]|r[e+1]<<8},Y=function(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0},kr=function(r,e){return Y(r,e)+Y(r,e+4)*4294967296},N=function(r,e,n){for(;n;++e)r[e]=n,n>>>=8};function ge(r,e){return he(r,e||{},0,0)}function we(r,e){return ie(r,{i:2},e&&e.out,e&&e.dictionary)}var Yr=function(r,e,n,a){for(var f in r){var v=r[f],i=e+f,s=a;Array.isArray(v)&&(s=Xr(a,v[1]),v=v[0]),v instanceof M?n[i]=[v,s]:(n[i+="/"]=[new M(0),s],Yr(v,i,n,a))}},Ir=typeof TextEncoder<"u"&&new TextEncoder,Ar=typeof TextDecoder<"u"&&new TextDecoder,me=0;try{Ar.decode(Rr,{stream:!0}),me=1}catch{}var xe=function(r){for(var e="",n=0;;){var a=r[n++],f=(a>127)+(a>223)+(a>239);if(n+f>r.length)return{s:e,r:lr(r,n-1)};f?f==3?(a=((a&15)<<18|(r[n++]&63)<<12|(r[n++]&63)<<6|r[n++]&63)-65536,e+=String.fromCharCode(55296|a>>10,56320|a&1023)):f&1?e+=String.fromCharCode((a&31)<<6|r[n++]&63):e+=String.fromCharCode((a&15)<<12|(r[n++]&63)<<6|r[n++]&63):e+=String.fromCharCode(a)}};function cr(r,e){var n;if(Ir)return Ir.encode(r);for(var a=r.length,f=new M(r.length+(r.length>>1)),v=0,i=function(c){f[v++]=c},n=0;nf.length){var s=new M(v+8+(a-n<<1));s.set(f),f=s}var l=r.charCodeAt(n);l<128||e?i(l):l<2048?(i(192|l>>6),i(128|l&63)):l>55295&&l<57344?(l=65536+(l&1047552)|r.charCodeAt(++n)&1023,i(240|l>>18),i(128|l>>12&63),i(128|l>>6&63),i(128|l&63)):(i(224|l>>12),i(128|l>>6&63),i(128|l&63))}return lr(f,0,v)}function jr(r,e){if(e){for(var n="",a=0;a65535&&I(9),e+=a+4}return e},Pr=function(r,e,n,a,f,v,i,s){var l=a.length,c=n.extra,t=s&&s.length,o=zr(c);N(r,e,i!=null?33639248:67324752),e+=4,i!=null&&(r[e++]=20,r[e++]=n.os),r[e]=20,e+=2,r[e++]=n.flag<<1|(v<0&&8),r[e++]=f&&8,r[e++]=n.compression&255,r[e++]=n.compression>>8;var u=new Date(n.mtime==null?Date.now():n.mtime),h=u.getFullYear()-1980;if((h<0||h>119)&&I(10),N(r,e,h<<25|u.getMonth()+1<<21|u.getDate()<<16|u.getHours()<<11|u.getMinutes()<<5|u.getSeconds()>>1),e+=4,v!=-1&&(N(r,e,n.crc),N(r,e+4,v<0?-v-2:v),N(r,e+8,n.size)),N(r,e+12,l),N(r,e+14,o),e+=16,i!=null&&(N(r,e,t),N(r,e+6,n.attrs),N(r,e+10,i),e+=14),r.set(a,e),e+=l,o)for(var y in c){var w=c[y],x=w.length;N(r,e,+y),N(r,e+2,x),r.set(w,e+4),e+=4+x}return t&&(r.set(s,e),e+=t),e},Se=function(r,e,n,a,f){N(r,e,101010256),N(r,e+8,n),N(r,e+10,n),N(r,e+12,a),N(r,e+16,f)};function Me(r,e){e||(e={});var n={},a=[];Yr(r,"",n,e);var f=0,v=0;for(var i in n){var s=n[i],l=s[0],c=s[1],t=c.level==0?0:8,o=cr(i),u=o.length,h=c.comment,y=h&&cr(h),w=y&&y.length,x=zr(c.extra);u>65535&&I(11);var T=t?ge(l,c):l,z=T.length,C=ce();C.p(l),a.push(Xr(c,{size:l.length,crc:C.d(),c:T,f:o,m:y,u:u!=i.length||y&&h.length!=w,o:f,compression:t})),f+=30+u+x+z,v+=76+2*(u+x)+(w||0)+z}for(var O=new M(v+22),$=f,U=v-f,A=0;A65558)&&I(13);var f=Q(r,a+8);if(!f)return{};var v=Y(r,a+16),i=v==4294967295||f==65535;if(i){var s=Y(r,a-12);i=Y(r,s)==101075792,i&&(f=Y(r,s+32),v=Y(r,s+48))}for(var l=0;l|]/g,"_")||"Projekt",n={};for(const l of r.files)n[`${e}/${br(l.path)}`]=new Uint8Array(cr(l.text));const a=[...r.packages.map(l=>`${e}/${dr(l)}/${re(l).replace(/\./g,"/")}/`),...ee(r).map(l=>`${e}/${l}/`)];for(const l of a)Object.keys(n).some(c=>c.startsWith(l))||(n[l.replace(/\/\/$/,"/")]=new Uint8Array);return(r.uml&&Object.keys(r.uml).length||(f=r.notes)!=null&&f.length||(v=r.objects)!=null&&v.length)&&(n[`${e}/${$r}`]=new Uint8Array(cr(JSON.stringify({format:"visuobject",version:1,uml:r.uml??{},...(i=r.notes)!=null&&i.length?{notes:r.notes}:{},...(s=r.objects)!=null&&s.length?{objects:r.objects}:{}},null,2)))),Me(n,{level:6})}function ze(r,e){var c;const n=Ce(r),a=Object.entries(n).filter(([t])=>/\.java$/i.test(t)&&!t.startsWith("__MACOSX/")).map(([t,o])=>({name:t,text:jr(o)})),f=new Set(Object.keys(n).map(t=>t.split("/")[0])),v=f.size===1&&Object.keys(n).some(t=>t.includes("/"))?[...f][0]:e,i=v!==e,s=Br(v,[]);for(const t of a){const o=Br(v,[{name:t.name.slice(t.name.lastIndexOf("/")+1),text:t.text}]).files[0],u=t.name.split("/").slice(i?1:0,-1),h=Er(o.text).split(".").filter(Boolean),w=u.slice(u.length-h.length).join("/")===h.join("/")?u.slice(0,u.length-h.length).join("/"):"",x=w&&w!==mr&&w.split("/").every(Gr)&&!w.includes(":")?w:mr,T=Qr(Vr(x,Er(o.text)),o.path.slice(o.path.lastIndexOf("/")+1));s.files=[...s.files.filter(z=>z.path!==T),{...o,path:T}],x!==mr&&!((c=s.sourceFolders)!=null&&c.includes(x))&&(s.sourceFolders=[...s.sourceFolders??[],x])}const l=Object.entries(n).find(([t])=>t===$r||t.endsWith(`/${$r}`));if(l)try{const t=JSON.parse(jr(l[1])),o=Lr(t.uml);o&&(s.uml=o);const u=_r(t.notes);u&&(s.notes=u);const h=pr(t.objects);h&&(s.objects=h)}catch{}return s}export{ze as projectFromZip,je as projectToZip}; +import{p as Br,d as Er,a as mr,i as Gr,b as Qr,c as Vr,u as Lr,n as _r,o as pr,e as br,r as dr,f as re,s as ee}from"./objectApp-Cl7eAHYv.js";import"./index-D4MtCuvD.js";var M=Uint8Array,K=Uint16Array,Tr=Int32Array,hr=new M([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),gr=new M([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Sr=new M([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Wr=function(r,e){for(var n=new K(31),a=0;a<31;++a)n[a]=e+=1<>1|(F&21845)<<1;b=(b&52428)>>2|(b&13107)<<2,b=(b&61680)>>4|(b&3855)<<4,Cr[F]=((b&65280)>>8|(b&255)<<8)>>1}var V=(function(r,e,n){for(var a=r.length,f=0,v=new K(e);f>l]=c}else for(s=new K(a),f=0;f>15-r[f]);return s}),d=new M(288);for(var F=0;F<144;++F)d[F]=8;for(var F=144;F<256;++F)d[F]=9;for(var F=256;F<280;++F)d[F]=7;for(var F=280;F<288;++F)d[F]=8;var ir=new M(32);for(var F=0;F<32;++F)ir[F]=5;var ae=V(d,9,0),fe=V(d,9,1),ve=V(ir,5,0),te=V(ir,5,1),xr=function(r){for(var e=r[0],n=1;ne&&(e=r[n]);return e},X=function(r,e,n){var a=e/8|0;return(r[a]|r[a+1]<<8)>>(e&7)&n},yr=function(r,e){var n=e/8|0;return(r[n]|r[n+1]<<8|r[n+2]<<16)>>(e&7)},Ur=function(r){return(r+7)/8|0},lr=function(r,e,n){return(e==null||e<0)&&(e=0),(n==null||n>r.length)&&(n=r.length),new M(r.subarray(e,n))},oe=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],I=function(r,e,n){var a=new Error(e||oe[r]);if(a.code=r,Error.captureStackTrace&&Error.captureStackTrace(a,I),!n)throw a;return a},ie=function(r,e,n,a){var f=r.length,v=a?a.length:0;if(!f||e.f&&!e.l)return n||new M(0);var i=!n,s=i||e.i!=2,l=e.i;i&&(n=new M(f*3));var c=function(fr){var vr=n.length;if(fr>vr){var nr=new M(Math.max(vr*2,fr));nr.set(n),n=nr}},t=e.f||0,o=e.p||0,u=e.b||0,h=e.l,y=e.d,w=e.m,x=e.n,T=f*8;do{if(!h){t=X(r,o,1);var z=X(r,o+1,3);if(o+=3,z)if(z==1)h=fe,y=te,w=9,x=5;else if(z==2){var U=X(r,o,31)+257,A=X(r,o+10,15)+4,m=U+X(r,o+5,31)+1;o+=14;for(var g=new M(m),B=new M(19),j=0;j>4;if(C<16)g[j++]=C;else{var E=0,k=0;for(C==16?(k=3+X(r,o,3),o+=2,E=g[j-1]):C==17?(k=3+X(r,o,7),o+=3):C==18&&(k=11+X(r,o,127),o+=7);k--;)g[j++]=E}}var W=g.subarray(0,U),J=g.subarray(U);w=xr(W),x=xr(J),h=V(W,w,1),y=V(J,x,1)}else I(1);else{var C=Ur(o)+4,O=r[C-4]|r[C-3]<<8,$=C+O;if($>f){l&&I(0);break}s&&c(u+O),n.set(r.subarray(C,$),u),e.b=u+=O,e.p=o=$*8,e.f=t;continue}if(o>T){l&&I(0);break}}s&&c(u+131072);for(var ar=(1<>4;if(o+=E&15,o>T){l&&I(0);break}if(E||I(2),q<256)n[u++]=q;else if(q==256){L=o,h=null;break}else{var H=q-254;if(q>264){var j=q-257,S=hr[j];H=X(r,o,(1<>4;G||I(3),o+=G&15;var J=ne[rr];if(rr>3){var S=gr[rr];J+=yr(r,o)&(1<T){l&&I(0);break}s&&c(u+131072);var er=u+H;if(u>8},tr=function(r,e,n){n<<=e&7;var a=e/8|0;r[a]|=n,r[a+1]|=n>>8,r[a+2]|=n>>16},Fr=function(r,e){for(var n=[],a=0;au&&(u=v[a].s);var h=new K(u+1),y=Or(n[t-1],h,0);if(y>e){var a=0,w=0,x=y-e,T=1<e)w+=T-(1<>=x;w>0;){var C=v[a].s;h[C]=0&&w;--a){var O=v[a].s;h[O]==e&&(--h[O],++w)}y=e}return{t:new M(h),l:y}},Or=function(r,e,n){return r.s==-1?Math.max(Or(r.l,e,n+1),Or(r.r,e,n+1)):e[r.s]=n},Nr=function(r){for(var e=r.length;e&&!r[--e];);for(var n=new K(++e),a=0,f=r[0],v=1,i=function(l){n[a++]=l},s=1;s<=e;++s)if(r[s]==f&&s!=e)++v;else{if(!f&&v>2){for(;v>138;v-=138)i(32754);v>2&&(i(v>10?v-11<<5|28690:v-3<<5|12305),v=0)}else if(v>3){for(i(f),--v;v>6;v-=6)i(8304);v>2&&(i(v-3<<5|8208),v=0)}for(;v--;)i(f);v=1,f=r[s]}return{c:n.subarray(0,a),n:e}},or=function(r,e){for(var n=0,a=0;a>8,r[f+2]=r[f]^255,r[f+3]=r[f+1]^255;for(var v=0;v4&&!B[Sr[D-1]];--D);var p=c+5<<3,Z=or(f,d)+or(v,ir)+i,P=or(f,u)+or(v,w)+i+14+3*D+or(A,B)+2*A[16]+3*A[17]+7*A[18];if(l>=0&&p<=Z&&p<=P)return Kr(e,t,r.subarray(l,l+c));var E,k,W,J;if(_(e,t,1+(P15&&(_(e,t,q[m]>>5&127),t+=q[m]>>12)}}else E=ae,k=d,W=ve,J=ir;for(var m=0;m255){var H=S>>18&31;tr(e,t,E[H+257]),t+=k[H+257],H>7&&(_(e,t,S>>23&31),t+=hr[H]);var G=S&31;tr(e,t,W[G]),t+=J[G],G>3&&(tr(e,t,S>>5&8191),t+=gr[G])}else tr(e,t,E[S]),t+=k[S]}return tr(e,t,E[256]),t+k[256]},le=new Tr([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Rr=new M(0),se=function(r,e,n,a,f,v){var i=v.z||r.length,s=new M(a+i+5*(1+Math.ceil(i/7e3))+f),l=s.subarray(a,s.length-f),c=v.l,t=(v.r||0)&7;if(e){t&&(l[0]=v.r>>3);for(var o=le[e-1],u=o>>13,h=o&8191,y=(1<7e3||B>24576)&&(E>423||!c)){t=Dr(r,l,0,O,$,U,m,B,D,g-D,t),B=A=m=0,D=g;for(var k=0;k<286;++k)$[k]=0;for(var k=0;k<30;++k)U[k]=0}var W=2,J=0,ar=h,R=Z-P&32767;if(E>2&&p==C(g-R))for(var L=Math.min(u,E)-1,q=Math.min(32767,g),H=Math.min(258,E);R<=q&&--ar&&Z!=P;){if(r[g+W]==r[g+W-R]){for(var S=0;SW){if(W=S,J=R,S>L)break;for(var G=Math.min(R,S-2),rr=0,k=0;krr&&(rr=ur,P=er)}}}Z=P,P=w[Z],R+=Z-P&32767}if(J){O[B++]=268435456|Mr[W]<<18|Jr[J];var fr=Mr[W]&31,vr=Jr[J]&31;m+=hr[fr]+gr[vr],++$[257+fr],++U[vr],j=g+W,++A}else O[B++]=r[g],++$[r[g]]}}for(g=Math.max(g,j);g=i&&(l[t/8|0]=c,nr=i),t=Kr(l,t+1,r.subarray(g,nr))}v.i=i}return lr(s,0,a+Ur(t)+f)},ue=(function(){for(var r=new Int32Array(256),e=0;e<256;++e){for(var n=e,a=9;--a;)n=(n&1&&-306674912)^n>>>1;r[e]=n}return r})(),ce=function(){var r=-1;return{p:function(e){for(var n=r,a=0;a>>8;r=n},d:function(){return~r}}},he=function(r,e,n,a,f){if(!f&&(f={l:1},e.dictionary)){var v=e.dictionary.subarray(-32768),i=new M(v.length+r.length);i.set(v),i.set(r,v.length),r=i,f.w=v.length}return se(r,e.level==null?6:e.level,e.mem==null?f.l?Math.ceil(Math.max(8,Math.min(13,Math.log(r.length)))*1.5):20:12+e.mem,n,a,f)},Xr=function(r,e){var n={};for(var a in r)n[a]=r[a];for(var a in e)n[a]=e[a];return n},Q=function(r,e){return r[e]|r[e+1]<<8},Y=function(r,e){return(r[e]|r[e+1]<<8|r[e+2]<<16|r[e+3]<<24)>>>0},kr=function(r,e){return Y(r,e)+Y(r,e+4)*4294967296},N=function(r,e,n){for(;n;++e)r[e]=n,n>>>=8};function ge(r,e){return he(r,e||{},0,0)}function we(r,e){return ie(r,{i:2},e&&e.out,e&&e.dictionary)}var Yr=function(r,e,n,a){for(var f in r){var v=r[f],i=e+f,s=a;Array.isArray(v)&&(s=Xr(a,v[1]),v=v[0]),v instanceof M?n[i]=[v,s]:(n[i+="/"]=[new M(0),s],Yr(v,i,n,a))}},Ir=typeof TextEncoder<"u"&&new TextEncoder,Ar=typeof TextDecoder<"u"&&new TextDecoder,me=0;try{Ar.decode(Rr,{stream:!0}),me=1}catch{}var xe=function(r){for(var e="",n=0;;){var a=r[n++],f=(a>127)+(a>223)+(a>239);if(n+f>r.length)return{s:e,r:lr(r,n-1)};f?f==3?(a=((a&15)<<18|(r[n++]&63)<<12|(r[n++]&63)<<6|r[n++]&63)-65536,e+=String.fromCharCode(55296|a>>10,56320|a&1023)):f&1?e+=String.fromCharCode((a&31)<<6|r[n++]&63):e+=String.fromCharCode((a&15)<<12|(r[n++]&63)<<6|r[n++]&63):e+=String.fromCharCode(a)}};function cr(r,e){var n;if(Ir)return Ir.encode(r);for(var a=r.length,f=new M(r.length+(r.length>>1)),v=0,i=function(c){f[v++]=c},n=0;nf.length){var s=new M(v+8+(a-n<<1));s.set(f),f=s}var l=r.charCodeAt(n);l<128||e?i(l):l<2048?(i(192|l>>6),i(128|l&63)):l>55295&&l<57344?(l=65536+(l&1047552)|r.charCodeAt(++n)&1023,i(240|l>>18),i(128|l>>12&63),i(128|l>>6&63),i(128|l&63)):(i(224|l>>12),i(128|l>>6&63),i(128|l&63))}return lr(f,0,v)}function jr(r,e){if(e){for(var n="",a=0;a65535&&I(9),e+=a+4}return e},Pr=function(r,e,n,a,f,v,i,s){var l=a.length,c=n.extra,t=s&&s.length,o=zr(c);N(r,e,i!=null?33639248:67324752),e+=4,i!=null&&(r[e++]=20,r[e++]=n.os),r[e]=20,e+=2,r[e++]=n.flag<<1|(v<0&&8),r[e++]=f&&8,r[e++]=n.compression&255,r[e++]=n.compression>>8;var u=new Date(n.mtime==null?Date.now():n.mtime),h=u.getFullYear()-1980;if((h<0||h>119)&&I(10),N(r,e,h<<25|u.getMonth()+1<<21|u.getDate()<<16|u.getHours()<<11|u.getMinutes()<<5|u.getSeconds()>>1),e+=4,v!=-1&&(N(r,e,n.crc),N(r,e+4,v<0?-v-2:v),N(r,e+8,n.size)),N(r,e+12,l),N(r,e+14,o),e+=16,i!=null&&(N(r,e,t),N(r,e+6,n.attrs),N(r,e+10,i),e+=14),r.set(a,e),e+=l,o)for(var y in c){var w=c[y],x=w.length;N(r,e,+y),N(r,e+2,x),r.set(w,e+4),e+=4+x}return t&&(r.set(s,e),e+=t),e},Se=function(r,e,n,a,f){N(r,e,101010256),N(r,e+8,n),N(r,e+10,n),N(r,e+12,a),N(r,e+16,f)};function Me(r,e){e||(e={});var n={},a=[];Yr(r,"",n,e);var f=0,v=0;for(var i in n){var s=n[i],l=s[0],c=s[1],t=c.level==0?0:8,o=cr(i),u=o.length,h=c.comment,y=h&&cr(h),w=y&&y.length,x=zr(c.extra);u>65535&&I(11);var T=t?ge(l,c):l,z=T.length,C=ce();C.p(l),a.push(Xr(c,{size:l.length,crc:C.d(),c:T,f:o,m:y,u:u!=i.length||y&&h.length!=w,o:f,compression:t})),f+=30+u+x+z,v+=76+2*(u+x)+(w||0)+z}for(var O=new M(v+22),$=f,U=v-f,A=0;A65558)&&I(13);var f=Q(r,a+8);if(!f)return{};var v=Y(r,a+16),i=v==4294967295||f==65535;if(i){var s=Y(r,a-12);i=Y(r,s)==101075792,i&&(f=Y(r,s+32),v=Y(r,s+48))}for(var l=0;l|]/g,"_")||"Projekt",n={};for(const l of r.files)n[`${e}/${br(l.path)}`]=new Uint8Array(cr(l.text));const a=[...r.packages.map(l=>`${e}/${dr(l)}/${re(l).replace(/\./g,"/")}/`),...ee(r).map(l=>`${e}/${l}/`)];for(const l of a)Object.keys(n).some(c=>c.startsWith(l))||(n[l.replace(/\/\/$/,"/")]=new Uint8Array);return(r.uml&&Object.keys(r.uml).length||(f=r.notes)!=null&&f.length||(v=r.objects)!=null&&v.length)&&(n[`${e}/${$r}`]=new Uint8Array(cr(JSON.stringify({format:"visuobject",version:1,uml:r.uml??{},...(i=r.notes)!=null&&i.length?{notes:r.notes}:{},...(s=r.objects)!=null&&s.length?{objects:r.objects}:{}},null,2)))),Me(n,{level:6})}function ze(r,e){var c;const n=Ce(r),a=Object.entries(n).filter(([t])=>/\.java$/i.test(t)&&!t.startsWith("__MACOSX/")).map(([t,o])=>({name:t,text:jr(o)})),f=new Set(Object.keys(n).map(t=>t.split("/")[0])),v=f.size===1&&Object.keys(n).some(t=>t.includes("/"))?[...f][0]:e,i=v!==e,s=Br(v,[]);for(const t of a){const o=Br(v,[{name:t.name.slice(t.name.lastIndexOf("/")+1),text:t.text}]).files[0],u=t.name.split("/").slice(i?1:0,-1),h=Er(o.text).split(".").filter(Boolean),w=u.slice(u.length-h.length).join("/")===h.join("/")?u.slice(0,u.length-h.length).join("/"):"",x=w&&w!==mr&&w.split("/").every(Gr)&&!w.includes(":")?w:mr,T=Qr(Vr(x,Er(o.text)),o.path.slice(o.path.lastIndexOf("/")+1));s.files=[...s.files.filter(z=>z.path!==T),{...o,path:T}],x!==mr&&!((c=s.sourceFolders)!=null&&c.includes(x))&&(s.sourceFolders=[...s.sourceFolders??[],x])}const l=Object.entries(n).find(([t])=>t===$r||t.endsWith(`/${$r}`));if(l)try{const t=JSON.parse(jr(l[1])),o=Lr(t.uml);o&&(s.uml=o);const u=_r(t.notes);u&&(s.notes=u);const h=pr(t.objects);h&&(s.objects=h)}catch{}return s}export{ze as projectFromZip,je as projectToZip}; diff --git a/website/app/assets/robot3d-GGJ-E5MR.js b/website/app/assets/robot3d-FyDAbXTC.js similarity index 99% rename from website/app/assets/robot3d-GGJ-E5MR.js rename to website/app/assets/robot3d-FyDAbXTC.js index 8713b55c..c4165879 100644 --- a/website/app/assets/robot3d-GGJ-E5MR.js +++ b/website/app/assets/robot3d-FyDAbXTC.js @@ -1,4 +1,4 @@ -var gl=Object.defineProperty;var _l=(i,t,e)=>t in i?gl(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var le=(i,t,e)=>_l(i,typeof t!="symbol"?t+"":t,e);import{C as rn,L as oo}from"./index-BZrdbqtU.js";/** +var gl=Object.defineProperty;var _l=(i,t,e)=>t in i?gl(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var le=(i,t,e)=>_l(i,typeof t!="symbol"?t+"":t,e);import{C as rn,L as oo}from"./index-D4MtCuvD.js";/** * @license * Copyright 2010-2025 Three.js Authors * SPDX-License-Identifier: MIT diff --git a/website/app/index.html b/website/app/index.html index 07c678db..83ebf59e 100644 --- a/website/app/index.html +++ b/website/app/index.html @@ -6,7 +6,7 @@ VisuStruct Web - +