89 lines
2.3 KiB
JavaScript
89 lines
2.3 KiB
JavaScript
import "./style.css";
|
|
import { registerViewer } from "@boardgamers/protocol/viewer";
|
|
import { createTutorial } from "@boardgamers/protocol/tutorial";
|
|
import { mountTutorialGuide } from "@boardgamers/protocol/tutorial/dom";
|
|
import { stripSecret } from "../engine/index.js";
|
|
import { chapters } from "./tutorials.js";
|
|
import { mountGame } from "./ui.js";
|
|
export async function mountLesson(target, options) {
|
|
const chapter = chapters[options.chapter];
|
|
if (!chapter) throw new Error("Unknown tutorial chapter.");
|
|
let storage;
|
|
try {
|
|
storage = window.localStorage;
|
|
} catch {}
|
|
const tutorial = await createTutorial({
|
|
...chapter,
|
|
storage,
|
|
onProgress: options.onProgress,
|
|
});
|
|
const ui = mountGame(target, { onMove: (m) => tutorial.play(m) });
|
|
ui.setPlayer(0);
|
|
let previousStep;
|
|
const off = tutorial.subscribe((snapshot) => {
|
|
if (previousStep !== snapshot.step) {
|
|
ui.closeModal();
|
|
previousStep = snapshot.step;
|
|
}
|
|
ui.render(stripSecret(snapshot.state));
|
|
ui.setEnabled(
|
|
!snapshot.busy && !snapshot.completed && !snapshot.canContinue,
|
|
);
|
|
});
|
|
const removeGuide = mountTutorialGuide(ui.guide, tutorial, {
|
|
nextChapter: options.nextChapter,
|
|
});
|
|
return () => {
|
|
off();
|
|
removeGuide();
|
|
tutorial.destroy();
|
|
ui.destroy();
|
|
};
|
|
}
|
|
registerViewer(
|
|
"primordialSoup",
|
|
(ctx) => {
|
|
let pending, timeout;
|
|
const ui = mountGame(ctx.target, {
|
|
onMove: (m) =>
|
|
new Promise((resolve, reject) => {
|
|
pending = { resolve, reject };
|
|
timeout = setTimeout(() => {
|
|
pending = undefined;
|
|
reject(
|
|
new Error(
|
|
"Waiting for the server. Refresh if your move has not appeared.",
|
|
),
|
|
);
|
|
}, 15000);
|
|
ctx.move(m);
|
|
}),
|
|
});
|
|
return {
|
|
onPlayer(player) {
|
|
ui.setPlayer(player.index);
|
|
},
|
|
onState(state) {
|
|
ui.render(state);
|
|
if (pending) {
|
|
clearTimeout(timeout);
|
|
pending.resolve();
|
|
pending = undefined;
|
|
}
|
|
},
|
|
onError(error) {
|
|
if (pending) {
|
|
clearTimeout(timeout);
|
|
pending.reject(error);
|
|
pending = undefined;
|
|
}
|
|
},
|
|
destroy() {
|
|
clearTimeout(timeout);
|
|
pending?.resolve();
|
|
ui.destroy();
|
|
},
|
|
};
|
|
},
|
|
{ tutorial: mountLesson },
|
|
);
|