treehouse/static/js/components/literate-programming.js

291 lines
9.1 KiB
JavaScript
Raw Normal View History

2024-03-02 20:53:44 +01:00
import { CodeJar } from "treehouse/vendor/codejar.js";
import { compileSyntax, highlight } from "treehouse/components/literate-programming/highlight.js";
2024-02-16 22:01:19 +01:00
const loggingEnabled = false;
function log(...message) {
if (loggingEnabled) {
console.log("[lp]", ...message);
}
}
2024-02-16 22:01:19 +01:00
let literatePrograms = new Map();
function getLiterateProgram(name) {
if (literatePrograms.get(name) == null) {
literatePrograms.set(name, {
2024-02-17 14:56:17 +01:00
frames: [],
2024-02-16 22:01:19 +01:00
onChanged: [],
2024-02-17 14:56:17 +01:00
outputCount: 0,
nextOutputIndex() {
2024-02-18 23:37:31 +01:00
return this.outputCount++;
},
2024-02-16 22:01:19 +01:00
});
}
return literatePrograms.get(name);
}
2024-02-20 23:30:36 +01:00
function getLiterateProgramWorkerCommands(name, count) {
2024-02-17 14:56:17 +01:00
let commands = [];
2024-02-16 22:01:19 +01:00
let literateProgram = getLiterateProgram(name);
2024-02-20 23:30:36 +01:00
for (let i = 0; i < count; ++i) {
let frame = literateProgram.frames[i];
2024-02-17 14:56:17 +01:00
if (frame.mode == "input") {
commands.push({
kind: "module",
source: frame.textContent,
language: frame.language,
kernelParameters: frame.kernelAttributes,
});
2024-02-17 14:56:17 +01:00
} else if (frame.mode == "output") {
2024-02-18 23:37:31 +01:00
commands.push({ kind: "output" });
2024-02-17 14:56:17 +01:00
}
2024-02-16 22:01:19 +01:00
}
2024-02-20 23:30:36 +01:00
2024-02-17 14:56:17 +01:00
return commands;
2024-02-16 22:01:19 +01:00
}
let compiledSyntaxes = new Map();
2024-02-17 18:01:17 +01:00
async function getCompiledSyntax(language) {
if (compiledSyntaxes.has(language)) {
return compiledSyntaxes.get(language);
} else {
let json = await (await fetch(TREEHOUSE_SYNTAX_URLS[language])).text();
let compiled = compileSyntax(JSON.parse(json));
compiledSyntaxes.set(language, compiled);
return compiled;
}
}
2024-02-17 18:01:17 +01:00
class InputMode {
2024-02-17 14:56:17 +01:00
constructor(frame) {
this.frame = frame;
2024-02-16 22:01:19 +01:00
getCompiledSyntax(this.frame.language).then((syntax) => {
this.syntax = syntax;
this.highlight();
});
this.codeJar = CodeJar(frame, (frame) => this.highlight(frame));
2024-02-16 22:01:19 +01:00
this.codeJar.onUpdate(() => {
log(`${this.frame.programName} input frame ${this.frame.frameIndex} update`);
2024-02-17 14:56:17 +01:00
for (let handler of frame.program.onChanged) {
handler(frame.programName, frame.frameIndex);
2024-02-16 22:01:19 +01:00
}
});
2024-02-16 22:01:19 +01:00
frame.addEventListener("click", (event) => event.preventDefault());
2024-02-16 22:01:19 +01:00
}
async highlight() {
if (this.syntax == null) return;
highlight(this.frame, this.syntax, (token, span) => {
2024-02-17 21:03:45 +01:00
if (token.kind == "keyword1" && token.string == "export") {
// This is something a bit non-obvious about the treehouse's literate programs
// so let's document it.
span.classList.add("export");
span.title = "This item is exported and visible in code blocks that follow";
}
});
2024-02-16 22:01:19 +01:00
}
}
2024-02-18 23:37:31 +01:00
function messageOutputArrayToString(output) {
return output
.map((x) => {
2024-02-18 23:37:31 +01:00
if (typeof x === "object") return JSON.stringify(x);
else return x + "";
})
.join(" ");
}
2024-02-17 14:56:17 +01:00
class OutputMode {
constructor(frame) {
this.frame = frame;
2024-02-16 22:01:19 +01:00
2024-02-17 14:56:17 +01:00
this.outputIndex = this.frame.program.nextOutputIndex();
2024-02-16 22:01:19 +01:00
2024-02-18 23:37:31 +01:00
this.console = document.createElement("pre");
this.console.classList.add("console");
this.frame.appendChild(this.console);
this.clearConsoleOnNextOutput = false;
2024-02-16 22:01:19 +01:00
2024-02-18 23:37:31 +01:00
this.error = document.createElement("pre");
this.error.classList.add("error");
this.frame.appendChild(this.error);
2024-02-16 22:01:19 +01:00
2024-02-18 23:37:31 +01:00
this.iframe = document.createElement("iframe");
this.iframe.classList.add("hidden");
this.iframe.src = `${TREEHOUSE_SITE}/sandbox`;
this.frame.appendChild(this.iframe);
this.currentEvaluation = new Promise((resolve) => resolve());
this.completeCurrentEvaluation = () => {};
this.evaluationEnqueued = false;
2024-02-18 23:37:31 +01:00
this.iframe.contentWindow.treehouseSandboxInternals = { outputIndex: this.outputIndex };
2024-02-16 22:01:19 +01:00
this.iframe.contentWindow.addEventListener("message", (event) => {
log(
`${this.frame.programName} output frame ${this.frame.frameIndex} (output index ${this.outputIndex}) recv`,
event.data,
);
2024-02-16 22:01:19 +01:00
let message = event.data;
2024-02-18 23:37:31 +01:00
if (message.kind == "ready") {
this.evaluate();
} else if (message.kind == "resize" && message.outputIndex == this.outputIndex) {
this.resize();
2024-02-17 14:56:17 +01:00
} else if (message.kind == "output" && message.outputIndex == this.outputIndex) {
2024-02-18 23:37:31 +01:00
if (message.output.kind == "error") {
this.completeCurrentEvaluation();
2024-02-18 23:37:31 +01:00
this.error.textContent = messageOutputArrayToString(message.output.message);
this.iframe.classList.add("hidden");
} else {
this.addOutput(message.output);
}
} else if (message.kind == "evalComplete") {
this.completeCurrentEvaluation();
2024-02-18 23:37:31 +01:00
this.error.textContent = "";
this.flushConsoleClear();
2024-02-16 22:01:19 +01:00
}
});
2024-02-20 23:32:54 +01:00
if (this.frame.placeholderImage != null) {
this.frame.placeholderImage.classList.add("js", "loading");
2024-02-20 23:32:54 +01:00
}
2024-02-20 23:30:36 +01:00
this.frame.program.onChanged.push((_, inputFrameIndex) => {
if (inputFrameIndex < this.frame.frameIndex) {
this.evaluateWhenPossible();
}
});
}
evaluateWhenPossible() {
if (!this.evaluationEnqueued) {
this.evaluationEnqueued = true;
this.currentEvaluation.then(() => {
this.evaluate();
this.evaluationEnqueued = false;
});
}
2024-02-18 23:37:31 +01:00
}
evaluate() {
log(`${this.frame.programName} output frame ${this.frame.frameIndex} evaluate`);
this.currentEvaluation = new Promise((resolve) => {
this.completeCurrentEvaluation = resolve;
});
2024-02-18 23:37:31 +01:00
this.requestConsoleClear();
this.iframe.contentWindow.postMessage({
2024-02-16 22:01:19 +01:00
action: "eval",
input: getLiterateProgramWorkerCommands(
this.frame.programName,
this.frame.frameIndex + 1,
),
2024-02-16 22:01:19 +01:00
});
2024-02-17 14:56:17 +01:00
}
2024-02-16 22:01:19 +01:00
2024-02-18 23:37:31 +01:00
clearConsole() {
2024-02-21 23:28:13 +01:00
if (this.frame.placeholderConsole != null) {
this.frame.removeChild(this.frame.placeholderConsole);
this.frame.placeholderConsole = null;
}
2024-02-18 23:37:31 +01:00
this.console.replaceChildren();
}
requestConsoleClear() {
this.clearConsoleOnNextOutput = true;
}
flushConsoleClear() {
if (this.clearConsoleOnNextOutput) {
this.clearConsole();
this.clearConsoleOnNextOutput = false;
2024-02-16 22:01:19 +01:00
}
2024-02-18 23:37:31 +01:00
}
2024-02-16 22:01:19 +01:00
2024-02-18 23:37:31 +01:00
addOutput(output) {
this.flushConsoleClear();
2024-02-16 22:01:19 +01:00
let line = document.createElement("code");
line.classList.add("output");
line.classList.add(output.kind);
2024-02-17 14:56:17 +01:00
// One day this will be more fancy. Today is not that day.
line.textContent = output.message
.map((x) => {
2024-02-17 14:56:17 +01:00
if (typeof x === "object") return JSON.stringify(x);
else return x + "";
})
.join(" ");
2024-02-16 22:01:19 +01:00
2024-02-18 23:37:31 +01:00
this.console.appendChild(line);
2024-02-18 12:10:02 +01:00
}
2024-02-18 00:29:58 +01:00
2024-02-18 23:37:31 +01:00
resize() {
// iframe cannot be `display: none` to get its scrollWidth/scrollHeight.
this.iframe.classList.remove("hidden");
2024-02-18 00:29:58 +01:00
2024-02-20 23:30:36 +01:00
if (this.frame.placeholderImage != null) {
// Fade the iframe in after it becomes visible, and remove the image.
setTimeout(() => this.iframe.classList.add("loaded"), 0);
this.frame.removeChild(this.frame.placeholderImage);
2024-02-21 23:28:13 +01:00
this.frame.placeholderImage = null;
2024-02-20 23:30:36 +01:00
} else {
// If there is no image, don't do the fade in.
this.iframe.classList.add("loaded");
}
2024-02-18 23:37:31 +01:00
let width = this.iframe.contentDocument.body.scrollWidth;
let height = this.iframe.contentDocument.body.scrollHeight;
2024-02-18 00:29:58 +01:00
2024-02-18 23:37:31 +01:00
if (width == 0 || height == 0) {
this.iframe.classList.add("hidden");
} else {
this.iframe.width = width;
this.iframe.height = height;
}
2024-02-18 00:29:58 +01:00
}
}
2024-02-17 14:56:17 +01:00
class LiterateProgram extends HTMLElement {
connectedCallback() {
this.language = this.getAttribute("data-language");
2024-02-17 14:56:17 +01:00
this.programName = this.getAttribute("data-program");
2024-02-20 23:30:36 +01:00
this.frameIndex = this.program.frames.length;
2024-02-17 14:56:17 +01:00
this.program.frames.push(this);
2024-02-21 23:26:53 +01:00
this.placeholderImage = this.getElementsByClassName("placeholder-image")[0];
this.placeholderConsole = this.getElementsByClassName("placeholder-console")[0];
2024-02-20 23:30:36 +01:00
this.kernelAttributes = {};
for (let name of this.getAttributeNames()) {
if (name.startsWith("k-")) {
this.kernelAttributes[name] = this.getAttribute(name);
}
}
2024-02-17 14:56:17 +01:00
this.mode = this.getAttribute("data-mode");
if (this.mode == "input") {
this.modeImpl = new InputMode(this);
} else if (this.mode == "output") {
this.modeImpl = new OutputMode(this);
}
}
get program() {
return getLiterateProgram(this.programName);
2024-02-16 22:01:19 +01:00
}
}
2024-02-17 14:56:17 +01:00
customElements.define("th-literate-program", LiterateProgram);