fix(cli): show real timer units, readable durations and fractions in gram view #38

Merged
abiwab merged 4 commits from fix/cli-view-timer-units into main 2026-09-29 11:28:58 +02:00
13 changed files with 189 additions and 58 deletions

View file

@ -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`.

View file

@ -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, any>): 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,
}

View file

@ -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;
}

View file

@ -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,

View file

@ -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");
});
});

View file

@ -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.

View file

@ -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<string, unknown>): { 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

View file

@ -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

View file

@ -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<string, unknown>): { 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

View file

@ -20,6 +20,8 @@ export {
getQty,
formatQuantityValue,
formatDuration,
formatTimer,
toCommonFraction,
escapeHtml,
escapeMarkdownHtml,
joinStepTokens,

View file

@ -50,17 +50,7 @@ export function round1(value: number): number {
return Math.round(value * 10) / 10;
}
export function formatDecimalToFraction(value: unknown, unit?: string): string {
if (typeof value !== "number") return String(value);
// Exact integers
if (Math.abs(value - Math.round(value)) < 0.01) {
return String(Math.round(value));
}
// Fractions only for values strictly below 1
if (value < 1) {
const commonFractions = [
const COMMON_FRACTIONS = [
{ val: 0.5, str: "1/2" },
{ val: 0.25, str: "1/4" },
{ val: 0.75, str: "3/4" },
@ -70,11 +60,25 @@ export function formatDecimalToFraction(value: unknown, unit?: string): string {
{ 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;
];
/** "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);
// Exact integers
if (Math.abs(value - Math.round(value)) < 0.01) {
return String(Math.round(value));
}
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;
}
/**

View file

@ -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();
});
});

View file

@ -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);