Skip to content

Rendering and output formats (@gram-lang/renderer)

Once a recipe has been parsed by @gram-lang/parser, scheduled by @gram-lang/kitchen, and enriched by @gram-lang/analyzer, it is ready for visual presentation.

The @gram-lang/renderer package consumes this complete JSON object and formats it into structured Markdown, semantic HTML, plain text, or a standalone print document.

The renderer supports five primary export targets:

Generates standardized GitHub Flavored Markdown (GFM) containing a formatted shopping list, equipment inventory, numbered instructions, footnotes ([^1]), gross purchasing mass badges, and an optional nutritional panel (## Nutrition). This format integrates cleanly with static site generators (Astro, VitePress, Hugo) and personal knowledge management tools (Obsidian).

Produces clean, semantic HTML markup. The HTML formatter employs an inversion of control architecture, allowing you to inject custom CSS classes (e.g. Tailwind CSS) and SVG icon sets to match your host application’s design system.

Generates a complete, self-contained <!DOCTYPE html> document featuring an inlined print stylesheet (A4 format, page-break-aware sections) and standalone vector icons. Designed for direct browser printing without external stylesheet or asset dependencies. While custom classes cannot be injected into toPrintHTML, formatting helpers (formatDuration, formatFraction, hideStepQty) remain fully supported.

Formats the recipe for terminals and plain-text exports (gram view, gram export --format text), with a title box, portions and timing summary, shopping list, cookware, and numbered steps. All labels come from @gram-lang/i18n, and callers can pass textStyle hooks to apply ANSI colors without altering alignment width.

5. The run sheet (runSheetToText, runSheetToMarkdown, runSheetToHTML, runSheetToPrintHTML)

Section titled “5. The run sheet (runSheetToText, runSheetToMarkdown, runSheetToHTML, runSheetToPrintHTML)”

The canonical view of the schedule, just as the recipe view is the canonical view of cooking instructions. It faithfully presents the structures computed by the engine (runSheet() from @gram-lang/scheduler): the calendar breakdown of days, and for each active kitchen visit, the mise en place, the steps of each section written out with their temperatures and timers, and ongoing passive processes, alongside anticipation margins and adjusted rest periods. Text labels follow the configured lang option.

This renderer serves as a reference implementation without prescribing a single UI approach. Some display rules are view-level choices: a visit ends when a passive rest reaches at least one hour (VISIT_GAP_MINUTES, defined in the scheduler because it shapes schedule data), an anticipation margin is displayed only when reaching at least 15 minutes, and the mise en place and the steps are extracted directly from the compiled recipe. To allow custom interfaces to reuse this logic without duplicating it, four helper utilities are exported:

  • visitKit(data, sections, options): extracts and aggregates ingredients required by the sections (with sum breakdowns), preparations from earlier visits, in-stock bases, and necessary cookware. The run sheet itself composes it from three parts, following the mise en place mode carried by the sheet.
  • sectionProgram(data, section, stepIndexes): gives, for a section during a visit, its title and the first and last step it covers, as well as the source file for imported sections.
  • sectionSteps(data, section, stepIndexes, options): writes out the steps a section does in a visit, numbered as the recipe view numbers them, as HTML, Markdown and plain text, without icons. A standalone note goes with the step that follows it.
  • describeRunSheet(): converts the complete schedule into a structured text representation (RunSheetModel), powering the four formatters and the CLI calendar export.

Standard recipe views (toHTML, toMarkdown, toPrintHTML, toText) focus exclusively on culinary execution (the how) without exposing the timeline; to render the schedule as a dedicated view, call the runSheetTo* formatters (or render("runSheet", ...)). See Build a custom UI to render a custom planning view directly from the underlying data.

The miseEnPlace option ("perSection" by default, "upfront", or "perDay") and the rests option ("shortest" by default, "balanced", "longest") choose the timeline whose total and idle durations the document headers show (see The three mise en place strategies).

Internally, the recipe formatters (Markdown, HTML, Print HTML, Plain Text) delegate content iteration to a central orchestrator (renderRecipe in traversal.ts), which interfaces with each format’s RenderBackend implementation. This architecture guarantees strict structural parity: titles, metadata, ingredient lists, cookware, instructions, footnotes, and nutritional breakdowns are traversed in the exact same sequence across all output targets. The run sheet has its own dedicated traversal, as it follows chronological time rather than the recipe’s section sequence.

import { toMarkdown, toHTML } from '@gram-lang/renderer';

// Assuming `recipe` originates from @gram-lang/kitchen or @gram-lang/analyzer
const recipe = {
  title: "Simple Crepes",
  metrics: { preparationTime: 5, activeTime: 10 },
  // Reference schedule consumed by the renderer
  schedule: {
    miseEnPlace: "perSection",
    rests: "shortest",
    totalTime: 30,
    idleTime: 15,
    blocks: [],
    days: [],
  },
  shopping_list: [
    { id: "flour", name: "flour", qty: 200, unit: "g" }
  ],
  sections: [
    {
      title: "Preparation",
      ingredients: [],
      cookware: [],
      steps: [
        { type: "step", content: ["Whisk everything together."] }
      ]
    }
  ]
};

// 1. Standard Markdown rendering
const markdown = toMarkdown(recipe);

// 2. Customized HTML rendering (Inversion of Control)
const html = toHTML(recipe, {
  icons: {
    clock: '<svg class="icon-clock">...</svg>',
    fire: '<svg class="icon-fire">...</svg>'
  },
  classes: {
    recipeTitle: "text-2xl font-bold custom-title",
    recipeMeta: "flex gap-2 text-gray-500"
  }
});

The RendererOptions interface also provides bakersMathOnly (displaying baker’s percentages without absolute quantities), hideStepQty (hiding in-step ingredient quantities), and renderId. The latter prefixes anchor identifiers (e.g. "note-1") to prevent HTML ID collisions when multiple recipes share a single web page.

  • Fraction formatting: Formats floating-point values into readable vulgar fractions (0.5 → "1/2", 0.33 → "1/3"). Output consists of clean ASCII character sequences (1/2), avoiding single-glyph Unicode fractions.
  • Escaping and security: All user-provided strings are sanitized. Output produced by toHTML and toPrintHTML is safe for direct DOM insertion. The toMarkdown formatter explicitly escapes < and & (converting them to &lt; and &amp;), preventing malicious HTML execution during downstream markdown parsing.
  • Duration formatting: Converts raw minute integers into natural duration strings in the display language, rounded more coarsely as they grow: to the second below an hour, to the minute up to a day, to the hour beyond (90 → 1 h 30 min, 1506 → 1 d 1 h, with a non-breaking space between number and unit).
  • Bundled CSS: The package distributes @gram-lang/renderer/gram.css: the light and dark tokens shared by every view, then the styles of each view, scoped to its root element (<article class="gram-recipe">, <section class="gram-run-sheet">) so that no rule of one view reaches another. Until 2.0.0 it also ships gantt.css for the deprecated Gantt chart. Print documents embed these rules directly in the document <head>, requiring no external asset fetching.

If you are developing a modern frontend application (React, Vue, Svelte, mobile), relying on @gram-lang/renderer is entirely optional.

The JSON emitted by @gram-lang/analyzer is strongly typed and directly iterable: looping over recipe.sections and recipe.shopping_list meets most UI requirements. For sophisticated edge cases (alternative ingredient groups, composites, baker’s percentages, or purchasingMass), the internal implementation of @gram-lang/renderer serves as an established reference pattern.