In the browser

Plain JavaScript

createAnswer draws into any element, with no framework. Push the text as it arrives and end it when it's done.

View as Markdown
Terminal
npm install @morphscreen/web
Terminal
pnpm add @morphscreen/web
Terminal
yarn add @morphscreen/web
Terminal
bun add @morphscreen/web
src/main.ts
import { createAnswer, loadCore } from "@morphscreen/web";
import "@morphscreen/web/morphscreen.css";
import wasm from "@morphscreen/web/morphscreen.wasm?url";
import { SAMPLE } from "./sample";

const core = await loadCore(wasm);
const answer = createAnswer(document.querySelector<HTMLElement>("#answer")!, { core });

// Your server's stream goes here; this feeds a saved answer in pieces.
for (let i = 0; i < SAMPLE.length; i += 24) {
  answer.push(SAMPLE.slice(i, i + 24));
  await new Promise((r) => setTimeout(r, 10));
}
answer.end();
document.body.dataset.done = "yes";
index.html
<!doctype html>
<html lang="en">
  <head><meta charset="utf-8"><title>MorphScreen with Vite</title></head>
  <body>
    <div id="answer"></div>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>

createAnswer returns the answer: push(text) for each piece, end() when it's done, html() for the finished answer as HTML, applyState(states) to set what the reader did, and destroy(). The web SDK reference has its options.