1060 lines
69 KiB
TypeScript
1060 lines
69 KiB
TypeScript
// SPDX-FileCopyrightText: 2026 Scientific Computing Studio, LLC
|
||
// SPDX-License-Identifier: Apache-2.0
|
||
/**
|
||
* The application shell, laid out like an IDE:
|
||
*
|
||
* top bar the problem, the primary action (Run, or Compile & run for
|
||
* Mojo), share, open, reset, help, theme
|
||
* editor the language panes as file tabs over one editor; the
|
||
* other tabs follow the open one as you type
|
||
* side always there: the run setup (call, input, build, machine),
|
||
* the stepper controls, what runs next, the variables, and an
|
||
* inspect panel whose tabs are offered only when they mean
|
||
* something for the pane and the run (trace table, table of
|
||
* values, flowchart, data flow, lifetimes, proof, tests)
|
||
* dock full width, folds away: output, problems, the real compiler's
|
||
* answer (Mojo), the machine model's numbers (x86-64)
|
||
*
|
||
* Everything reads from the Session. Widths, the dock tab, and what is folded
|
||
* travel in the share link with the rest of the layout.
|
||
*/
|
||
import { el, clear, add, button, copyText, debounce } from './dom.js';
|
||
import { Editor } from './editor.js';
|
||
import { Session } from '../core/session.js';
|
||
import { LANG_NAMES, type LangId, type QuickFix, type ViewId } from '#core/common/types.js';
|
||
import { SERVICES, LANG_ORDER } from '#core/services/index.js';
|
||
import { LINKED, SyncHub, isLinked } from '#core/sync/hub.js';
|
||
import { generatedLabel, mojoBadges } from './provenance.js';
|
||
import { MACHINES } from '#core/services/asm.js';
|
||
import { asmMojoLines, machineLabel, machineName, parseMachine, relateAsmMojo } from '../core/hardware.js';
|
||
import { PROBLEMS, stateForProblem } from '../core/catalog.js';
|
||
import { encodeState, routeFor, clearLocal, EMBED_VIEWS, readStateFile, StateError, LIMITS, type PlayState, type DockTab } from '../core/state.js';
|
||
import { shortcodeTitle } from '../quarto/shortcodes.js';
|
||
import { traceView, type StepperApi } from './views/trace.js';
|
||
import { problemsView, proofView, type PanelHooks } from './views/panels.js';
|
||
import { testsView } from './views/tests.js';
|
||
import { hardwareBoard, type BoardApi } from './hw/board.js';
|
||
import type { BoardViewId } from '../core/hardware.js';
|
||
import { practicesView } from './views/practices.js';
|
||
import { storagePressure, exportVersions, importVersions, versionKey, newWorkspaceId } from '../core/versions.js';
|
||
import { practicesOn, setPracticesOn, onPracticesChange, PRACTICE_AREAS } from '../core/prefs.js';
|
||
import { flowView, dataFlowView, traceTableView } from './views/viz.js';
|
||
import { compilerView, focusCompilerLine } from './views/compiler.js';
|
||
import { confirmSend } from './consent.js';
|
||
import { lifetimesView } from './views/lifetimes.js';
|
||
import { runView } from './views/run.js';
|
||
import { nextIndent as mojoNextIndent, LINE_COMMENT as MOJO_LINE_COMMENT } from '#core/mojo/editing.js';
|
||
import { explainMojo } from '#core/mojo/reference.js';
|
||
import { forSimulator, simulatorSetup } from '#core/mojo/att.js';
|
||
import { MOJO_VERSION } from '#core/mojo/generated/pin.js';
|
||
import type { ListingFunction } from '#core/services/godbolt.js';
|
||
import { splitter } from './splitter.js';
|
||
import { tooltip } from './tooltip.js';
|
||
import { cycleTheme, effectiveTheme } from './theme.js';
|
||
import { FAMILIES, FAMILY_LABEL } from './stepkinds.js';
|
||
import { AREA_ORDER, AREAS, areaHasPane, paneForArea, safeSwitches, type AreaDef, type AreaId, type InspectId } from '../core/areas.js';
|
||
|
||
/**
|
||
* An inspect tab is offered when it applies to the pane, and dimmed (with the
|
||
* reason) when it applies but the run has nothing for it yet. A tab that does
|
||
* not apply is not shown at all, so nothing on screen is a dead end.
|
||
*/
|
||
interface InspectDef { id: InspectId; label: string; applies(area: AreaDef, lang: LangId): boolean; ready?(s: Session): string | null }
|
||
/** What an inspect tab needs from the pane that is open, apart from the area (which lists the tabs it may offer). */
|
||
const PANE_FIT: Record<InspectId, (l: LangId) => boolean> = {
|
||
trace: () => true, table: (l) => l !== 'asm', flow: (l) => l !== 'asm' && l !== 'speco', data: (l) => l !== 'asm' && l !== 'speco',
|
||
life: (l) => l === 'mojo', proof: (l) => l !== 'asm' && l !== 'mojo', tests: (l) => l !== 'asm' && l !== 'speco',
|
||
};
|
||
const INSPECT: InspectDef[] = [
|
||
{ id: 'trace', label: 'Trace', applies: (a, l) => a.inspect.includes('trace') && PANE_FIT.trace(l) }, // for x86-64 the panel holds the memory and what the instruction did; see labelOf
|
||
{ id: 'table', label: 'Values', applies: (a, l) => a.inspect.includes('table') && PANE_FIT.table(l) },
|
||
{ id: 'flow', label: 'Flowchart', applies: (a, l) => a.inspect.includes('flow') && PANE_FIT.flow(l) },
|
||
{ id: 'data', label: 'Data flow', applies: (a, l) => a.inspect.includes('data') && PANE_FIT.data(l) },
|
||
{ id: 'life', label: 'Lifetimes', applies: (a, l) => a.inspect.includes('life') && PANE_FIT.life(l), ready: (s) => { const tr = s.trace(); return tr && (tr.steps as any[]).some((st) => st.life?.length) ? null : 'No value in this run has a visible lifecycle yet: give a struct a __deinit__, __copyinit__ or __moveinit__ and run again.'; } },
|
||
{ id: 'proof', label: 'Prove', applies: (a, l) => a.inspect.includes('proof') && PANE_FIT.proof(l), ready: (s) => (s.proof()?.report.counts.total ? null : 'Nothing to prove yet: add ENSURE under a FUNCTION, or a SPEC in the speco pane.') },
|
||
{ id: 'tests', label: 'Tests', applies: (a, l) => a.inspect.includes('tests') && PANE_FIT.tests(l), ready: (s) => (s.tests().length ? null : 'Generated-input tests need a function with parameters.') },
|
||
];
|
||
|
||
const DOCKS: Array<{ id: DockTab; label: string; applies(area: AreaDef, lang: LangId): boolean }> = [
|
||
{ id: 'setup', label: 'Setup', applies: (a) => a.dock.includes('setup') },
|
||
{ id: 'output', label: 'Output', applies: (a) => a.dock.includes('output') },
|
||
{ id: 'problems', label: 'Problems', applies: (a) => a.dock.includes('problems') },
|
||
{ id: 'compiler', label: 'Compiler', applies: (a, l) => a.dock.includes('compiler') && l === 'mojo' },
|
||
// the Hardware area's board (ui/hw/board.ts); for its Mojo pane it says how to get to the machine
|
||
{ id: 'asm', label: 'Machine', applies: (a, l) => a.dock.includes('asm') && (l === 'asm' || a.id === 'hw') },
|
||
// the helper's own tab exists only while the area's switch is on
|
||
{ id: 'practices', label: 'Best practices', applies: (a, l) => a.dock.includes('practices') && practicesOn(a.id) && l === 'mojo' },
|
||
];
|
||
|
||
const MOJO_QUEST = 'https://quest.mojolang.org';
|
||
|
||
/**
|
||
* The whole playground inside a host page (`#/embed/playground/...`, the Quarto
|
||
* shortcode's view="playground"). The toolbar keeps Run, Share and the theme,
|
||
* shows the example's title in place of the problem menu (choosing another
|
||
* problem would navigate the frame away), and Reset discards the reader's
|
||
* edits to this example rather than the app's save for a problem.
|
||
*/
|
||
/** The part of the workspace a phone-width screen shows (styles.css). */
|
||
type NarrowPart = 'code' | 'side' | 'dock';
|
||
|
||
export interface ShellEmbed {
|
||
/** Discard the reader's saved edits and show the author's version again; absent when read-only. */
|
||
reset?: () => void;
|
||
/** Whether the reader has changed the example (Reset is shown only then). */
|
||
edited?: () => boolean;
|
||
readOnly?: boolean;
|
||
}
|
||
|
||
const PLACEHOLDER: Record<LangId, string> = {
|
||
lingo: 'To count the G bases in T:\n Start with Count at 0.\n For each letter b of T:\n If b is \'G\', add 1 to Count.\n The answer is Count.',
|
||
matho: '% equations, written in LaTeX\n\\bar{x} = \\frac{1}{n} \\sum_{i=0}^{n-1} x_i\n\\sigma^2 = \\frac{1}{n - 1} \\sum_{i=0}^{n-1} (x_i - \\bar{x})^2',
|
||
pseudo: 'FUNCTION COUNT_BASE(B : CHAR, T : STRING) RETURNS INTEGER\n ...\nENDFUNCTION',
|
||
speco: 'SPEC COUNT_BASE(B, T)\n ENSURE result = |{ K ∈ [0, |T|) : T[K] = B }|\n LOOP FOR I\n INVARIANT Total = |{ K ∈ [0, I) : T[K] = B }|',
|
||
mojo: 'def count_base(b: String, t: String) -> Int:\n var total = 0\n ...\n return total\n\n\ndef main():\n print(count_base("A", "GATTACA"))',
|
||
asm: ' xor eax, eax\n.scan:\n ...\n ret',
|
||
};
|
||
|
||
/** How a tab says where its pane stands against the others. */
|
||
const LINK_MARK: Record<'authored' | 'sync' | 'stale' | 'authority', string> = { authored: '', sync: '\u21c4', stale: '\u26a0', authority: '\u270e' };
|
||
const LINK_TEXT: Record<'authored' | 'sync' | 'authority', string> = {
|
||
authored: 'As written by the problem\'s author: nothing has been translated yet. Your first edit makes this pane the one the others follow.',
|
||
sync: 'In step: this pane follows the one you last edited.',
|
||
authority: 'You are editing here: the other panes follow this one.',
|
||
};
|
||
|
||
/** The line comment each pane toggles with Ctrl+/ (Cmd+/). */
|
||
const LINE_COMMENTS: Partial<Record<LangId, string>> = { pseudo: '//', mojo: MOJO_LINE_COMMENT, asm: ';' };
|
||
|
||
/** A row's tabs as one tablist with nothing else in it; `display: contents`, so the row lays out as before. */
|
||
function tabList(label: string): HTMLElement {
|
||
return el('div', { class: 'tablist', role: 'tablist', 'aria-label': label });
|
||
}
|
||
|
||
export class Shell {
|
||
readonly root: HTMLElement;
|
||
private session: Session;
|
||
private editors = new Map<LangId, Editor>();
|
||
|
||
// editor column
|
||
private paneTabs = el('div', { class: 'tabs pane-tabs' });
|
||
private paneHead = el('div', { class: 'pane-head' });
|
||
private paneHost = el('div', { class: 'pane-host' });
|
||
private paneSplit = el('div', { class: 'pane-split' });
|
||
/** The stepper, docked under the editor at the editor's width: the controls, the run's status, what runs next. */
|
||
private stepDock = el('div', { class: 'step-dock' });
|
||
|
||
// side column
|
||
private setup = el('section', { class: 'setup view view-setup' });
|
||
private runBar = el('div', { class: 'run-bar' });
|
||
private statusHost = el('div', { class: 'run-status' });
|
||
private nextHost = el('div', { class: 'next-host' });
|
||
private varsHost = el('div', { class: 'panel-body vars-host' });
|
||
private inspectTabs = el('div', { class: 'tabs inspect-tabs' });
|
||
private inspectHost = el('div', { class: 'panel-body inspect-host' });
|
||
private traceTableHost = el('div', { class: 'inspect-view inspect-trace' });
|
||
private inspectViewHost = el('div', { class: 'inspect-view' });
|
||
private sideSplit = el('div', { class: 'side-split' });
|
||
|
||
// dock
|
||
private dockTabs = el('div', { class: 'tabs dock-tabs' });
|
||
private dockHost = el('div', { class: 'dock-body' });
|
||
private outputEmpty = el('p', { class: 'muted small output-empty' });
|
||
private outputHost = el('div', { class: 'view view-output' });
|
||
private dockViewHost = el('div', { class: 'view' });
|
||
private dock = el('section', { class: 'dock' });
|
||
private dockToggle = el('button', { type: 'button', class: 'tab tab-toggle', title: 'Fold the dock away (or bring it back)' }, '▾');
|
||
private outputSummary = '';
|
||
|
||
private toolbar = el('header', { class: 'toolbar' });
|
||
/**
|
||
* On a phone-width screen (styles.css, max-width 700px) the workspace shows one part at a time, chosen in this bar
|
||
* at the foot of the toolbar: the code with the stepper, the side column (or the Hardware board) with the stepper,
|
||
* or the dock. On a wider screen the bar is hidden and every part is where it always is.
|
||
*/
|
||
private narrow: NarrowPart = 'code';
|
||
private narrowBar = el('div', { class: 'narrow-bar seg', role: 'group', 'aria-label': 'Show' });
|
||
private banner = el('div', { class: 'banner', role: 'status' });
|
||
private versionsOpen = false;
|
||
private versionsOff: (() => void) | null = null;
|
||
private workspace: HTMLElement;
|
||
private main: HTMLElement;
|
||
private stepper: StepperApi | null = null;
|
||
private inspectOff: (() => void) | null = null;
|
||
private dockOff: (() => void) | null = null;
|
||
private offSession: () => void;
|
||
private inlineMessages = (() => { try { return localStorage.getItem('pplus.inline') !== '0'; } catch { return true; } })();
|
||
private breakpoints = new Map<LangId, Set<number>>();
|
||
private inspect: InspectId = 'trace';
|
||
private dockTab: DockTab = 'output';
|
||
|
||
/** Hardware: the board on the right, in place of the side column and the dock. */
|
||
private readonly boardMode: boolean;
|
||
private boardHost = el('section', { class: 'side board-side' });
|
||
private board: BoardApi | null = null;
|
||
|
||
/** One of the app's own views as a card on the board: the setup, the output, the problems, the compiler, the Run view. */
|
||
private mountCard(id: BoardViewId, host: HTMLElement): (() => void) | void {
|
||
const hooks = this.hooks();
|
||
switch (id) {
|
||
case 'setup': this.setup.style.display = ''; add(host, this.setup); return;
|
||
case 'output': this.outputHost.style.display = ''; add(host, this.outputHost); return;
|
||
case 'problems': return problemsView(this.session, host, hooks);
|
||
case 'compiler': return compilerView(this.session, host, { ...hooks, sendToAsm: (fns, fn) => this.sendToAsm(fns, fn), compile: () => void this.compileNow(), askAgain: () => void this.compileNow(true) });
|
||
case 'run': return runView(this.session, host, { goto: (t) => { this.session.setT(t); this.stepper?.goto(t); }, follow: () => this.session.layout().follow ?? null, setFollow: (follow) => this.session.setLayout({ follow }) });
|
||
}
|
||
}
|
||
|
||
private embed: ShellEmbed | null;
|
||
private shownEdited = false;
|
||
private area: AreaDef;
|
||
|
||
constructor(session: Session, area: AreaDef, opts: { embed?: ShellEmbed } = {}) {
|
||
this.session = session;
|
||
this.area = area;
|
||
this.boardMode = area.workspace === 'board';
|
||
this.embed = opts.embed ?? null;
|
||
// a pane that is not one of the area's (a link made in another area) opens on the area's own first choice
|
||
if (!areaHasPane(area, session.state.lang)) session.setLang(paneForArea(area, session.state));
|
||
const s = session.state;
|
||
// a link from before the dock: the view it opened on is now a dock tab or an inspect tab
|
||
if (s.view === 'problems' || s.view === 'compiler' || s.view === 'asm') { this.dockTab = s.view; this.inspect = 'trace'; }
|
||
else this.inspect = s.view as InspectId;
|
||
if (!INSPECT.find((v) => v.id === this.inspect)?.applies(area, s.lang)) this.inspect = 'trace';
|
||
const lay = session.layout();
|
||
if (lay.dockTab) this.dockTab = lay.dockTab;
|
||
if (!DOCKS.find((d) => d.id === this.dockTab)?.applies(area, s.lang)) this.dockTab = 'output';
|
||
|
||
add(this.stepDock, this.runBar, this.nextHost);
|
||
const panes = el('section', { class: 'panes' }, this.paneTabs, this.paneHead, this.paneSplit, this.stepDock);
|
||
add(this.paneSplit, this.paneHost);
|
||
const inspectPanel = el('section', { class: 'panel panel-inspect' }, this.inspectTabs, this.inspectHost);
|
||
add(this.inspectHost, this.traceTableHost, this.inspectViewHost);
|
||
add(this.sideSplit, inspectPanel); this.sideSplit.classList.add('inspect-only');
|
||
// a board area (Hardware) is two panes: the code, and the board, which holds what the side column and the dock would
|
||
const side = this.boardMode ? this.boardHost : el('section', { class: 'side' }, this.sideSplit);
|
||
|
||
this.main = el('div', { class: 'main' + (this.boardMode ? ' main-board' : '') });
|
||
const split = splitter({
|
||
container: this.main, axis: 'x', initial: lay.split ?? (this.boardMode ? 0.46 : 0.54), min: 0.25, max: 0.8,
|
||
apply: (f) => this.main.style.setProperty('--split', `${(f * 100).toFixed(2)}%`),
|
||
onChange: (f) => session.setLayout({ split: f }),
|
||
});
|
||
add(this.main, panes, split, side);
|
||
|
||
add(this.dock, this.dockTabs, this.dockHost);
|
||
add(this.dockHost, this.setup, this.outputHost, this.dockViewHost);
|
||
this.workspace = el('main', { class: 'workspace' + (this.boardMode ? ' workspace-board' : ''), 'aria-label': `${area.name} workspace` });
|
||
if (this.boardMode) add(this.workspace, this.main);
|
||
else {
|
||
const dockBar = splitter({
|
||
container: this.workspace, axis: 'y', initial: lay.dock ?? 0.68, min: 0.3, max: 0.9,
|
||
apply: (f) => this.workspace.style.setProperty('--dock', `${(f * 100).toFixed(2)}%`),
|
||
onChange: (f) => session.setLayout({ dock: f }),
|
||
});
|
||
add(this.workspace, this.main, dockBar, this.dock);
|
||
}
|
||
this.workspace.dataset.narrow = this.narrow;
|
||
this.root = el('div', { class: 'shell' }, this.toolbar, this.banner, this.workspace);
|
||
this.renderBanner();
|
||
|
||
for (const lang of LANG_ORDER) this.editors.set(lang, this.makeEditor(lang));
|
||
this.renderToolbar();
|
||
this.renderPaneTabs();
|
||
this.showPane(s.lang);
|
||
if (this.boardMode) {
|
||
this.board = hardwareBoard(session, this.boardHost, {
|
||
items: () => session.layout().board ?? null,
|
||
setItems: (board) => session.setLayout({ board }),
|
||
app: (id, host) => this.mountCard(id, host),
|
||
openPane: (lang) => { session.setLang(lang); this.showPane(lang); },
|
||
});
|
||
} else {
|
||
if (session.allDiagnostics().some((d) => d.severity === 'error')) { this.dockTab = 'problems'; this.session.setLayout({ dockCollapsed: false }); }
|
||
this.showDock(this.dockTab);
|
||
this.applyDockCollapsed();
|
||
}
|
||
this.offSession = session.onChange((what) => {
|
||
// the area switch depends on whether another area would show the same Mojo
|
||
if (what === 'source' && this.session.state.lang === 'mojo' && this.area.id === 'bridge') this.renderToolbar();
|
||
if (what === 'source') { this.refreshDiagnostics(); this.refreshDerived(); this.renderInspectTabs(); }
|
||
// an embedded playground: Reset appears once the reader has changed the example, and goes once they undo it
|
||
if (this.embed?.edited && this.embed.edited() !== this.shownEdited) this.renderToolbar();
|
||
if (what === 'run') { this.refreshDiagnostics(); this.renderInspectTabs(); if (this.session.state.lang === 'mojo') { this.renderToolbar(); this.renderPaneHead(); } }
|
||
if (what === 'state') this.renderInspectTabs();
|
||
});
|
||
this.offPractices = onPracticesChange(() => this.practicesChanged());
|
||
this.refreshDiagnostics();
|
||
this.refreshDerived();
|
||
}
|
||
|
||
private offPractices: () => void = () => { };
|
||
/** Whether the Mojo tab (Bridge) shows the rewritten copy instead of only the literal translation. */
|
||
private idiomatic = false;
|
||
|
||
private practicesChanged(): void {
|
||
if (!practicesOn(this.area.id)) this.idiomatic = false;
|
||
this.renderToolbar();
|
||
this.refreshDiagnostics();
|
||
this.renderPaneHead();
|
||
const here = DOCKS.find((d) => d.id === this.dockTab)!;
|
||
if (!here.applies(this.area, this.session.state.lang)) this.showDock('output'); else this.showDock(this.dockTab);
|
||
}
|
||
|
||
/** Light lines in their panes without moving the student's own cursor or tab. */
|
||
private highlightPairs(pairs: Array<[LangId, number]>): void {
|
||
for (const [lang, line] of pairs) {
|
||
const ed = this.editors.get(lang);
|
||
if (!ed) continue;
|
||
ed.setDecorations({ linked: new Set([line]) });
|
||
ed.scrollToLine(line);
|
||
setTimeout(() => ed.setDecorations({ linked: undefined }), 1600);
|
||
}
|
||
}
|
||
|
||
destroy(): void { this.board?.destroy(); this.versionsOff?.(); this.offPractices(); this.offSession(); this.stepper?.destroy(); this.inspectOff?.(); this.dockOff?.(); tooltip.hide(); }
|
||
|
||
/* ---------- editors ---------- */
|
||
|
||
private makeEditor(lang: LangId): Editor {
|
||
const svc = SERVICES[lang];
|
||
const onChange = debounce((v: string) => { this.session.setSource(lang, v); }, 150);
|
||
const ed = new Editor({
|
||
tokenize: svc.tokenize, tokenizeLines: svc.tokenizeLines, placeholder: PLACEHOLDER[lang], lang, inlineMessages: this.inlineMessages, readOnly: !!this.embed?.readOnly || (lang === 'mojo' && this.area.id === 'bridge'),
|
||
nextIndent: lang === 'mojo' ? mojoNextIndent : undefined, lineComment: LINE_COMMENTS[lang],
|
||
explainWord: lang === 'mojo' ? (w) => explainMojo(w) : undefined,
|
||
onCursorLine: lang === 'mojo' ? (line) => { focusCompilerLine(line); if (this.area.id === 'hw') this.linkLines(lang, line); }
|
||
: lang === 'asm' || isLinked(lang) ? (line) => this.linkLines(lang, line) : undefined,
|
||
onChange, onDiagnosticClick: () => this.showDock('problems', true),
|
||
onLineClick: lang === 'speco' ? undefined : (line) => this.toggleBreakpoint(lang, line),
|
||
});
|
||
ed.value = this.session.source(lang);
|
||
return ed;
|
||
}
|
||
|
||
private toggleBreakpoint(lang: LangId, line: number): void {
|
||
const set = this.breakpoints.get(lang) ?? new Set<number>();
|
||
if (set.has(line)) set.delete(line); else set.add(line);
|
||
this.breakpoints.set(lang, set);
|
||
this.editors.get(lang)!.setDecorations({ breakpoints: set });
|
||
if (this.stepper) { this.stepper.breakpoints.clear(); for (const l of set) this.stepper.breakpoints.add(l); }
|
||
}
|
||
|
||
private refreshDiagnostics(): void {
|
||
for (const [lang, ed] of this.editors) ed.setDiagnostics(this.session.diagnostics(lang));
|
||
this.renderPaneTabs();
|
||
this.renderDockTabs();
|
||
}
|
||
|
||
/**
|
||
* Bring the open pane up to date with the others. Only the pane on screen is touched (a hidden one is brought up
|
||
* to date when its tab is shown), the pane that was edited is never rewritten, and a pane that is not in step is
|
||
* read-only until the student chooses to edit it (which makes it the authority).
|
||
*/
|
||
private refreshDerived(): void {
|
||
this.syncEditor(this.session.state.lang);
|
||
this.renderPaneHead();
|
||
}
|
||
|
||
private syncEditor(lang: LangId): void {
|
||
const ed = this.editors.get(lang);
|
||
if (!ed) return;
|
||
const bridgeMojo = lang === 'mojo' && this.area.id === 'bridge';
|
||
if (bridgeMojo || (isLinked(lang) && this.session.state.sync?.authority !== lang)) ed.setSynced(this.session.source(lang));
|
||
const stale = isLinked(lang) && this.session.linkState(lang).kind === 'stale';
|
||
ed.setReadOnly(!!this.embed?.readOnly || bridgeMojo || stale);
|
||
}
|
||
|
||
/**
|
||
* Mark, in the next tab over, the lines that match a line of the open pane, so they are lit when that tab is
|
||
* selected: through the hub's maps in the Bridge, and in Hardware through the line table the compiler's listing
|
||
* left in the x86-64 pane (`; mojo line N`).
|
||
*/
|
||
private linkLines(lang: LangId, line: number): void {
|
||
if (lang !== this.session.state.lang) return;
|
||
const target = this.linkTarget();
|
||
const ed = target ? this.editors.get(target) : null;
|
||
if (!target || !ed) return;
|
||
const lines = this.area.id === 'hw'
|
||
? relateAsmMojo(this.session.source('asm'), lang as 'asm' | 'mojo', line)
|
||
: SyncHub.relate(this.session.lineMaps(), lang, line, target);
|
||
ed.setDecorations({ linked: new Set(lines) });
|
||
if (lines.length) ed.scrollToLine(lines[0]);
|
||
}
|
||
|
||
/** The x86-64 pane's line table, kept while the pane's text is the same. */
|
||
private asmTable: { source: string; map: Map<number, number> } | null = null;
|
||
private asmLinks(): Map<number, number> {
|
||
const src = this.session.source('asm');
|
||
if (this.asmTable?.source !== src) this.asmTable = { source: src, map: asmMojoLines(src) };
|
||
return this.asmTable.map;
|
||
}
|
||
|
||
private editInDeveloper(): void {
|
||
if (this.session.wouldReplaceMojo() && !confirm('Replace the Mojo in the Developer area with this generated Mojo?')) return;
|
||
if (this.session.adoptGeneratedMojo()) void this.openIn('dev');
|
||
}
|
||
|
||
/* ---------- the real compiler ---------- */
|
||
|
||
/**
|
||
* Compile & run. On work this browser already has godbolt's answer for (the same source, input and build level)
|
||
* it shows that answer again and sends nothing; `again` asks anyway, on purpose.
|
||
*/
|
||
private async compileNow(again = false): Promise<void> {
|
||
const kept = again ? null : this.session.keptCompile();
|
||
if (kept) { this.showDock('compiler', true); this.session.reuseCompile(kept); return; }
|
||
// the first send in this browser says what leaves it, and asks (ui/consent.ts)
|
||
if (!(await confirmSend())) return;
|
||
this.showDock('compiler', true);
|
||
void this.session.compile().then(() => {
|
||
const errs = this.session.diagnostics('mojo').filter((d) => d.severity === 'error');
|
||
if (errs.length && this.session.state.lang === 'mojo') this.editors.get('mojo')!.scrollToLine(errs[0].line);
|
||
});
|
||
}
|
||
|
||
/**
|
||
* One function of the listing, in Intel syntax, into the x86-64 pane. It
|
||
* replaces the pane's program, so it replaces the setup that belonged to
|
||
* that program too: registers for the function's arguments, in the System V
|
||
* order the compiler used. Asks first if the pane holds something else.
|
||
*/
|
||
private sendToAsm(functions: ListingFunction[], fn: ListingFunction): void {
|
||
const { source, data } = forSimulator(functions, fn);
|
||
const current = this.session.source('asm');
|
||
if (current.trim() && current !== source && !confirm(`Replace the x86-64 pane's program (and its setup) with ${fn.name}?`)) return;
|
||
this.session.setSource('asm', source);
|
||
this.editors.get('asm')!.value = source;
|
||
this.session.setSetup(simulatorSetup(fn, data));
|
||
this.session.setLang('asm');
|
||
// an area without an x86-64 pane (the Bridge, Developer) opens the work in Hardware, where the listing is
|
||
if (!areaHasPane(this.area, 'asm')) { void this.openIn('hw'); return; }
|
||
this.showPane('asm');
|
||
}
|
||
|
||
/* ---------- the editor column ---------- */
|
||
|
||
private renderPaneHead(): void {
|
||
clear(this.paneHead);
|
||
const lang = this.session.state.lang;
|
||
const link = isLinked(lang) && this.area.id === 'bridge' ? this.session.linkState(lang) : null;
|
||
if (link?.kind === 'stale') {
|
||
add(this.paneHead, el('span', { class: 'pane-note pane-stale', title: link.reason }, `Not in step: ${link.reason}`),
|
||
el('span', { class: 'spacer' }),
|
||
button('Edit anyway', () => { this.session.takeAuthority(lang as any); this.editors.get(lang)?.focus(); }, { class: 'btn btn-small', title: 'Make this pane the one the others follow; they are regenerated from it' }));
|
||
} else if (lang !== 'mojo') add(this.paneHead, this.tabsNote());
|
||
if (lang === 'mojo' && this.area.id === 'bridge') {
|
||
add(this.paneHead, ...mojoBadges(this.session),
|
||
el('span', { class: 'pane-note' }, 'Read-only, made from the pseudo. ', el('b', {}, 'Compile & run'), ' asks the real compiler. '),
|
||
el('span', { class: 'spacer' }),
|
||
practicesOn('bridge') ? button(this.idiomatic ? 'Hide idiomatic version' : 'Show idiomatic version', () => { this.idiomatic = !this.idiomatic; this.renderPaneHead(); }, { class: 'btn btn-small', title: 'A copy with the safe best-practice rewrites applied, shown only if it checks and prints the same' }) : null,
|
||
button('Edit in Developer', () => this.editInDeveloper(), { class: 'btn btn-small', title: 'Copy this Mojo into the Developer area, where you can change it' }));
|
||
if (this.idiomatic && practicesOn('bridge')) {
|
||
const r = this.session.idiomaticMojo();
|
||
add(this.paneHead, r.ok
|
||
? el('div', { class: 'idiomatic' }, el('div', { class: 'idiomatic-head' }, generatedLabel('generated', { rewrites: r.applied.length }),
|
||
el('span', { class: 'small muted' }, r.applied.map((f) => f.rule).filter((x, i, a) => a.indexOf(x) === i).join(', ')), el('span', { class: 'spacer' }),
|
||
button('Copy', async (e) => { await copyText(r.source); (e.target as HTMLButtonElement).textContent = 'Copied'; }, { class: 'btn btn-small' })),
|
||
el('pre', { class: 'mono idiomatic-code' }, r.source))
|
||
: el('p', { class: 'hint idiomatic' }, r.reason));
|
||
}
|
||
} else if (lang === 'mojo') {
|
||
const p = PROBLEMS.find((x) => x.id === this.session.state.problem);
|
||
const own = p?.mojo;
|
||
const same = own && own.source === this.session.source('mojo');
|
||
// generated Mojo never passes for verified: the exercise's own badge shows only when nothing says it came from a translation
|
||
const origin = this.session.provenance();
|
||
add(this.paneHead,
|
||
...mojoBadges(this.session),
|
||
origin ? null
|
||
: own ? (same
|
||
? el('span', { class: `badge ${own.verified ? 'badge-proved' : 'badge-open'}`, title: own.verified ? `godbolt's Mojo ${MOJO_VERSION} compiler built and ran this program, and it printed what it should.` : `Not verified: ${own.why}` }, own.verified ? `verified on Mojo ${MOJO_VERSION}` : 'not verified')
|
||
: el('span', { class: 'badge badge-open', title: 'You have changed the exercise\'s Mojo; Compile & run checks your version.' }, 'your edits')) : el('span', { class: 'badge' }, `Mojo ${MOJO_VERSION}`),
|
||
el('span', { class: 'pane-note' }, 'Steps live here; ', el('b', {}, 'Compile & run'), ' asks the real compiler. '),
|
||
this.area.id === 'hw' ? this.tabsNote() : null,
|
||
origin ? el('span', { class: 'spacer' }) : null,
|
||
origin ? button("I've reviewed this", () => { this.session.clearMojoOrigin(); }, { class: 'btn btn-small', title: 'Take the generated label and the header comment off. Only you can do this; compiling does not.' }) : null);
|
||
}
|
||
this.paneHead.style.display = this.paneHead.childNodes.length ? '' : 'none';
|
||
}
|
||
|
||
/**
|
||
* The tab one step from the open pane, whose lines a click here marks. In the Bridge, what it becomes one step
|
||
* down: lingo and matho mark the pseudo, pseudo marks the Mojo made from it. In Hardware, Mojo and x86-64 mark
|
||
* each other when the x86-64 came from the compiler's listing.
|
||
*/
|
||
private linkTarget(): 'pseudo' | 'mojo' | 'asm' | null {
|
||
const lang = this.session.state.lang;
|
||
if ((lang === 'lingo' || lang === 'matho') && areaHasPane(this.area, 'pseudo')) return 'pseudo';
|
||
if (lang === 'pseudo' && this.area.id === 'bridge') return 'mojo';
|
||
if (this.area.id === 'hw' && this.asmLinks().size > 0) {
|
||
if (lang === 'asm') return 'mojo';
|
||
if (lang === 'mojo') return 'asm';
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* One short line in the pane head saying the other tabs follow this one (the Bridge), or where the matching
|
||
* code is (Hardware). There is no second pane on screen: the student selects the tab to see it.
|
||
*/
|
||
private tabsNote(): HTMLElement | null {
|
||
const lang = this.session.state.lang;
|
||
if (this.area.id === 'bridge' && isLinked(lang)) {
|
||
const names = this.area.panes.filter((l) => l !== lang && (isLinked(l) || l === 'mojo')).map((l) => l === 'mojo' ? 'Mojo' : LANG_NAMES[l]);
|
||
if (!names.length) return null;
|
||
const list = names.length === 1 ? names[0] : names.length === 2 ? names.join(' and ') : `${names.slice(0, -1).join(', ')}, and ${names[names.length - 1]}`;
|
||
const text = `The ${list} tabs update as you type here; select a tab to see it.`;
|
||
return el('span', { class: 'pane-note pane-tabs-note', title: `${text} Click a line here and its lines are marked in the ${lang === 'pseudo' ? 'Mojo' : 'pseudo'} tab.` }, text);
|
||
}
|
||
if (this.area.id === 'hw' && (lang === 'mojo' || lang === 'asm')) {
|
||
const other = lang === 'mojo' ? 'x86-64' : 'Mojo';
|
||
if (!this.session.source(lang === 'mojo' ? 'asm' : 'mojo').trim()) return null;
|
||
const linked = this.asmLinks().size > 0;
|
||
const text = linked ? `Click a line to mark it in the ${other} tab.` : `${other} is in its own tab (lines not linked).`;
|
||
return el('span', { class: 'pane-note pane-tabs-note', title: linked ? 'Through the line table in the compiler\'s listing.' : 'This x86-64 was not sent from the Compiler view, so no line of it is tied to a line of the Mojo. Compile & run, then open a function of the listing in Hardware, to see them linked.' }, text);
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* The pane tabs, Mojo first. x86-64 appears when there is assembly to
|
||
* show (or the pane is open); pseudo, lingo, matho and speco sit to the
|
||
* right, dimmed until they hold something. A dimmed tab still opens: an
|
||
* empty pane with its placeholder, to write in.
|
||
*/
|
||
private renderPaneTabs(): void {
|
||
clear(this.paneTabs);
|
||
// the tabs alone are the tablist; the tools beside them (the inline-messages switch) sit outside it (tabList)
|
||
const list = tabList('Panes');
|
||
add(this.paneTabs, list);
|
||
const s = this.session.state;
|
||
const has = (l: LangId) => !!this.session.source(l).trim();
|
||
const bridge = this.area.id === 'bridge';
|
||
for (const lang of this.area.panes) {
|
||
const diags = this.session.diagnostics(lang);
|
||
const errs = diags.filter((d) => d.severity === 'error').length;
|
||
const warns = diags.filter((d) => d.severity === 'warning').length;
|
||
const dim = lang !== 'mojo' && lang !== 'asm' && !has(lang) && s.lang !== lang;
|
||
// where the pane stands against the others (the Bridge keeps four of them in step; see sync/hub.ts)
|
||
const link = bridge && isLinked(lang) ? this.session.linkState(lang) : null;
|
||
const mark = link ? LINK_MARK[link.kind] : '';
|
||
const title = link ? (link.kind === 'stale' ? `Not in step: ${link.reason}` : LINK_TEXT[link.kind]) : bridge && lang === 'mojo' ? 'Generated from the pseudo, line for line. Read-only: Edit in Developer to change it.' : dim ? `Nothing here yet; open the ${LANG_NAMES[lang]} pane to write some` : '';
|
||
add(list, el('button', {
|
||
type: 'button', role: 'tab', class: `tab tab-${lang}` + (lang === s.lang ? ' active' : '') + (dim ? ' tab-dim' : '') + (bridge && lang === 'mojo' ? ' tab-apart' : '') + (link ? ` tab-link-${link.kind}` : ''), 'aria-selected': lang === s.lang,
|
||
title,
|
||
onClick: () => { this.session.setLang(lang); this.showPane(lang); },
|
||
}, el('span', { class: 'tab-dot' }), bridge && lang === 'mojo' ? 'Mojo (from pseudo)' : LANG_NAMES[lang], mark ? el('span', { class: 'tab-state', 'aria-label': link!.kind }, mark) : null, errs ? el('span', { class: 'tab-badge err' }, String(errs)) : warns ? el('span', { class: 'tab-badge warn' }, String(warns)) : null));
|
||
}
|
||
const on = this.inlineMessages;
|
||
add(this.paneTabs, el('span', { class: 'spacer' }), el('label', { class: 'tool-label tool-check tabs-tool', title: 'Show each line\'s first problem at the end of the line' }, el('input', { type: 'checkbox', checked: on, onChange: (e: Event) => { this.inlineMessages = (e.target as HTMLInputElement).checked; try { localStorage.setItem('pplus.inline', this.inlineMessages ? '1' : '0'); } catch { /* ignore */ } for (const ed of this.editors.values()) ed.setInlineMessages(this.inlineMessages); } }), ' inline messages'));
|
||
}
|
||
|
||
/** Open the same work in another area. A problem opens by its id (its edits are saved); a shared or loaded program travels in the link. */
|
||
private async openIn(area: AreaId): Promise<void> {
|
||
if (area === this.area.id) return;
|
||
const st = this.session.state;
|
||
location.hash = st.problem ? routeFor({ kind: 'problem', area, id: st.problem }) : routeFor({ kind: 'shared', area, blob: await encodeState(st) });
|
||
}
|
||
|
||
/**
|
||
* The area switcher: shown only when another area would show the open pane exactly as it is (Developer and
|
||
* Hardware on the same Mojo), so the move itself never changes the work. Otherwise the areas are separate pages,
|
||
* reached from the nav and the home page; Edit in Developer and Open in Hardware are the deliberate moves.
|
||
*/
|
||
private areaSwitch(): HTMLElement | null {
|
||
const others = safeSwitches(this.area.id, this.session.state.lang, (a, l) => this.session.shownIn(a, l));
|
||
if (!others.length) return null;
|
||
const ids = AREA_ORDER.filter((id) => id === this.area.id || others.includes(id));
|
||
return el('div', { class: 'seg', role: 'group', title: 'The same work, as it is, in another area' },
|
||
...ids.map((id) => el('button', { type: 'button', class: 'seg-opt' + (id === this.area.id ? ' on' : ''), 'aria-pressed': id === this.area.id, title: id === this.area.id ? AREAS[id].tagline : `${AREAS[id].tagline} The ${LANG_NAMES[this.session.state.lang]} pane opens there as it is here.`, onClick: () => void this.openIn(id) }, AREAS[id].name)));
|
||
}
|
||
|
||
/** The area's name, where the switcher was: always say which area this is. */
|
||
private areaName(): HTMLElement {
|
||
return el('span', { class: 'area-name', title: this.area.tagline }, this.area.name);
|
||
}
|
||
|
||
private showPane(lang: LangId): void {
|
||
clear(this.paneHost);
|
||
this.renderToolbar();
|
||
this.syncEditor(lang);
|
||
const ed = this.editors.get(lang)!;
|
||
add(this.paneHost, ed.root);
|
||
ed.render();
|
||
this.renderPaneTabs();
|
||
this.renderToolbar();
|
||
this.renderSetup();
|
||
this.refreshDerived();
|
||
this.mountStepper();
|
||
if (!INSPECT.find((v) => v.id === this.inspect)!.applies(this.area, lang)) this.inspect = 'trace';
|
||
this.showInspect(this.inspect);
|
||
if (!DOCKS.find((d) => d.id === this.dockTab)!.applies(this.area, lang)) this.dockTab = 'output';
|
||
this.showDock(this.dockTab);
|
||
}
|
||
|
||
/* ---------- the side column ---------- */
|
||
|
||
/** The run setup, a dock tab: a fixed home for the call, the input, the build, the machine, the setup block. */
|
||
private renderSetup(): void {
|
||
clear(this.setup);
|
||
const s = this.session.state;
|
||
const lang = s.lang;
|
||
const grid = el('div', { class: 'setup-grid' });
|
||
const field = (label: string, control: HTMLElement, help?: string) => add(grid, el('label', { class: 'setup-label', title: help ?? '' }, label), control);
|
||
if (lang === 'mojo') {
|
||
const build = el('select', { class: 'select', 'aria-label': 'Build level', onChange: () => this.session.setBuildLevel(build.value as 'O0' | 'default') },
|
||
el('option', { value: 'O0', selected: this.session.buildLevel() === 'O0' }, 'as written (-O0)'),
|
||
el('option', { value: 'default', selected: this.session.buildLevel() === 'default' }, 'optimized'));
|
||
field('build', build, 'As written keeps every function you wrote, so the listing shows each one. Optimized is what mojo build does by default: small functions are folded into their callers.');
|
||
field('stdin', this.inputBox('What input() reads, one line per call, in order.'), 'What input() reads, one line per call, in order.');
|
||
} else if (lang === 'asm') {
|
||
const chosen = parseMachine(s.machine);
|
||
const machine = el('select', { class: 'select', 'aria-label': 'Machine', onChange: () => this.session.setMachine(machineName({ preset: machine.value, paging: chosen.paging })) }, ...MACHINES.map((m) => el('option', { value: m, selected: chosen.preset === m }, m)));
|
||
field('machine', machine, 'The machine model the x86-64 pane runs on (the Machine tab also turns virtual memory on or off)');
|
||
const ta = el('textarea', { class: 'input mono setup-ta', rows: 3, placeholder: 'rdi = 0x1000\nmemory 0x1000 "GATTACA"\nstdin "..."', value: s.setup || '' });
|
||
ta.addEventListener('change', () => this.session.setSetup(ta.value));
|
||
field('setup', ta, 'Registers, memory, and input, one per line. The program also gets a 512-byte stack.');
|
||
} else {
|
||
const call = el('input', { class: 'input mono', placeholder: this.session.callText() || 'CALL(…)', value: s.call ?? '' });
|
||
call.addEventListener('change', () => this.session.setCall(call.value.trim() || null));
|
||
call.addEventListener('keydown', (e) => { if (e.key === 'Enter') { this.session.setCall(call.value.trim() || null); this.stepper?.goto(0); } });
|
||
field('call', call, 'The call to run, such as COUNT_BASE(\'A\', "GATTACA"). Leave empty for the default.');
|
||
field('input', this.inputBox('What INPUT reads, one value per line, in order.'), 'What INPUT reads, one value per line, in order.');
|
||
}
|
||
add(this.setup, grid, el('p', { class: 'small muted setup-note' }, lang === 'mojo' ? 'The stepper above runs the Mojo pane in Programming+\'s interpreter as you edit; Compile & run sends it, with this input, to the real compiler.' : lang === 'asm' ? 'The program starts with these registers and this memory, and a 512-byte stack.' : 'The call runs as you edit; press Enter in the call to start the stepper over.'));
|
||
this.renderDockTabs();
|
||
}
|
||
|
||
private setupSummary(): string {
|
||
const s = this.session.state;
|
||
if (s.lang === 'mojo') return `${this.session.buildLevel() === 'O0' ? '-O0' : 'optimized'}${this.session.inputLines().length ? ` · ${this.session.inputLines().length} input line${this.session.inputLines().length === 1 ? '' : 's'}` : ''}`;
|
||
if (s.lang === 'asm') return `${machineLabel(s.machine)}${(s.setup || '').trim() ? ' · setup' : ''}`;
|
||
return this.session.callText() || '';
|
||
}
|
||
|
||
/** The input box: a fixed three-line well that scrolls, never one that grows under the pointer. */
|
||
private inputBox(title: string): HTMLElement {
|
||
const s = this.session.state;
|
||
const inp = el('textarea', { class: 'input mono setup-ta', rows: 2, placeholder: 'one value per line', title, spellcheck: false });
|
||
inp.value = s.input ?? '';
|
||
const reads = this.session.readsInput();
|
||
if (!reads && !(s.input ?? '').trim()) inp.placeholder = 'the program reads no input';
|
||
inp.addEventListener('change', () => this.session.setInput(inp.value));
|
||
return inp;
|
||
}
|
||
|
||
/** The stepper for the active pane's trace, with each of its parts in its persistent home. */
|
||
private mountStepper(): void {
|
||
this.stepper?.destroy(); this.stepper = null;
|
||
clear(this.runBar); clear(this.nextHost); clear(this.varsHost); clear(this.traceTableHost); clear(this.outputHost); clear(this.statusHost);
|
||
add(this.outputHost, this.outputEmpty);
|
||
const target: LangId = this.session.traceLang();
|
||
const controls = el('div', { class: 'run-controls' });
|
||
add(this.runBar, controls, this.statusHost);
|
||
this.stepper = traceView(this.session, this.runBar, {
|
||
hosts: { controls, next: this.nextHost, output: this.outputHost, status: this.statusHost },
|
||
onBreakpoints: (lines) => { this.breakpoints.set(target, new Set(lines)); this.editors.get(target)!.setDecorations({ breakpoints: new Set(lines) }); },
|
||
onStep: (next, last, hits) => {
|
||
const active = this.editors.get(target)!;
|
||
active.setDecorations({ current: next, last, hits, breakpoints: this.breakpoints.get(target) });
|
||
if (next) active.scrollToLine(next);
|
||
},
|
||
onOutput: (lines, err) => {
|
||
this.outputSummary = err ? 'stopped' : lines.length ? `${lines.length} line${lines.length === 1 ? '' : 's'}` : '';
|
||
this.renderDockTabs();
|
||
const tr = this.session.trace();
|
||
this.outputEmpty.textContent = !tr ? '' : lines.length || err ? '' : tr.output.length ? `Nothing printed yet at this step; the run prints ${tr.output.length} line${tr.output.length === 1 ? '' : 's'} in all.` : 'This run prints nothing.';
|
||
this.outputEmpty.style.display = this.outputEmpty.textContent ? '' : 'none';
|
||
},
|
||
});
|
||
for (const l of this.breakpoints.get(target) ?? []) this.stepper.breakpoints.add(l);
|
||
this.stepper.goto(this.stepper.t);
|
||
}
|
||
|
||
private renderInspectTabs(): void {
|
||
clear(this.inspectTabs);
|
||
const list = tabList('Views of the run');
|
||
add(this.inspectTabs, list);
|
||
const lang = this.session.state.lang;
|
||
for (const v of INSPECT) {
|
||
if (!v.applies(this.area, lang)) continue;
|
||
const why = v.ready ? v.ready(this.session) : null;
|
||
const label = v.id === 'trace' ? (lang === 'asm' ? 'Memory' : 'Run') : v.label;
|
||
add(list, el('button', { type: 'button', role: 'tab', class: 'tab' + (v.id === this.inspect ? ' active' : '') + (why ? ' tab-dim' : ''), title: why ?? '', 'aria-selected': v.id === this.inspect, onClick: () => this.showInspect(v.id) }, label));
|
||
}
|
||
const max = this.sideSplit.classList.contains('inspect-max');
|
||
add(this.inspectTabs, el('span', { class: 'spacer' }), this.legend(),
|
||
this.sideSplit.classList.contains('inspect-only') ? null : el('button', { type: 'button', class: 'tab tab-toggle', title: max ? 'Show the variables again' : 'Give this panel the whole column', onClick: () => { this.sideSplit.classList.toggle('inspect-max'); this.renderInspectTabs(); } }, max ? '⤓' : '⤢'));
|
||
}
|
||
|
||
/** What the step colors mean, once, where the steps are. */
|
||
private legend(): HTMLElement {
|
||
const box = el('details', { class: 'legend' }, el('summary', { title: 'What the colors on the steps mean' }, 'legend'));
|
||
const list = el('div', { class: 'legend-list' });
|
||
for (const f of FAMILIES) add(list, el('span', { class: 'legend-item' }, el('span', { class: `k-dot k-${f}` }), FAMILY_LABEL[f]));
|
||
add(box, list);
|
||
return box;
|
||
}
|
||
|
||
private showInspect(view: InspectId): void {
|
||
if (this.boardMode) return;
|
||
this.inspect = view;
|
||
this.session.setView(view);
|
||
this.inspectOff?.(); this.inspectOff = null;
|
||
clear(this.inspectViewHost);
|
||
this.renderInspectTabs();
|
||
// the Run view draws the run for every language but x86-64, whose memory and registers the stepper draws
|
||
const isTrace = view === 'trace' && this.session.state.lang === 'asm';
|
||
this.traceTableHost.style.display = isTrace ? '' : 'none';
|
||
this.inspectViewHost.style.display = isTrace ? 'none' : '';
|
||
this.inspectViewHost.className = `inspect-view view view-${view}`;
|
||
if (isTrace) return;
|
||
const host = this.inspectViewHost;
|
||
const hooks = this.hooks();
|
||
const gotoStep = (t: number) => { this.session.setT(t); this.stepper?.goto(t); this.showInspect('trace'); };
|
||
switch (view) {
|
||
case 'trace': this.inspectOff = runView(this.session, host, { goto: (t) => { this.session.setT(t); this.stepper?.goto(t); }, follow: () => this.session.layout().follow ?? null, setFollow: (follow) => this.session.setLayout({ follow }) }); break;
|
||
case 'proof': this.inspectOff = proofView(this.session, host, hooks); break;
|
||
case 'tests': this.inspectOff = testsView(this.session, host, { ...hooks, stepThrough: (call) => { this.session.setCall(call); this.renderSetup(); this.stepper?.goto(0); this.showInspect('trace'); } }); break;
|
||
case 'life': this.inspectOff = lifetimesView(this.session, host, { goto: gotoStep }); break;
|
||
case 'flow': this.inspectOff = flowView(this.session, host, hooks); break;
|
||
case 'data': this.inspectOff = dataFlowView(this.session, host, hooks); break;
|
||
case 'table': this.inspectOff = traceTableView(this.session, host, { goto: gotoStep }); break;
|
||
}
|
||
}
|
||
|
||
/* ---------- the dock ---------- */
|
||
|
||
private renderDockTabs(): void {
|
||
clear(this.dockTabs);
|
||
const list = tabList('The dock');
|
||
add(this.dockTabs, list);
|
||
const lang = this.session.state.lang;
|
||
const errs = this.session.allDiagnostics().filter((d) => d.severity === 'error').length;
|
||
const warns = this.session.allDiagnostics().filter((d) => d.severity === 'warning').length;
|
||
for (const d of DOCKS) {
|
||
if (!d.applies(this.area, lang)) continue;
|
||
const badge = d.id === 'problems' ? (errs ? el('span', { class: 'tab-badge err' }, String(errs)) : warns ? el('span', { class: 'tab-badge warn' }, String(warns)) : null)
|
||
: d.id === 'output' && this.outputSummary ? el('span', { class: 'tab-badge' }, this.outputSummary)
|
||
: d.id === 'setup' ? el('span', { class: 'tab-note mono' }, this.setupSummary()) : null;
|
||
add(list, el('button', { type: 'button', role: 'tab', class: 'tab' + (d.id === this.dockTab ? ' active' : ''), 'aria-selected': d.id === this.dockTab, onClick: () => this.showDock(d.id, true) }, d.label, badge));
|
||
}
|
||
this.dockToggle.onclick = () => { this.session.setLayout({ dockCollapsed: !this.session.layout().dockCollapsed }); this.applyDockCollapsed(); };
|
||
add(this.dockTabs, el('span', { class: 'spacer' }), this.dockToggle);
|
||
}
|
||
|
||
private applyDockCollapsed(): void {
|
||
const c = !!this.session.layout().dockCollapsed;
|
||
this.workspace.classList.toggle('dock-collapsed', c);
|
||
this.dockToggle.textContent = c ? '▴' : '▾';
|
||
this.dockToggle.title = c ? 'Bring the dock back' : 'Fold the dock away';
|
||
}
|
||
|
||
private showDock(tab: DockTab, open = false): void {
|
||
// asking for a part of the dock (Compile & run, a click on a diagnostic) shows it on a phone-width screen too
|
||
if (open) this.setNarrow('dock');
|
||
if (this.boardMode) {
|
||
// the board holds these as cards: asking for one (Compile & run, a click on a diagnostic) brings it into view
|
||
if (open && (tab === 'setup' || tab === 'output' || tab === 'problems' || tab === 'compiler')) this.board?.reveal(tab);
|
||
return;
|
||
}
|
||
this.dockTab = tab;
|
||
if (this.session.layout().dockTab !== tab) this.session.setLayout({ dockTab: tab });
|
||
if (open && this.session.layout().dockCollapsed) { this.session.setLayout({ dockCollapsed: false }); this.applyDockCollapsed(); }
|
||
this.dockOff?.(); this.dockOff = null;
|
||
clear(this.dockViewHost);
|
||
this.renderDockTabs();
|
||
const isOutput = tab === 'output', isSetup = tab === 'setup';
|
||
this.outputHost.style.display = isOutput ? '' : 'none';
|
||
this.setup.style.display = isSetup ? '' : 'none';
|
||
this.dockViewHost.style.display = isOutput || isSetup ? 'none' : '';
|
||
this.dockViewHost.className = `view view-${tab}`;
|
||
if (isOutput || isSetup) return;
|
||
const hooks = this.hooks();
|
||
switch (tab) {
|
||
case 'problems': this.dockOff = problemsView(this.session, this.dockViewHost, hooks); break;
|
||
case 'practices': this.dockOff = practicesView(this.session, this.dockViewHost, { highlight: (pairs) => this.highlightPairs(pairs) }); break;
|
||
case 'compiler': this.dockOff = compilerView(this.session, this.dockViewHost, { ...hooks, sendToAsm: (fns, fn) => this.sendToAsm(fns, fn), compile: () => void this.compileNow(), askAgain: () => void this.compileNow(true) }); break;
|
||
}
|
||
}
|
||
|
||
/* ---------- toolbar ---------- */
|
||
|
||
private renderToolbar(): void {
|
||
clear(this.toolbar);
|
||
const s = this.session.state;
|
||
this.shownEdited = !!this.embed?.edited?.();
|
||
const select = el('select', { class: 'select', 'aria-label': 'Problem', onChange: () => { location.hash = routeFor({ kind: 'problem', area: this.area.id, id: select.value }); } });
|
||
let group: HTMLOptGroupElement | null = null;
|
||
for (const p of PROBLEMS) {
|
||
if (!group || group.label !== p.group) { group = el('optgroup', { label: p.group }); select.appendChild(group); }
|
||
group.appendChild(el('option', { value: p.id, selected: p.id === s.problem }, p.title));
|
||
}
|
||
// the page's heading, for a screen reader's outline: the area and the work open in it (the toolbar shows both)
|
||
add(this.toolbar, el('h1', { class: 'sr-only' }, `${this.area.name}: ${s.title || PROBLEMS.find((p) => p.id === s.problem)?.title || 'a shared program'}`));
|
||
if (!s.problem) select.insertBefore(el('option', { value: '', selected: true }, s.title || 'shared program'), select.firstChild);
|
||
else if (!PROBLEMS.some((p) => p.id === s.problem)) select.insertBefore(el('option', { value: s.problem, selected: true }, s.title || s.problem), select.firstChild);
|
||
if (this.embed) {
|
||
// in a host page: the example's title, not a menu that would navigate the frame away
|
||
const open = el('a', { class: 'brand', href: '#', target: '_blank', rel: 'noopener', title: 'Open this example, as it is now, in Programming+' }, el('span', { class: 'brand-mark' }, 'P+'), 'Programming+ ↗');
|
||
void encodeState(s).then((blob) => { open.href = `${location.href.split('#')[0]}${routeFor({ kind: 'shared', area: this.area.id, blob })}`; });
|
||
add(this.toolbar, open, el('span', { class: 'embed-name' }, s.title || PROBLEMS.find((p) => p.id === s.problem)?.title || 'Example'), this.areaSwitch() ?? this.areaName());
|
||
} else add(this.toolbar, el('a', { class: 'brand', href: '#/' }, el('span', { class: 'brand-mark' }, 'P+'), 'Programming+'), this.areaSwitch() ?? this.areaName(), select, this.versionsControl());
|
||
const lang = s.lang;
|
||
const primary = lang === 'mojo'
|
||
? button(this.session.compiling ? 'Compiling…' : '▶ Compile & run', () => void this.compileNow(), { class: 'btn btn-primary', disabled: !!this.session.compiling, title: `Build and run the Mojo pane with the real Mojo ${MOJO_VERSION} compiler: sends the program and its input to godbolt.org (Ctrl+Enter)` })
|
||
: button('▶ Run', () => { this.showInspect('trace'); this.stepper?.goto(this.session.trace()?.count ?? 0); this.setNarrow('side'); }, { class: 'btn btn-primary', title: 'Run to the end (Ctrl+Enter)' });
|
||
add(this.toolbar,
|
||
el('span', { class: 'spacer' }),
|
||
primary,
|
||
button('Share', () => this.share(), { class: 'btn', title: 'Link, embed code, or a file' }),
|
||
this.embed ? null : button('Open…', () => this.openFile(), { class: 'btn', title: 'Load a saved .pplus.json file' }),
|
||
this.embed ? (this.embed.reset && this.embed.edited?.() ? button('Reset', () => { if (confirm('Discard your changes to this example and show the original again?')) this.embed!.reset!(); }, { class: 'btn btn-quiet', title: 'Your changes here are saved in this browser. Reset shows the original example again.' }) : null) :
|
||
s.problem ? button('Reset', () => this.resetProblem(), { class: 'btn btn-quiet', title: 'Show the problem as written. Your work is saved as a version first, so Reset can be undone from the Versions menu.' }) : null,
|
||
!this.embed && (PRACTICE_AREAS as readonly string[]).includes(this.area.id)
|
||
? button(practicesOn(this.area.id) ? 'Best practices: on' : 'Best practices: off', () => setPracticesOn(this.area.id, !practicesOn(this.area.id)), { class: `btn btn-quiet${practicesOn(this.area.id) ? ' btn-on' : ''}`, 'aria-pressed': practicesOn(this.area.id), title: 'Notes on how a Mojo programmer would write the Mojo here. Off until you turn it on; each area remembers its own choice in this browser.' }) : null,
|
||
button('?', () => this.helpDialog(), { class: 'btn btn-quiet icon-btn', title: 'Keyboard shortcuts and how the panes fit together' }),
|
||
button(effectiveTheme() === 'dark' ? '☀' : '☾', (e) => { cycleTheme(); (e.target as HTMLButtonElement).textContent = effectiveTheme() === 'dark' ? '☀' : '☾'; }, { class: 'btn btn-quiet icon-btn', title: 'Switch between light and dark' }),
|
||
this.narrowBar,
|
||
);
|
||
this.renderNarrowBar();
|
||
}
|
||
|
||
/* ---------- a phone-width screen: one part at a time ---------- */
|
||
|
||
private renderNarrowBar(): void {
|
||
clear(this.narrowBar);
|
||
const parts: Array<[NarrowPart, string]> = this.boardMode ? [['code', 'Code'], ['side', 'Board']] : [['code', 'Code'], ['side', 'Run and views'], ['dock', 'Setup and output']];
|
||
for (const [id, label] of parts) add(this.narrowBar, el('button', { type: 'button', class: 'seg-opt' + (id === this.narrow ? ' on' : ''), 'aria-pressed': id === this.narrow, onClick: () => this.setNarrow(id) }, label));
|
||
}
|
||
|
||
/** Show one part on a phone-width screen; on a wider one it only records the choice. */
|
||
private setNarrow(part: NarrowPart): void {
|
||
if (this.boardMode && part === 'dock') part = 'side';
|
||
if (this.narrow === part) return;
|
||
this.narrow = part;
|
||
this.workspace.dataset.narrow = part;
|
||
this.renderNarrowBar();
|
||
}
|
||
|
||
/* ---------- saved versions ---------- */
|
||
|
||
private versionTime(at: number): string {
|
||
return new Date(at).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' });
|
||
}
|
||
|
||
private versionsChanged(): void {
|
||
this.reload();
|
||
this.renderBanner();
|
||
}
|
||
|
||
/** The problem as written, after saving the student's work as a version (a refused save asks first). */
|
||
private resetProblem(): void {
|
||
const s = this.session.state;
|
||
const p = PROBLEMS.find((x) => x.id === s.problem);
|
||
if (!p) return;
|
||
const has = this.session.hasUnsavedEdits();
|
||
if (has ? !confirm('Show the problem as written? Your work is saved first as a version, so you can come back to it.') : !confirm('Show the problem as written?')) return;
|
||
if (!this.session.reset(stateForProblem(p))) {
|
||
if (!confirm('Your work could not be saved as a version (the list is full or the browser refused). Reset anyway and lose it?')) return;
|
||
this.session.resetTo(stateForProblem(p));
|
||
}
|
||
this.versionsChanged();
|
||
}
|
||
|
||
/** The line under the toolbar when the problem changed under the student's saved edits. */
|
||
private renderBanner(): void {
|
||
clear(this.banner);
|
||
const show = this.session.stale && !this.embed;
|
||
this.banner.style.display = show ? '' : 'none';
|
||
if (!show) return;
|
||
add(this.banner,
|
||
el('span', {}, 'This problem has changed since you saved your edits. You are looking at your edits to the older version.'),
|
||
el('span', { class: 'spacer' }),
|
||
button('See the new version', () => {
|
||
if (!this.session.seeNewVersion()) { alert('Your edits could not be saved as a version, so the problem was not changed.'); return; }
|
||
this.versionsChanged();
|
||
}, { class: 'btn btn-small', title: 'Keeps your edits as the version "My edits, before the problem changed" and opens the problem as it is now' }));
|
||
}
|
||
|
||
/** The versions drop-down: Current, then saved versions newest first, then Save version…. */
|
||
private versionsControl(): HTMLElement {
|
||
const host = el('div', { class: 'versions' });
|
||
const count = this.session.versions().length;
|
||
const btn = button(count ? `Versions (${count}) ▾` : 'Versions ▾', () => { this.versionsOpen = !this.versionsOpen; this.drawVersions(host, btn); }, { class: 'btn btn-quiet', 'aria-haspopup': 'true', 'aria-expanded': this.versionsOpen, title: 'Save the work under a name, and come back to any saved version' });
|
||
host.appendChild(btn);
|
||
if (this.versionsOpen) this.drawVersions(host, btn);
|
||
return host;
|
||
}
|
||
|
||
private drawVersions(host: HTMLElement, btn: HTMLElement): void {
|
||
host.querySelector('.versions-menu')?.remove();
|
||
btn.setAttribute('aria-expanded', String(this.versionsOpen));
|
||
if (!this.versionsOpen) { this.versionsOff?.(); this.versionsOff = null; return; }
|
||
const close = () => { this.versionsOpen = false; this.versionsOff?.(); this.versionsOff = null; this.renderToolbar(); };
|
||
const outside = (e: Event) => { if (!host.contains(e.target as Node)) close(); };
|
||
const esc = (e: KeyboardEvent) => { if (e.key === 'Escape') close(); };
|
||
this.versionsOff?.();
|
||
document.addEventListener('mousedown', outside, true); document.addEventListener('keydown', esc, true);
|
||
this.versionsOff = () => { document.removeEventListener('mousedown', outside, true); document.removeEventListener('keydown', esc, true); };
|
||
const here = this.session.currentVersion();
|
||
const unsaved = this.session.hasUnsavedEdits();
|
||
const menu = el('div', { class: 'versions-menu', role: 'menu' });
|
||
add(menu, el('div', { class: 'version-row version-current' + (here ? '' : ' on') },
|
||
el('span', {}, el('b', {}, 'Current'), here ? el('span', { class: 'small muted' }, ` · same as “${here.name}”`) : unsaved ? el('span', { class: 'small muted' }, ' · not saved as a version') : null)));
|
||
const list = this.session.versions();
|
||
if (!list.length) add(menu, el('p', { class: 'small muted version-none' }, 'No saved versions yet.'));
|
||
for (const v of list) {
|
||
add(menu, el('div', { class: 'version-row' + (here?.id === v.id ? ' on' : ''), role: 'menuitem' },
|
||
el('button', { type: 'button', class: 'version-pick', title: 'Make this version the work. Anything the work holds that is not saved yet is saved first.', onClick: () => {
|
||
if (!this.session.restoreVersion(v.id)) { alert('Your current work could not be saved as a version first (the list is full or the browser refused), so nothing was changed. Delete a version and try again.'); return; }
|
||
this.versionsOpen = false; this.versionsOff?.(); this.versionsOff = null; this.versionsChanged();
|
||
} }, el('span', { class: 'version-name' }, v.name), el('span', { class: 'small muted' }, `${this.versionTime(v.at)} · ${AREAS[v.area].name}${v.auto ? ' · automatic' : ''}`)),
|
||
button('Rename…', () => { const n = prompt('Name this version', v.name); if (n && this.session.renameVersion(v.id, n)) this.renderToolbar(); }, { class: 'btn btn-small btn-quiet' }),
|
||
button('Delete…', () => { if (confirm(`Delete the version “${v.name}”?`)) { this.session.deleteVersion(v.id); this.renderToolbar(); } }, { class: 'btn btn-small btn-quiet' })));
|
||
}
|
||
if (storagePressure().nearlyFull) add(menu, el('p', { class: 'small version-warn' }, 'This browser’s storage is nearly full. Delete versions you do not need, or download your work (Share → Download) to keep it elsewhere.'));
|
||
add(menu, el('div', { class: 'version-row version-save' }, button('Save version…', () => {
|
||
const n = prompt('Name this version', `Version ${list.length + 1}`);
|
||
if (!n) return;
|
||
const r = this.session.saveVersion(n);
|
||
if (!r.ok) { alert(r.reason === 'cap' ? 'This work already has 50 saved versions. Delete one first.' : 'The browser would not store another version. Delete some, or download your work with Share → Download.'); return; }
|
||
if (!this.session.state.problem) this.pinWorkspace();
|
||
this.renderToolbar();
|
||
}, { class: 'btn btn-small' })));
|
||
host.appendChild(menu);
|
||
}
|
||
|
||
/** Work from a link or a file just got its workspace id: put it in the address so a reload finds the same work and its versions. */
|
||
private pinWorkspace(): void {
|
||
void encodeState(this.session.state).then((blob) => { history.replaceState(null, '', `${location.href.split('#')[0]}${routeFor({ kind: 'shared', area: this.area.id, blob })}`); });
|
||
}
|
||
|
||
private helpDialog(): void {
|
||
const dlg = el('dialog', { class: 'share' });
|
||
const row = (k: string, what: string) => [el('span', {}, ...k.split(' ').map((x, i) => [i ? ' ' : null, el('kbd', {}, x)])), el('span', {}, what)];
|
||
add(dlg, el('h3', {}, 'Getting around'),
|
||
el('p', { class: 'small muted' }, 'Each pane is one way of writing the same procedure. lingo and matho (equations, written in LaTeX) lower to pseudo; speco is proved against pseudo; Mojo steps through Programming+\'s interpreter and is compiled and run by the real Mojo compiler on godbolt.org (Ctrl+Enter); x86-64 is its own program, stepped on a model machine. The right column always shows the stepper and the variables; its tabs offer only what applies to the pane. The dock below holds the output, the problems, and the compiler\'s answer.'),
|
||
el('div', { class: 'keys' },
|
||
...row('Ctrl Enter', 'run to the end, or compile'), ...row('→ ←', 'one step forward or back'), ...row('Shift →', 'next pass of the loop you are in'), ...row('Home End', 'first or last step'),
|
||
...row('Space', 'play or pause'), ...row('B', 'run to the next breakpoint (click a line number to set one)'), ...row('P', 'predict mode: say what the next step writes before you take it'),
|
||
...row('Tab', 'indent; Shift+Tab outdents'), ...row('Ctrl /', 'comment the line out, or back in'), ...row('Ctrl F', 'find and replace in the editor'), ...row('Ctrl G', 'go to a line'), ...row('Ctrl Z Y', 'undo and redo')),
|
||
el('div', { class: 'share-actions' }, button('Close', () => dlg.close(), { class: 'btn' })));
|
||
document.body.appendChild(dlg);
|
||
dlg.addEventListener('close', () => dlg.remove());
|
||
dlg.showModal();
|
||
}
|
||
|
||
private reload(): void {
|
||
for (const [lang, ed] of this.editors) ed.value = this.session.source(lang);
|
||
this.showPane(this.session.state.lang);
|
||
this.refreshDiagnostics();
|
||
}
|
||
|
||
/* ---------- save, load, share ---------- */
|
||
|
||
private fileName(): string { return `${(this.session.state.title || this.session.state.problem || 'procedure').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')}.pplus.json`; }
|
||
|
||
private download(withVersions = false): void {
|
||
// the saved versions travel in the same file when asked: Open… puts them back (a link never carries them)
|
||
const versions = withVersions ? exportVersions(this.session.versionKey()) : [];
|
||
const state = withVersions && versions.length && !this.session.state.problem && !this.session.state.workspace ? { ...this.session.state, workspace: newWorkspaceId() } : this.session.state;
|
||
const data = JSON.stringify({ pplus: 1, savedAt: new Date().toISOString(), state, ...(versions.length ? { versions } : {}) }, null, 2);
|
||
const blob = new Blob([data], { type: 'application/json' });
|
||
const url = URL.createObjectURL(blob);
|
||
const a = el('a', { href: url, download: this.fileName() });
|
||
document.body.appendChild(a); a.click(); a.remove();
|
||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||
}
|
||
|
||
private openFile(): void {
|
||
const input = el('input', { type: 'file', accept: '.json,application/json', style: { display: 'none' } });
|
||
input.addEventListener('change', async () => {
|
||
const f = input.files?.[0];
|
||
if (!f) return;
|
||
try {
|
||
if (f.size > LIMITS.stateBytes) throw new StateError(`That file is larger than Programming+ opens (${Math.round(f.size / 1024).toLocaleString('en-US')} kB; the most is ${Math.round(LIMITS.stateBytes / 1024)} kB).`);
|
||
const { state: st, versions: saved } = readStateFile(await f.text());
|
||
st.problem = undefined; // a loaded file is its own thing; it does not overwrite a catalog problem's saved edits
|
||
st.title = st.title || f.name.replace(/\.pplus\.json$|\.json$/, '');
|
||
// its saved versions go into the list for this work (never over a version with the same id)
|
||
if (saved.length && !st.workspace) st.workspace = newWorkspaceId();
|
||
if (saved.length) importVersions(versionKey(st), saved);
|
||
this.session.adopt(st);
|
||
this.reload();
|
||
location.hash = routeFor({ kind: 'shared', area: this.area.id, blob: await encodeState(st) });
|
||
} catch (e: any) {
|
||
alert(e instanceof StateError ? e.message : `That file did not open as a Programming+ state: ${e?.message || e}`);
|
||
}
|
||
});
|
||
document.body.appendChild(input); input.click(); input.remove();
|
||
}
|
||
|
||
private async share(): Promise<void> {
|
||
const blob = await encodeState(this.session.state);
|
||
const base = location.href.split('#')[0];
|
||
const appLink = `${base}${routeFor({ kind: 'shared', area: this.area.id, blob })}`;
|
||
const dlg = el('dialog', { class: 'share' });
|
||
const row = (label: string, value: string) => {
|
||
const inp = el('input', { class: 'input mono', readOnly: true, value });
|
||
return el('div', { class: 'share-row' }, el('label', {}, label), inp, button('Copy', async (e) => { await copyText(value); (e.target as HTMLButtonElement).textContent = 'Copied'; }, { class: 'btn btn-small' }));
|
||
};
|
||
const EMBED_LABEL: Record<string, string> = { playground: 'the whole playground, as you have it', asm: 'machine', life: 'lifetimes', compiler: 'compiler (Mojo)' };
|
||
const embedView = el('select', { class: 'select', 'aria-label': 'Embed which view' }, ...EMBED_VIEWS.map((v) => el('option', { value: v, selected: v === 'playground' }, EMBED_LABEL[v] ?? ((LANG_NAMES as any)[v] ? `${(LANG_NAMES as any)[v]} pane` : v))));
|
||
const withVersions = el('input', { type: 'checkbox', checked: true }) as HTMLInputElement;
|
||
const embedRow = el('div', { class: 'share-row' });
|
||
const quartoRow = el('div', { class: 'share-row' });
|
||
const renderEmbed = () => {
|
||
clear(embedRow); clear(quartoRow);
|
||
const view = embedView.value;
|
||
const tall = view === 'playground' ? 720 : 520;
|
||
const url = `${base}${routeFor({ kind: 'embed', view: view as any, blob, params: new URLSearchParams() })}`;
|
||
const snippet = `<iframe src="${url}" width="100%" height="${tall}" style="border:1px solid #ccc;border-radius:8px" loading="lazy" title="Programming+"></iframe>`;
|
||
// the Quarto extension's shortcode for the same state: this layout, panes, build and step, on any page
|
||
const title = this.session.state.title || PROBLEMS.find((p) => p.id === this.session.state.problem)?.title;
|
||
// the title comes from the state, which anyone can write: it must not end the shortcode in the author's page
|
||
const titled = title && shortcodeTitle(title) ? ` title="${shortcodeTitle(title)}"` : '';
|
||
const shortcode = view === 'playground'
|
||
? `{{< pplus-playground state="${blob}" height="${tall}"${titled} >}}`
|
||
: `{{< pplus-embed state="${blob}" view="${view}"${titled} >}}`;
|
||
add(embedRow, el('label', {}, 'embed'), el('input', { class: 'input mono', readOnly: true, value: snippet }), button('Copy', async (e) => { await copyText(snippet); (e.target as HTMLButtonElement).textContent = 'Copied'; }, { class: 'btn btn-small' }));
|
||
add(quartoRow, el('label', {}, 'Quarto'), el('input', { class: 'input mono', readOnly: true, value: shortcode }), button('Copy', async (e) => { await copyText(shortcode); (e.target as HTMLButtonElement).textContent = 'Copied'; }, { class: 'btn btn-small' }),
|
||
el('a', { class: 'small', href: '#/quarto', target: '_blank', rel: 'noopener', title: 'Every shortcode of the Quarto extension, and the views it renders into a page' }, 'more ways ↗'));
|
||
};
|
||
embedView.addEventListener('change', renderEmbed);
|
||
renderEmbed();
|
||
add(dlg, el('h3', {}, 'Share this exact state'),
|
||
el('p', { class: 'small muted' }, `${blob.length} characters in the link. The link carries every pane, the call, the setup, the chosen language, the layout, and the step you are on.`),
|
||
row('open in Programming+', appLink),
|
||
this.session.provenance() || this.session.compileBadge()
|
||
? el('div', { class: 'share-row' }, el('label', {}, 'the Mojo'), el('span', { class: 'share-badges' }, ...mojoBadges(this.session)),
|
||
el('span', { class: 'small muted' }, this.session.provenance() ? 'The label stays with the Mojo wherever it is shown. ' : '', 'Compile results stay in this browser: a link never carries them.')) : null,
|
||
el('div', { class: 'share-row' }, el('label', {}, 'embed which view'), embedView),
|
||
embedRow,
|
||
quartoRow,
|
||
el('div', { class: 'share-row' }, el('label', {}, 'as a file'), el('span', { class: 'small muted' }, `${this.fileName()} holds the same state; Open… loads it back, here or on another machine.`), button('Download', () => this.download(withVersions.checked), { class: 'btn btn-small' })),
|
||
this.session.versions().length ? el('div', { class: 'share-row' }, el('label', {}, 'versions'), el('label', { class: 'small' }, withVersions, ` Include my ${this.session.versions().length} saved version${this.session.versions().length === 1 ? '' : 's'} in the file (a link never carries them)`)) : null,
|
||
el('div', { class: 'share-actions' }, button('Close', () => dlg.close(), { class: 'btn' })));
|
||
document.body.appendChild(dlg);
|
||
dlg.addEventListener('close', () => dlg.remove());
|
||
dlg.showModal();
|
||
}
|
||
|
||
/* ---------- hooks for the views ---------- */
|
||
|
||
private hooks(): PanelHooks {
|
||
return {
|
||
reveal: (lang, line) => {
|
||
this.setNarrow('code');
|
||
if (lang !== this.session.state.lang) { this.session.setLang(lang); this.showPane(lang); }
|
||
const ed = this.editors.get(lang)!;
|
||
ed.scrollToLine(line);
|
||
ed.setDecorations({ linked: new Set([line]) });
|
||
setTimeout(() => ed.setDecorations({ linked: undefined }), 1200);
|
||
},
|
||
fix: (lang, f: QuickFix) => { this.editors.get(lang)!.applyFix(f); },
|
||
};
|
||
}
|
||
}
|