From a1d9c59268fd682de8c82f927ef3ca28daedccd9 Mon Sep 17 00:00:00 2001 From: abiwab Date: Tue, 29 Sep 2026 11:25:59 +0200 Subject: [PATCH 1/4] fix(renderer): round durations and add timer and fraction helpers --- packages/renderer/src/index.ts | 2 + packages/renderer/src/utils.ts | 68 +++++++++++++------ .../tests/duration-timer-format.test.ts | 62 +++++++++++++++++ .../vscode-extension/media/gantt-webview.js | 11 +++ 4 files changed, 122 insertions(+), 21 deletions(-) create mode 100644 packages/renderer/tests/duration-timer-format.test.ts diff --git a/packages/renderer/src/index.ts b/packages/renderer/src/index.ts index 14b5b369..5702cce1 100644 --- a/packages/renderer/src/index.ts +++ b/packages/renderer/src/index.ts @@ -20,6 +20,8 @@ export { getQty, formatQuantityValue, formatDuration, + formatTimer, + toCommonFraction, escapeHtml, escapeMarkdownHtml, joinStepTokens, diff --git a/packages/renderer/src/utils.ts b/packages/renderer/src/utils.ts index 9414b1fd..756f26e5 100644 --- a/packages/renderer/src/utils.ts +++ b/packages/renderer/src/utils.ts @@ -50,6 +50,24 @@ export function round1(value: number): number { return Math.round(value * 10) / 10; } +const COMMON_FRACTIONS = [ + { val: 0.5, str: "1/2" }, + { val: 0.25, str: "1/4" }, + { val: 0.75, str: "3/4" }, + { val: 1 / 3, str: "1/3" }, + { val: 2 / 3, str: "2/3" }, + { val: 0.125, str: "1/8" }, + { val: 0.375, str: "3/8" }, + { val: 0.625, str: "5/8" }, + { val: 0.875, str: "7/8" }, +]; + +/** "1/4" for a value strictly below 1 that is (nearly) a common fraction. */ +export function toCommonFraction(value: number): string | undefined { + if (value >= 1) return undefined; + return COMMON_FRACTIONS.find((f) => Math.abs(value - f.val) < 0.01)?.str; +} + export function formatDecimalToFraction(value: unknown, unit?: string): string { if (typeof value !== "number") return String(value); @@ -58,22 +76,8 @@ export function formatDecimalToFraction(value: unknown, unit?: string): string { return String(Math.round(value)); } - // Fractions only for values strictly below 1 - if (value < 1) { - const commonFractions = [ - { val: 0.5, str: "1/2" }, - { val: 0.25, str: "1/4" }, - { val: 0.75, str: "3/4" }, - { val: 1 / 3, str: "1/3" }, - { val: 2 / 3, str: "2/3" }, - { val: 0.125, str: "1/8" }, - { val: 0.375, str: "3/8" }, - { val: 0.625, str: "5/8" }, - { val: 0.875, str: "7/8" }, - ]; - const match = commonFractions.find((f) => Math.abs(value - f.val) < 0.01); - if (match) return match.str; - } + const fraction = toCommonFraction(value); + if (fraction) return fraction; if (unit && isCoarseUnit(unit)) { return String(round1(value)); @@ -135,13 +139,35 @@ export function formatQuantityValue(q: any): string { /** * Formats duration values into human readable strings (e.g. 90 -> 1h 30m). + * Compiled timings are floats (20s is 0.333 min), so the value is rounded: + * to the minute from one hour up, to the second below — never a raw decimal. */ export function formatDuration(minutes: number): string { - if (!minutes) return "0m"; - const h = Math.floor(minutes / 60); - const m = minutes % 60; - if (h > 0) return `${h}h ${m > 0 ? `${m}m` : ""}`; - return `${m}m`; + if (!Number.isFinite(minutes) || minutes <= 0) return "0m"; + if (minutes >= 60) { + const total = Math.round(minutes); + const h = Math.floor(total / 60); + const m = total % 60; + return m > 0 ? `${h}h ${m}m` : `${h}h`; + } + const totalSeconds = Math.round(minutes * 60); + const m = Math.floor(totalSeconds / 60); + const s = totalSeconds % 60; + if (m === 0) return `${s}s`; + return s > 0 ? `${m}m ${s}s` : `${m}m`; +} + +/** + * Displays a compiled timer token: its value followed by its unit. The unit + * lives on the token (`{ type: "timer", quantity, unit }`), never on the + * quantity. No unit means the value alone — there is no implicit "min". + */ +export function formatTimer( + item: { quantity?: unknown; unit?: string | null }, + separator = "", +): string { + const value = formatQuantityValue(item.quantity ?? ""); + return item.unit ? `${value}${separator}${item.unit}` : value; } /** diff --git a/packages/renderer/tests/duration-timer-format.test.ts b/packages/renderer/tests/duration-timer-format.test.ts new file mode 100644 index 00000000..414c89ae --- /dev/null +++ b/packages/renderer/tests/duration-timer-format.test.ts @@ -0,0 +1,62 @@ +import { describe, it, expect } from "bun:test"; +import { formatDuration, formatTimer, toCommonFraction } from "../src/index"; + +describe("formatDuration", () => { + it("keeps whole durations readable", () => { + expect(formatDuration(45)).toBe("45m"); + expect(formatDuration(60)).toBe("1h"); + expect(formatDuration(90)).toBe("1h 30m"); + }); + + it("rounds to the minute from one hour up, never leaking a float", () => { + expect(formatDuration(64.5)).toBe("1h 5m"); + expect(formatDuration(1497.58333)).toBe("24h 58m"); + }); + + it("shows seconds below one hour", () => { + expect(formatDuration(25.083333333333336)).toBe("25m 5s"); + expect(formatDuration(20 / 60)).toBe("20s"); + }); + + it("degrades to 0m on empty or invalid input", () => { + expect(formatDuration(0)).toBe("0m"); + expect(formatDuration(Number.NaN)).toBe("0m"); + expect(formatDuration(-5)).toBe("0m"); + }); +}); + +describe("formatTimer", () => { + it("reads the unit from the token, not the quantity", () => { + expect(formatTimer({ quantity: { value: 1, text: "1" }, unit: "h" })).toBe( + "1h", + ); + expect( + formatTimer({ quantity: { value: 20, text: "20" }, unit: "s" }), + ).toBe("20s"); + }); + + it("supports a separator and ranges", () => { + expect( + formatTimer( + { quantity: { type: "range", text: "10-15" }, unit: "min" }, + " ", + ), + ).toBe("10-15 min"); + }); + + it("shows the bare value when there is no unit", () => { + expect(formatTimer({ quantity: { value: 5, text: "5" } })).toBe("5"); + }); +}); + +describe("toCommonFraction", () => { + it("maps near-common fractions below 1", () => { + expect(toCommonFraction(0.25)).toBe("1/4"); + expect(toCommonFraction(1 / 3)).toBe("1/3"); + }); + + it("returns undefined otherwise", () => { + expect(toCommonFraction(0.3)).toBeUndefined(); + expect(toCommonFraction(1.5)).toBeUndefined(); + }); +}); diff --git a/packages/vscode-extension/media/gantt-webview.js b/packages/vscode-extension/media/gantt-webview.js index 733c9dbf..08f1b142 100644 --- a/packages/vscode-extension/media/gantt-webview.js +++ b/packages/vscode-extension/media/gantt-webview.js @@ -89,6 +89,17 @@ var EMPTY_MACROS = Object.fromEntries( NUTRIENTS.filter((n) => n.required).map((n) => [n.key, 0]) ); + var COMMON_FRACTIONS = [ + { val: 0.5, str: "1/2" }, + { val: 0.25, str: "1/4" }, + { val: 0.75, str: "3/4" }, + { val: 1 / 3, str: "1/3" }, + { val: 2 / 3, str: "2/3" }, + { val: 0.125, str: "1/8" }, + { val: 0.375, str: "3/8" }, + { val: 0.625, str: "5/8" }, + { val: 0.875, str: "7/8" } + ]; function formatTime(minutes) { const h = Math.floor(minutes / 60); const m = Math.floor(minutes % 60); -- 2.54.0 From 4452428ea87c83d48cdb06bdeab84c7f8e7e2fe2 Mon Sep 17 00:00:00 2001 From: abiwab Date: Tue, 29 Sep 2026 11:25:59 +0200 Subject: [PATCH 2/4] fix(cli): show real timer units, rest time and fractions in gram view --- packages/cli/src/services/viewer.ts | 21 ++++++++++----------- packages/cli/src/ui/cook/StepView.tsx | 9 +++------ packages/cli/src/ui/viewer.ts | 25 +++++++++---------------- packages/cli/tests/viewer.test.ts | 23 +++++++++++++++++++++++ 4 files changed, 45 insertions(+), 33 deletions(-) diff --git a/packages/cli/src/services/viewer.ts b/packages/cli/src/services/viewer.ts index f78c8153..5ff26b2f 100644 --- a/packages/cli/src/services/viewer.ts +++ b/packages/cli/src/services/viewer.ts @@ -3,7 +3,11 @@ import { runPipeline } from "../core/pipeline"; import { fmtNumber } from "../core/format"; import { isCoarseUnit } from "@gram-lang/i18n"; import type { IngredientData } from "@gram-lang/analyzer"; -import type { NutritionBasis } from "@gram-lang/renderer"; +import { + formatTimer, + toCommonFraction, + type NutritionBasis, +} from "@gram-lang/renderer"; import type { RecipeViewModel } from "../types"; function formatMass(grams: number): string { @@ -16,9 +20,8 @@ function formatQty(item: any): string { if (qty == null) return ""; const decimals = isCoarseUnit(item.unit) ? 1 : 2; if (typeof qty === "number") { - return item.unit - ? `${fmtNumber(qty, decimals)} ${item.unit}` - : fmtNumber(qty, decimals); + const shown = toCommonFraction(qty) ?? fmtNumber(qty, decimals); + return item.unit ? `${shown} ${item.unit}` : shown; } if (typeof qty === "string") return item.unit ? `${qty} ${item.unit}` : qty; if (typeof qty === "object") { @@ -79,12 +82,8 @@ function tokenToText(item: any, registry: Record): string { switch (item.type) { case "text": return item.value ?? ""; - case "timer": { - const q = item.quantity; - if (!q) return ""; - const val = q.text ?? (q.value != null ? String(q.value) : ""); - return `~${val}${q.unit ?? "min"}`; - } + case "timer": + return item.quantity ? `~${formatTimer(item)}` : ""; case "temperature": { const q = item.quantity; if (!q) return item.text ?? ""; @@ -182,7 +181,7 @@ export async function buildViewModel( m && (m.totalTime || m.idleTime || m.activeTime || m.preparationTime) ? { total: m.totalTime || undefined, - idle: m.idleTime || undefined, + rest: m.idleTime || undefined, active: m.activeTime || undefined, prep: m.preparationTime || undefined, } diff --git a/packages/cli/src/ui/cook/StepView.tsx b/packages/cli/src/ui/cook/StepView.tsx index 5f7377a2..fd02b729 100644 --- a/packages/cli/src/ui/cook/StepView.tsx +++ b/packages/cli/src/ui/cook/StepView.tsx @@ -1,6 +1,7 @@ import React from "react"; import { Box, Text } from "ink"; import chalk from "chalk"; +import { formatTimer } from "@gram-lang/renderer"; import type { ActiveTimer, FlatStep } from "./types"; import type { CompilationResult } from "@gram-lang/kitchen"; import { fmtQty, fmtMass, fmtCountdown, shouldShowMass } from "./prepare"; @@ -21,9 +22,7 @@ function getTempDisplay(token: any): string { } function getTimerDisplay(token: any): string { - const val = getQtyText(token.quantity); - const unit = token.unit ?? token.quantity?.unit ?? "min"; - return `${val} ${unit}`; + return formatTimer(token, " "); } // Strip ANSI escape codes to get visible text (used for smart-join boundary checks) @@ -49,9 +48,7 @@ function buildInstruction( if (token.type === "comment" || token.type === "declaration") continue; if (token.type === "timer") { - const val = getQtyText(token.quantity); - const unit = token.unit ?? token.quantity?.unit ?? "min"; - parts.push(chalk.yellow(`${val} ${unit}`)); + parts.push(chalk.yellow(formatTimer(token, " "))); continue; } diff --git a/packages/cli/src/ui/viewer.ts b/packages/cli/src/ui/viewer.ts index edf52447..980ddf58 100644 --- a/packages/cli/src/ui/viewer.ts +++ b/packages/cli/src/ui/viewer.ts @@ -1,6 +1,8 @@ import chalk from "chalk"; import { spawn } from "node:child_process"; import { + formatDuration, + formatTimer, nutritionRows, resolveNutritionBasis, type NutritionBasis, @@ -31,10 +33,8 @@ function tokenToRichText( } if (item.type === "timer") { - const q = item.quantity; - if (!q) return ""; - const val = q.text ?? (q.value != null ? String(q.value) : ""); - return chalk.dim(`~${val}${q.unit ?? "min"}`); + if (!item.quantity) return ""; + return chalk.dim(`~${formatTimer(item)}`); } if (item.type === "temperature") { @@ -106,13 +106,6 @@ function rule(label?: string): string { return chalk.dim(inner + "─".repeat(Math.max(0, COL - inner.length))); } -function formatMinutes(mins: number): string { - if (mins < 60) return `${mins}min`; - const h = Math.floor(mins / 60); - const m = mins % 60; - return m ? `${h}h${m}` : `${h}h`; -} - function renderHeader(model: RecipeViewModel): string { const lines: string[] = []; const servStr = model.servings ? ` ${model.servings} servings ` : " "; @@ -128,10 +121,10 @@ function renderHeader(model: RecipeViewModel): string { if (model.times) { const t = model.times; const parts: string[] = []; - if (t.prep) parts.push(`Prep: ${formatMinutes(t.prep)}`); - if (t.active) parts.push(`Active: ${formatMinutes(t.active)}`); - if (t.rest) parts.push(`Rest: ${formatMinutes(t.rest)}`); - if (t.total) parts.push(`Total: ${formatMinutes(t.total)}`); + if (t.prep) parts.push(`Prep: ${formatDuration(t.prep)}`); + if (t.active) parts.push(`Active: ${formatDuration(t.active)}`); + if (t.rest) parts.push(`Rest: ${formatDuration(t.rest)}`); + if (t.total) parts.push(`Total: ${formatDuration(t.total)}`); if (parts.length > 0) { const inner = `⏱ ${parts.join(" · ")}`; lines.push( @@ -194,7 +187,7 @@ function renderSections( ? chalk.cyan(`[${step.action}]`).padEnd(12) : "".padEnd(10); const timer = step.timerMinutes - ? chalk.dim(` (~${formatMinutes(step.timerMinutes)})`) + ? chalk.dim(` (~${formatDuration(step.timerMinutes)})`) : ""; const richText = stepToRichText( step._tokens, diff --git a/packages/cli/tests/viewer.test.ts b/packages/cli/tests/viewer.test.ts index 132235b7..10f32150 100644 --- a/packages/cli/tests/viewer.test.ts +++ b/packages/cli/tests/viewer.test.ts @@ -126,4 +126,27 @@ describe("buildViewModel", () => { const vm = await buildViewModel(path, { scaleFactor: 2 }); expect(vm.sections[0]?.ingredients[0]?.displayQty).toBe("400 g"); }); + + it("keeps each timer's own unit in the step text", async () => { + const path = await tmp( + "## T\n\nA ~{20s} B ~{20 s} C ~{90s} D ~{2min} E ~{1h}\n", + ); + const vm = await buildViewModel(path, {}); + const text = vm.sections[0]?.steps[0]?.text ?? ""; + expect(text).toContain("~20s"); + expect(text).toContain("~90s"); + expect(text).toContain("~2min"); + expect(text).toContain("~1h"); + expect(text).not.toContain("~20min"); + expect(text).not.toContain("~1min"); + }); + + it("exposes the resting time as `rest`", async () => { + const path = await tmp( + "## T\n\nMix @flour{200g}. ~_{30min}\n\nBake it ~{10min}.\n", + ); + const vm = await buildViewModel(path, {}); + expect(vm.times?.rest).toBeGreaterThan(0); + expect(vm.times).not.toHaveProperty("idle"); + }); }); -- 2.54.0 From 2cd12df2ebbbd60201792d3619eea16a3e047d54 Mon Sep 17 00:00:00 2001 From: abiwab Date: Tue, 29 Sep 2026 11:25:59 +0200 Subject: [PATCH 3/4] docs(renderer): document duration rounding and new helpers --- packages/docs/public/llms-full.txt | 6 +++++- .../docs/src/content/docs/docs/reference/api/renderer.md | 4 +++- .../src/content/docs/fr/docs/explanation/engine/renderer.md | 2 +- .../docs/src/content/docs/fr/docs/reference/api/renderer.md | 4 +++- 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/packages/docs/public/llms-full.txt b/packages/docs/public/llms-full.txt index 2e6ab666..89e6860a 100644 --- a/packages/docs/public/llms-full.txt +++ b/packages/docs/public/llms-full.txt @@ -307,7 +307,9 @@ To specify a unit of measurement (weight, volume, etc.), add it directly after t A unit can be several words (`{2 tablespoons}`) and can contain dots or apostrophes (`{1 c.à.s}`, `{1 c. à s.}`). Common spellings of the same unit are recognized as equivalent: `c.à.s`, `c.a.s` and `càs` all mean tablespoon in French. -A quantity in braces that can't be read (`@salt{1 g/l}`, or a brace that is never closed) raises an error pointing at the offending brace, instead of being silently ignored. +:::caution +A quantity in braces that can't be read (`@salt{1 g/l}`, or a brace that is never closed) stops parsing with an error pointing at the offending brace. +::: ## Scaling & fixed quantities @@ -461,6 +463,8 @@ Add @butter{1½ sticks}. ## Error handling +Some syntax errors stop the recipe from being read before it is even compiled: an unreadable quantity in braces (`@salt{1 g/l}`), a brace that is never closed. The message points at the exact spot to fix, and the editor underlines it. + The compiler checks for semantic errors in your `@ingredient` declarations and will output specific warnings: - **Invalid Modifier**: If you combine incompatible modifiers (like `?*`), the compiler warns `INVALID_MODIFIER_COMBINATION` and ignores them. diff --git a/packages/docs/src/content/docs/docs/reference/api/renderer.md b/packages/docs/src/content/docs/docs/reference/api/renderer.md index 0afa696b..a074bb03 100644 --- a/packages/docs/src/content/docs/docs/reference/api/renderer.md +++ b/packages/docs/src/content/docs/docs/reference/api/renderer.md @@ -104,7 +104,9 @@ Lower-level helpers used internally by the three formatters, exported for buildi function formatDecimalToFraction(value: unknown): string // 0.5 -> "1/2" function getQty(item: Record): { value: number | string | null; text?: string; isRelative?: boolean } | undefined function formatQuantityValue(q: any): string // Timer/Temperature quantity -> display string -function formatDuration(minutes: number): string // 90 -> "1h 30m" +function formatDuration(minutes: number): string // 90 -> "1h 30m"; rounded to the minute from 1h up, to the second below (64.5 -> "1h 5m", 0.33 -> "20s") +function formatTimer(item: { quantity?: unknown; unit?: string | null }, separator?: string): string // { quantity: 1, unit: "h" } -> "1h" +function toCommonFraction(value: number): string | undefined // 0.25 -> "1/4", 0.3 -> undefined function escapeHtml(unsafe: string | null | undefined): string function escapeMarkdownHtml(unsafe: string | null | undefined): string // neutralizes `<`/`&` for safe Markdown-to-HTML rendering downstream function joinStepTokens(tokens: StepToken[], renderToken: (token: StepToken) => string, isSpaceable: (token: StepToken) => boolean): string diff --git a/packages/docs/src/content/docs/fr/docs/explanation/engine/renderer.md b/packages/docs/src/content/docs/fr/docs/explanation/engine/renderer.md index 5acbd450..253d5e03 100644 --- a/packages/docs/src/content/docs/fr/docs/explanation/engine/renderer.md +++ b/packages/docs/src/content/docs/fr/docs/explanation/engine/renderer.md @@ -74,7 +74,7 @@ L'objet `RendererOptions` offre aussi `bakersReference`/`bakersMathOnly` (pour l :::caution Même si cet échappement bloque les injections HTML vicieuses (le vecteur XSS classique via `markdown-it`/`remark`), `toMarkdown` ne purge **pas** tout. Un lien `[texte](javascript:...)` passera. Si vous rendez des `.gram` issus de sources douteuses, passez un coup de `DOMPurify` ou `rehype-sanitize` sur le HTML final par principe. ::: -- **Formatage des Durées** : Transforme d'infâmes minutes brutes en temps humain (`90` → `1 h 30 min`). +- **Formatage des Durées** : Transforme d'infâmes minutes brutes en temps humain (`90` → `1h 30m`). - **Pré-stylisation CSS** : Le *package* *ship* un fichier `gram.css` embarquant le thème officiel (tokens clair/sombre par composant) ainsi qu'un `gantt.css` (dépendant du premier). Le Print HTML, lui, a sa propre CSS directement injectée dans son *header* : c'est *plug and play*. ## Consommation directe du JSON diff --git a/packages/docs/src/content/docs/fr/docs/reference/api/renderer.md b/packages/docs/src/content/docs/fr/docs/reference/api/renderer.md index 9b3cffff..ef362744 100644 --- a/packages/docs/src/content/docs/fr/docs/reference/api/renderer.md +++ b/packages/docs/src/content/docs/fr/docs/reference/api/renderer.md @@ -104,7 +104,9 @@ Une poignée d'utilitaires bas niveau (utilisés en interne par les formateurs) function formatDecimalToFraction(value: unknown): string // 0.5 -> "1/2" function getQty(item: Record): { value: number | string | null; text?: string; isRelative?: boolean } | undefined function formatQuantityValue(q: any): string // Quantité de minuteur/température -> chaîne d'affichage -function formatDuration(minutes: number): string // 90 -> "1h 30m" +function formatDuration(minutes: number): string // 90 -> "1h 30m" ; arrondi à la minute dès 1h, à la seconde en dessous (64.5 -> "1h 5m", 0.33 -> "20s") +function formatTimer(item: { quantity?: unknown; unit?: string | null }, separator?: string): string // { quantity: 1, unit: "h" } -> "1h" +function toCommonFraction(value: number): string | undefined // 0.25 -> "1/4", 0.3 -> undefined function escapeHtml(unsafe: string | null | undefined): string function escapeMarkdownHtml(unsafe: string | null | undefined): string // neutralise `<`/`&` pour un rendu Markdown vers HTML sûr en aval function joinStepTokens(tokens: StepToken[], renderToken: (token: StepToken) => string, isSpaceable: (token: StepToken) => boolean): string -- 2.54.0 From 4c9652c68331adbedc95a6b1454a3ce47f6e6938 Mon Sep 17 00:00:00 2001 From: abiwab Date: Tue, 29 Sep 2026 11:25:59 +0200 Subject: [PATCH 4/4] chore: add changeset for gram view timer display fix --- .changeset/cli-view-timer-units.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 .changeset/cli-view-timer-units.md diff --git a/.changeset/cli-view-timer-units.md b/.changeset/cli-view-timer-units.md new file mode 100644 index 00000000..c84494ff --- /dev/null +++ b/.changeset/cli-view-timer-units.md @@ -0,0 +1,10 @@ +--- +"@gram-lang/cli": patch +"@gram-lang/renderer": patch +--- + +**CLI / View**: Fixed several display issues in `gram view` and cook mode: + - Timers now show their real unit (`~{1h}` is shown as `~1h`, `~{20s}` as `~20s`) instead of always "min". + - Recipe durations are rounded and readable (`1h 5m`, `25m 5s`) instead of raw decimals like `1h4.5`. + - The resting time now appears in the recipe header. + - Common fractions such as `1/4 tsp` stay fractions in the shopping list instead of becoming `0.3`. -- 2.54.0