typstream

Worksheets, quizzes and answer keys

Use @typstream/edu to render teachers' documents with numbered questions, hidden answers, a teacher's copy and an answer key, in English, Arabic or Bengali.

@typstream/edu is a Typst vocabulary for teachers' documents: templates (worksheet, quiz, exam, lesson plan, handout), questions with points, answer spaces, answers that only the teacher's copy shows, callouts, rubrics and drawings. Every function renders in both targets, so a quiz looks right as live HTML and as printed pages. This guide goes from adding the plugin to exporting a student's and a teacher's PDF. Every function is listed, with a live example, in the edu vocabulary.

Add the plugin

npm install typstream @typstream/edu
import { edu } from "@typstream/edu";
import { Typstream } from "typstream";

<Typstream source={text} isStreaming={status === "streaming"} plugins={[edu]} />;

To give every document on the page the vocabulary, put it on a provider instead: <TypstreamProvider plugins={[edu]}>. Without React, pass it the same way: mountTypstream(element, { engine, plugins: [edu] }) or engine.open({ plugins: [edu] }).

The plugin brings:

  • The Typst package, mounted as a local package under @typstream/edu:0.1.0. Nothing is downloaded and it needs no package allowlist entry.
  • A preamble that imports every public function, so documents call #question(…) directly, with no #import.
  • Templates your app can apply by name (see Templates).
  • A stylesheet for the HTML its functions write: answer lines, boxes, option letters. It follows the renderer's theme, so dark mode works. Without it the HTML keeps its content but loses its rules and frames.
  • The prompt kit: rules, a function catalogue and example documents for the model. See Prompting the model.

A quiz

A document applies one template on its first line, then writes questions. Each #question is numbered through the document, and its points add up to the total in the header. The answers go into the functions, never into the text:

idle
#show: quiz.with(title: [Fractions Check-in], subject: [Mathematics], grade: [Grade 5])

#question(points: 1)[
  Which fraction is equal to $1/2$?
  #mcq([$2/3$], [$3/6$], [$3/4$], [$5/8$], answer: 2)
]

#question(points: 1)[
  $2/5 + 1/5 =$ #blank(answer: $3/5$)
]

#question(points: 1)[
  #true-false(answer: false)[$3/4$ is smaller than $2/3$.]
]

#question(points: 2)[
  Explain why $4/8$ and $1/2$ are the same amount.
  #answer-lines(count: 2, answer: [Divide the top and bottom of $4/8$ by 4 to get $1/2$.])
]

#answer-key()

Tick Show answers to see the teacher's copy: the correct option in bold, the blank and the lines filled in red, the statement marked, and the answer key listed under the question numbers. The functions used:

FunctionWhat it writesanswer
quizTitle, subject, grade, total points, student fields
questionA numbered question with its points
mcqLettered optionsThe correct option's number, from 1, or an array
blankAn inline blankThe expected answer (content)
true-falseA statement to marktrue or false
answer-linesRuled lines for a written answerA model answer
answer-keyEvery answer, by question number

Others you'll use often: answer-space for working space, matching, answer for a worked solution, callout, rubric, and drawings such as number-line and coordinate-plane. Chemistry is ce: #ce("2H2 + O2 -> 2H2O").

Every parameter has a default and accepts what a stream cut leaves behind, so a half-written #mcq( renders as the options so far instead of failing the compile.

The teacher's copy

Answers appear only when the Typst input showAnswers is "true". Otherwise they produce no output at all, in either target: they aren't hidden with CSS, and they aren't in the PDF's text. A student's copy can't leak them.

So the teacher's copy is the same document compiled with one more input. You don't ask the model again:

import { edu, SHOW_ANSWERS_INPUT } from "@typstream/edu";
import { useState } from "react";
import { Typstream } from "typstream";

export function QuizPreview({ source, isStreaming }: { source: string; isStreaming: boolean }) {
  const [teacher, setTeacher] = useState(false);
  return (
    <>
      <label>
        <input type="checkbox" checked={teacher} onChange={(e) => setTeacher(e.target.checked)} /> Show answers
      </label>
      <Typstream
        source={source}
        isStreaming={isStreaming}
        plugins={[edu]}
        inputs={teacher ? { [SHOW_ANSWERS_INPUT]: "true" } : undefined}
      />
    </>
  );
}

SHOW_ANSWERS_INPUT is the string "showAnswers". Changing inputs recompiles the document in place; the source and the stream are untouched.

Templates

There are two ways to apply a template, and a document should use exactly one.

In the document (the default). The model writes the template line, with the document's own title:

#show: worksheet.with(title: [Adding Fractions], subject: [Mathematics], grade: [Grade 5])

This is what the prompt kit asks for, and the only way to set a title, subject, grade, instructions or language.

From the app. If the teacher picks the document type in your UI and the model writes only the body, pass the template's name:

<Typstream source={body} plugins={[edu]} template="worksheet" />

The template prop applies #show: worksheet with its defaults before the document. Tell the model not to write a template line then: one applied twice renders its header twice.

TemplateFor
worksheetTitle, subject and grade, and name, date and class lines.
quizA worksheet with the total of the questions' points.
examDuration and total points, student fields, an instructions box and a running header.
lesson-planA table of subject, grade, duration, date and teacher; no student fields.
handoutTitle and subtitle, with no student fields.

Every template takes paper ("a4" by default, or "us-letter"). Worksheets, quizzes and exams also take info, the student fields (none for none), and points-label, the word after the points ("marks", say).

Languages

Pass lang to the template, and everything edu writes itself follows the language: field labels, the points word, option letters, true and false, callout and key titles. Arabic and Bengali are supported alongside English, and right-to-left layout follows from the language in both targets.

idle
#show: quiz.with(lang: "ar", title: [المجموعة الشمسية], subject: [العلوم], grade: [الصف الخامس])

#question(points: 1)[
  ما هو أقرب كوكب إلى الشمس؟
  #mcq([الزهرة], [عطارد], [المريخ], [الأرض], answer: 2)
]

#question(points: 2)[
  #true-false(answer: true)[المريخ هو الكوكب الأحمر.]
]
EnglishArabic ("ar")Bengali ("bn")
Option letters(a), (b), (c)(أ), (ب), (ج)(ক), (খ), (গ)
Points1 point, 2 pointsدرجة واحدة, درجتان, 3 درجات1 নম্বর
Directionleft to rightright to leftleft to right

Arabic counts with its own forms for one and two. Other languages get the English words. The Arabic and Bengali fonts are downloaded the first time a document uses them; see Fonts and languages.

Export the student's and teacher's PDFs

Exports compile the document again in final mode with the inputs you give, so one document makes both copies. In React, the exports are on useTypstream():

"use client";
import { edu, SHOW_ANSWERS_INPUT } from "@typstream/edu";
import { Typstream, useTypstream } from "typstream";

const save = (pdf: Uint8Array, name: string) => {
  // TypeScript 5.7+ types Blob parts as ArrayBuffer-backed views.
  const url = URL.createObjectURL(new Blob([pdf as Uint8Array<ArrayBuffer>], { type: "application/pdf" }));
  const link = document.createElement("a");
  link.href = url;
  link.download = name;
  link.click();
  setTimeout(() => URL.revokeObjectURL(url), 0);
};

export function Quiz({ source, isStreaming }: { source: string; isStreaming: boolean }) {
  const t = useTypstream();
  const exportCopy = async (teacher: boolean) => {
    const pdf = await t.exportPdf({ inputs: { [SHOW_ANSWERS_INPUT]: teacher ? "true" : "false" } });
    save(pdf, teacher ? "quiz-teacher.pdf" : "quiz.pdf");
  };
  return (
    <>
      <Typstream ref={t.ref} source={source} isStreaming={isStreaming} plugins={[edu]} />
      <button type="button" disabled={!t.handle || isStreaming} onClick={() => exportCopy(false)}>
        Student PDF
      </button>
      <button type="button" disabled={!t.handle || isStreaming} onClick={() => exportCopy(true)}>
        Teacher PDF
      </button>
    </>
  );
}

Set showAnswers on both exports. An export's inputs go over the component's inputs prop: if the preview is showing answers, a "student" PDF without "false" would too.

On the server, @typstream/node renders the same document. Give it edu's files and preamble:

import { writeFile } from "node:fs/promises";
import { eduFiles, eduPreamble, SHOW_ANSWERS_INPUT } from "@typstream/edu";
import { render } from "@typstream/node";

const options = { files: eduFiles, preamble: eduPreamble };
const student = await render(source, "pdf", options);
const teacher = await render(source, "pdf", { ...options, inputs: { [SHOW_ANSWERS_INPUT]: "true" } });
if (student.ok) await writeFile("quiz.pdf", student.data);
if (teacher.ok) await writeFile("quiz-teacher.pdf", teacher.data);

Exports covers HTML exports, errors and timeouts.

On this page