gram/packages/renderer/tests/mise-en-place-schedule.test.ts

364 lines
12 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { describe, expect, it } from "bun:test";
import { scheduleFor, compile } from "@gram-lang/kitchen";
import { getAST } from "@gram-lang/parser";
import { buildTracks } from "../src/gantt/layout";
import { toGanttHTML, toHTML, toMarkdown, toPrintHTML } from "../src/index";
// The three timelines of a compiled recipe, laid out from its task graph.
const schedulesOf = (c: Parameters<typeof scheduleFor>[0]) => ({
perSection: scheduleFor(c, "perSection")!,
upfront: scheduleFor(c, "upfront")!,
perDay: scheduleFor(c, "perDay")!,
});
const SOURCE = `## Dough ->&dough
Mix @flour{500g} and @water{300ml} in a #bowl.
[Rest] Let the dough rest ~_{2h}.
## Filling ->&filling
Cook @onions{200g}(finely sliced) with @butter{30g}(cut into cubes) in a #pan.
## Assembly
Spread &filling over &dough, then bake for ~{25min}.
`;
const compiled = compile(getAST(SOURCE));
const countOf = (haystack: string, needle: string) =>
haystack.split(needle).length - 1;
const shoppingList = (html: string) =>
html.slice(
html.indexOf('<details class="shopping-list">'),
html.indexOf("</details>"),
);
describe("compiled data used below", () => {
it("has a mise en place for each of the three sections", () => {
// Assembly makes nothing but weighs out the two intermediates it uses.
expect(compiled.miseEnPlace.map((m) => m.section)).toEqual([0, 1, 2]);
});
});
describe("HTML — perSection (default)", () => {
const html = toHTML(compiled);
it("shows no mise en place label: the run sheet says what to take out", () => {
expect(html).not.toContain("section-prep");
expect(html).not.toContain("mise-en-place-session");
expect(html).not.toContain("Mise en place for this section");
});
it("never uses an h4 (gram.css hides it) nor a nested div (it would cut a </div> split)", () => {
expect(html).not.toContain("<h4");
expect(html).not.toMatch(/<div class="section-ingredients">\s*<div/);
});
it("has no up-front block", () => {
expect(html).not.toContain('class="mise-en-place"');
});
it("reads total and idle time from the per-section schedule", () => {
const { totalTime, idleTime } = schedulesOf(compiled).perSection;
expect(html).toContain(fmt(totalTime));
expect(html).toContain(fmt(idleTime));
});
it("is the default", () => {
expect(toHTML(compiled, { miseEnPlace: "perSection" })).toBe(html);
});
});
describe("HTML — upfront", () => {
const html = toHTML(compiled, { miseEnPlace: "upfront" });
it("writes no block of mise en place before the first section", () => {
expect(html).not.toContain("mise-en-place-session");
expect(html).not.toContain("section-prep");
});
it("reads total and idle time from the upfront schedule", () => {
const { totalTime, idleTime } = schedulesOf(compiled).upfront;
expect(html).toContain(fmt(totalTime));
expect(html).toContain(fmt(idleTime));
});
});
describe("both schedules describe the same recipe", () => {
// The setting is about time: the ingredient lists must not depend on it.
const withoutLabels = (html: string) =>
html
.replace(
/<section class="mise-en-place-session">[\s\S]*?<\/section>\s*/g,
"",
)
.replace(/<p class="section-prep">[\s\S]*?<\/p>\s*/g, "")
.replace(/<div class="section-prep">[\s\S]*?<\/div>\s*/g, "");
const listsOf = (html: string) =>
html.slice(
html.indexOf('<div class="instructions"'),
html.lastIndexOf("</div>") + 6,
);
it("keeps every ingredient list identical, apart from the per-section label", () => {
expect(
withoutLabels(listsOf(toHTML(compiled, { miseEnPlace: "upfront" }))),
).toBe(
withoutLabels(listsOf(toHTML(compiled, { miseEnPlace: "perSection" }))),
);
});
it("keeps the shopping list identical", () => {
expect(shoppingList(toHTML(compiled, { miseEnPlace: "upfront" }))).toBe(
shoppingList(toHTML(compiled, { miseEnPlace: "perSection" })),
);
});
it("keeps preparation and active time the same", () => {
const a = toHTML(compiled, { miseEnPlace: "perSection" });
const b = toHTML(compiled, { miseEnPlace: "upfront" });
for (const v of [
fmt(compiled.metrics.preparationTime),
fmt(compiled.metrics.activeTime),
]) {
expect(a).toContain(v);
expect(b).toContain(v);
}
});
});
describe("backend parity", () => {
const backends = {
html: (o: object) => toHTML(compiled, o),
print: (o: object) => toPrintHTML(compiled, o),
markdown: (o: object) => toMarkdown(compiled, o),
};
for (const [name, render] of Object.entries(backends)) {
it(`${name}: the two schedules differ by time only, never by an ingredient list`, () => {
const strip = (out: string) =>
out
.replace(/\d+\sh( \d+\smin)?|\d+\smin\b/g, "T")
.replace(
/<section class="mise-en-place-session">[\s\S]*?<\/section>\s*/g,
"",
)
.replace(/\*\*Mise en place[^\n]*\n\n(- [^\n]*\n)+\n/g, "")
.replace(/<p class="section-prep">[\s\S]*?<\/p>\s*/g, "");
expect(strip(render({ miseEnPlace: "upfront" }))).toBe(
strip(render({ miseEnPlace: "perSection" })),
);
});
}
it("markdown and print show no mise en place by section, just the times", () => {
for (const render of [backends.markdown, backends.print]) {
const out = render({ miseEnPlace: "perSection" });
expect(out).not.toMatch(
/mise-en-place"|## 🔪|section-prep|🔪 Mise en place/,
);
expect(out).not.toContain("Ingredients lookup");
}
});
it("markdown and print take their totals from the chosen schedule", () => {
const up = schedulesOf(compiled).upfront.totalTime;
const per = schedulesOf(compiled).perSection.totalTime;
expect(up).not.toBe(per);
expect(toMarkdown(compiled, { miseEnPlace: "upfront" })).toContain(fmt(up));
expect(toMarkdown(compiled, { miseEnPlace: "perSection" })).toContain(
fmt(per),
);
expect(toPrintHTML(compiled, { miseEnPlace: "upfront" })).toContain(
fmt(up),
);
expect(toPrintHTML(compiled, { miseEnPlace: "perSection" })).toContain(
fmt(per),
);
});
});
describe("Gantt", () => {
const prepBlocks = (html: string) =>
[...html.matchAll(/<div class="time-block[^"]*\bprep\b[^"]*"[^>]*>/g)].map(
(m) => m[0],
);
const attr = (tag: string, name: string) =>
Number(tag.match(new RegExp(`data-${name}="([^"]*)"`))?.[1]);
it("draws one preparation block per section with a cost, in the section colour", () => {
const html = toGanttHTML(compiled);
const blocks = prepBlocks(html);
expect(blocks).toHaveLength(3);
expect(blocks[0]).toContain("section-color-0");
expect(blocks[1]).toContain("section-color-1");
expect(blocks[2]).toContain("section-color-2");
expect(blocks[0]).toContain('data-label="Mise en place"');
});
it("puts the second preparation during the dough's rest, not at T0", () => {
const [first, second] = prepBlocks(toGanttHTML(compiled));
expect(attr(first!, "start")).toBe(0);
expect(attr(second!, "start")).toBeGreaterThan(30);
});
it("puts every preparation at the start in upfront, end to end", () => {
const [first, second] = prepBlocks(
toGanttHTML(compiled, { miseEnPlace: "upfront" }),
);
expect(attr(first!, "start")).toBe(0);
expect(attr(second!, "start")).toBe(attr(first!, "end"));
});
it("spans the chosen schedule's total time", () => {
for (const mode of ["perSection", "upfront"] as const) {
const html = toGanttHTML(compiled, { miseEnPlace: mode });
expect(html).toContain(
`data-max-real-time="${schedulesOf(compiled)[mode].totalTime}"`,
);
}
});
it("describes the preparation in the block's tooltip", () => {
const [first] = prepBlocks(toGanttHTML(compiled));
expect(first).toContain("data-tooltip=");
expect(first).toContain("Ingredients lookup");
});
});
// Day -3: a cream that rests; day -1: a crust made from it, then the pie; the
// last section has no anchor, so it falls on the day itself.
const MULTI_DAY = `## Cream ~{-3d} ->&cream
Whisk @milk{500ml} and @eggs{4}.
[Rest] Chill ~_{12h}.
## Crust ~{-1d} ->&crust
Mix &cream{100g} and @flour{200g}.
## Pie ~{-1d}
Fill with &crust{300g} and bake ~{30min}.
## Serve
Dust with @sugar{10g}.
`;
describe("perDay", () => {
const multi = compile(getAST(MULTI_DAY));
const options = { miseEnPlace: "perDay" } as const;
it("leaves the working days to the run sheet: no block in the recipe", () => {
const html = toHTML(multi, options);
expect(html).not.toContain("mise-en-place-session");
expect(html).not.toContain("Mise en place — D-");
expect(html).not.toContain("section-prep");
expect(toMarkdown(multi, options)).not.toContain("Mise en place — D-");
expect(toPrintHTML(multi, options)).not.toContain("Mise en place — D-");
});
it("marks each day on the Gantt and keeps block ids unique", () => {
const html = toGanttHTML(multi, options);
expect(html).toContain(">D-3<");
expect(html).toContain(">D-1<");
expect(countOf(html, 'class="gantt-marker day-marker"')).toBe(2);
const ids = buildTracks(multi, options).tracks.flatMap((t) =>
t.blocks.map((b) => b.id),
);
expect(ids.some((id) => id.endsWith("_later"))).toBe(true);
expect(new Set(ids).size).toBe(ids.length);
});
});
describe("data without schedules", () => {
it("still renders, without a badge or a block", () => {
const { schedules: _s, miseEnPlace: _m, ...legacy } = compiled;
const html = toHTML(legacy as never);
expect(html).not.toContain("section-prep");
expect(html).not.toContain('class="mise-en-place"');
});
});
// The recipe above has no `formatDuration` override, so the default one applies.
function fmt(minutes: number): string {
const h = Math.floor(minutes / 60);
const m = Math.round(minutes % 60);
// A non-breaking space between each number and its unit.
if (h > 0) return m > 0 ? `${h}\u00A0h ${m}\u00A0min` : `${h}\u00A0h`;
return `${m}\u00A0min`;
}
describe("mise en place wording", () => {
// The preparation card lists each line with its duration in a column of its
// own; the tooltips that have no such column spell it out.
it("does not give a preparation's duration twice on the preparation card", () => {
const html = toHTML(compiled);
expect(html).toContain('timing-detail-type">Preparation: onions</span>');
expect(html).not.toContain('timing-detail-type">Preparation: onions (+');
});
it("still gives it where there is no column, in the Gantt block's tooltip", () => {
const tooltips = toGanttHTML(compiled).match(/data-tooltip="[^"]*"/g) ?? [];
expect(
tooltips.some((t) => t.includes("Preparation: onions (+ 2\u00A0min)")),
).toBe(true);
});
it("puts no space before the colon in English, one in French", () => {
const en = toHTML(compiled, { lang: "en" });
const fr = toHTML(compiled, { lang: "fr" });
expect(en).toContain("Preparation: onions");
expect(fr).toContain("Préparation : onions");
expect(en).not.toContain("Preparation : ");
});
it("writes the gathering unit with the caller's duration format", () => {
const html = toHTML(compiled, { formatDuration: (m) => `${m} min` });
expect(html).toContain("(2 × 1 min)");
expect(html).not.toContain("× 1min");
});
});
describe("the total time tooltip", () => {
// Over a day: the pill rounds to the hour, the tooltip must still add up.
const LONG = `## Batter
Mix @milk{1l} with @flour{250g} ~{14min}.
[Rest] Let it rest in the fridge ~_{24h}.
## Bake
Bake ~{60min}.
`;
const html = toHTML(compile(getAST(LONG)), { lang: "en" });
const tooltip =
/timing-pill total[\s\S]*?<div class="timing-tooltip">([\s\S]*?)<\/div>\s*<\/span>/.exec(
html,
)?.[1] ?? "";
const values = [...tooltip.matchAll(/timing-val">(?:<strong>)?([^<]+)/g)].map(
(m) => m[1]!,
);
const minutes = (text: string) =>
Number(/(\d+)\sh\b/.exec(text)?.[1] ?? 0) * 60 +
Number(/(\d+)\smin/.exec(text)?.[1] ?? 0);
it("shows the pill in days, the breakdown in hours and minutes", () => {
expect(html).toMatch(/<span class="timing-text">1\sd( \d\sh)?<\/span>/);
expect(tooltip).not.toMatch(/\d\sd\b/);
});
it("adds its parts up to the total it ends on", () => {
const parts = values.filter((v) => v.startsWith("+"));
const total = values.find((v) => v.startsWith("="))!;
expect(parts.length).toBe(3);
expect(parts.reduce((sum, v) => sum + minutes(v), 0)).toBe(minutes(total));
});
});