Skip to content

Build a custom UI from JSON

If you are developing a modern web application (using React, Vue, Svelte, or Next.js, for instance), you can directly consume the compiled JSON data produced by Gram and connect it to your own user interface components.

While the parser initially produces a raw Abstract Syntax Tree (AST), @gram-lang/kitchen and @gram-lang/analyzer transform it into a structured, render-ready JSON object. This guide explains how to extract this data and design your UI around two core pillars: rendering the recipe view and presenting time (relative execution timeline or real-world calendar schedule).

  1. Gram is designed to run in any JavaScript environment (Node.js, Edge runtimes, or directly in the browser). To obtain the complete, enriched JSON representation of a recipe, combine its three foundational packages:

    import { getAST } from '@gram-lang/parser';
    import { compile } from '@gram-lang/kitchen';
    import { analyze } from '@gram-lang/analyzer';
    
    function getRecipeData(sourceCode: string) {
      // 1. Parse text into an AST
      const ast = getAST(sourceCode);
      
      // 2. Compile into structured sections and compute default schedule
      const compiled = compile(ast);
    
      // 3. Enrich with culinary calculations (masses, yields, nutrition)
      const analyzed = analyze(compiled, myDatabase);
    
      return analyzed.result;
    }

    The resulting JSON object encapsulates the entire recipe deterministically:

    • title (string): The recipe name (defined by # Title).
    • meta (object): Key-value metadata (e.g. author, portions, yield).
    • shopping_list (array): Aggregated list of all ingredients, ready for procurement.
    • sections (array): Cooking instructions divided into self-contained sections.
    • metrics (object): Overall metrics (preparationTime, activeTime in minutes, as well as mass and nutrition when analyzed).
    • miseEnPlace (array): Operational preparation breakdown and durations for each section.
    • tasks (object): Complete task dependency graph with durations, used by the scheduler.
    • schedule (object): Default schedule calculated from tasks (totalTime, idleTime, scheduled blocks, and working-day breakdown).
  2. Render the recipe: ingredients and instructions

    Section titled “Render the recipe: ingredients and instructions”

    Each entry in sections holds its own lists of ingredients (ingredients), cookware (cookware), and instructions (steps).

    {
      "title": "Dough",
      "ingredients": [ ... ],
      "cookware": [ ... ],
      "steps": [
        {
          "type": "step",
          "action": "Mix",
          "content": [
            "The ",
            {
              "id": "flour",
              "_usageId": "1",
              "qty": 500,
              "unit": "g",
              "normalizedMass": 500
            },
            " and ",
            {
              "id": "water",
              "_usageId": "2",
              "qty": 350,
              "unit": "ml"
            },
            "."
          ]
        }
      ]
    }

    Rendering this in your UI consists of mapping over these arrays within your front-end components.

    Here is an implementation illustrating how to render steps and their inline tokens with React:

    function RecipeStep({ step }) {
      // Comment node
      if (step.type === 'comment') {
        return <p className="text-gray-500 italic">{step.value}</p>;
      }
    
      // Standard instruction step
      if (step.type === 'step') {
        return (
          <li>
            {step.action && <strong>[{step.action}] </strong>}
            {step.content.map((token, i) => (
              <StepToken key={i} token={token} />
            ))}
          </li>
        );
      }
    }
    
    // Polymorphic token component
    function StepToken({ token, cookwareRegistry }) {
      // 1. Strings represent plain text
      if (typeof token === 'string') {
        return <span>{token}</span>;
      }
    
      // 2. Ingredients and cookware are objects without a 'type' field, identified by 'id'.
      if (!token.type && token.id) {
        const isCookware = !!cookwareRegistry[token.id];
        
        if (isCookware) {
          return <span className="text-blue-600 font-bold">{token.id}</span>;
        } else {
          return <span className="text-green-600 font-bold">{token.id} ({token.qty}{token.unit})</span>;
        }
      }
    
      // 3. Other tokens (timers, temperatures) have an explicit 'type' discriminator
      switch (token.type) {
        case 'timer':
          return <span className="bg-yellow-100 px-1 rounded">{token.quantity?.value}{token.unit}</span>;
        case 'temperature':
          return <span className="text-red-600">{token.quantity?.value}{token.unit}</span>;
        case 'checkpoint': // A target state (`={ribbon stage}`, 1.5)
          return <strong>{token.state}{token.note && ` (${token.note})`}</strong>;
        default:
          return null;
      }
    }

    By connecting each type discriminator to your own components, you maintain full control over styling, accessibility, and interactivity.

  3. Present time: relative timeline or calendar schedule

    Section titled “Present time: relative timeline or calendar schedule”

    Gram offers two complementary approaches to represent time depending on your application’s user experience:

    1. The relative execution timeline: expresses time in minutes starting from $t = 0$. Ideal for an in-kitchen live cooking mode or a continuous step timeline.
    2. The calendar schedule: projects steps onto concrete dates, wall-clock times, and distinct kitchen visits. Ideal for meal planning and production organization.

    Option A: Relative timeline (minutes from start)

    Section titled “Option A: Relative timeline (minutes from start)”

    To render a continuous timeline, use the blocks in recipe.schedule.blocks. If you want to explore different scheduling strategies dynamically without recompiling the recipe, pass recipe.tasks directly to layout():

    import { layout } from '@gram-lang/scheduler';
    
    // miseEnPlace: 'perSection' (default), 'upfront' (at the start), or 'perDay' (per day).
    // rests: 'shortest' (default), 'balanced', or 'longest' for passive ranges.
    const { schedule } = layout(recipe.tasks, { miseEnPlace: 'perSection', rests: 'shortest' });
    
    for (const block of schedule.blocks) {
      if (block.kind === 'prep') {
        // Section mise en place: recipe.miseEnPlace details associated items
        const prep = recipe.miseEnPlace.find((m) => m.section === block.section);
        draw('Mise en place', block.start, block.end, prep?.items);
      } else {
        // Active action ('step') or passive rest ('passive')
        const step = recipe.sections[block.section].steps[block.step];
        const label = block.kind === 'passive' ? (block.track ?? 'Passive rest') : step.action;
        draw(label, block.start, block.end);
      }
    }

    All start and end values are expressed in relative minutes. You can let users switch strategies interactively: total recipe time shifts (schedule.totalTime), but active prep work remains invariant (schedule.preparationTime).

    Option B: Real-world calendar schedule (dates and clock times)

    Section titled “Option B: Real-world calendar schedule (dates and clock times)”

    When you have a target serving time and cooking availability (such as cooking only between 8 a.m. and 10 p.m.), the engine projects the recipe onto a real-world calendar using project(), then organizes visits by day and visit using runSheet() :

    import { project, runSheet } from '@gram-lang/scheduler';
    
    const context = {
      serveAt: '2026-10-17T20:00',
      timeZone: 'Europe/Paris',
      availability: { daily: [{ start: '08:00', end: '22:00' }] },
    };
    
    // 1. Project the task graph onto the calendar
    const plan = project([{ graph: recipe.tasks, title: recipe.title }], context);
    
    // 2. Structure the operational schedule into days and visits
    const sheet = runSheet(plan, { graph: recipe.tasks, context });

    The data structure returned by runSheet() is identical to the output of gram plan --format json. It allows you to build a full calendar view in about thirty lines of TypeScript:

    const clock = (local?: string) => local?.slice(11, 16) ?? '';
    const hours = (minutes: number) => `${Math.round(minutes / 60)} h`;
    
    function planningView(sheet: ReturnType<typeof runSheet>, recipe: { sections: { title: string | null }[] }): string {
      const [planned] = sheet.recipes;
      return planned.days
        .map((day) => {
          const visits = day.visits
            .map((visit, k) => {
              const sections = visit.sections.map((s) => recipe.sections[s].title).join(', ');
              const threads = day.threads
                .filter((t) => t.visit === k)
                .map((t) => `<li>${t.task}: ${hours(t.planned)} unattended</li>`)
                .join('');
              const margin = visit.window ? ` (could start as early as ${clock(visit.window.earliestLocal)})` : '';
              return `<li><b>${clock(visit.startLocal)}–${clock(visit.endLocal)}</b> ${sections}${margin}<ul>${threads}</ul></li>`;
            })
            .join('');
          return `<section><h3>${day.date ?? `D-${day.daysBefore}`}</h3><ul>${visits}</ul></section>`;
        })
        .join('');
    }
    • day.visits[]: active kitchen visits. Each entry provides start and end (exact minutes before service), startLocal and endLocal (wall-clock timestamps in the target time zone), recipe section indexes (sections), task IDs (tasks), and window / fixedBy indicating scheduling margins.
    • day.threads[]: passive resting processes (proofing, resting, chilling) that continue unattended after a visit (visit is its index within the day), with their planned duration (planned), allowed range (range), and expected completion (toLocal).
    • day.entries[]: ordered sequence of all blocks for the day (active and passive), useful for drawing a detailed custom timeline or day view.
    • sheet.adjustments[] and sheet.diagnostics[]: lists of passive rests that were adjusted to fit your availability, and unresolved scheduling constraints that triggered warnings.