diff --git a/.changeset/temperature-note.md b/.changeset/temperature-note.md new file mode 100644 index 00000000..011b3ddb --- /dev/null +++ b/.changeset/temperature-note.md @@ -0,0 +1,14 @@ +--- +"@gram-lang/parser": minor +"@gram-lang/kitchen": minor +"@gram-lang/analyzer": minor +"@gram-lang/renderer": minor +"@gram-lang/cli": minor +--- + +**Parser & Kitchen**: A temperature can carry a note in parentheses glued to its closing brace, such as the oven mode or where it is measured: `^{160°C}(fan)`, `^oven{180°C}(grill)`, `^{63°C}(internal)`, `^{high heat}(covered)`: + - Only a parenthesis that touches the `}` is a note, and it ends on the same line: `^{180°C} (the oven must be hot)` keeps its parenthesis in the sentence, as before. + - The note is shown next to the temperature in every view, on screen, in Markdown, in plain text and in print, and in `gram cook`. `gram cook` now shows temperatures the way the views do (`180 °C`), including those in words (`^{high}`). + - The AST and the compiled JSON have a new `note` field on temperatures, left out when there is none. `gram diff` reports a note that was added, removed or changed. + - For integrators, `formatTemperature` (`@gram-lang/renderer`) displays a compiled temperature the way the views do, and the new `temperatureGroup` class holds a temperature and its note together in HTML. + - `gram import` keeps the oven mode found in a source recipe as a note instead of leaving it in the prose. diff --git a/audit/src/vocabulary.ts b/audit/src/vocabulary.ts index 536d9da7..a7c9d064 100644 --- a/audit/src/vocabulary.ts +++ b/audit/src/vocabulary.ts @@ -70,6 +70,11 @@ function walk(node: unknown, shapes: Set, ctx: WalkContext): void { if (record.preparation) shapes.add("Composite:hasPreparation"); break; } + case "Temperature": { + // The note glued to the brace (`^{160°C}(fan)`, 1.5). + if (record.note) shapes.add("Temperature:hasNote"); + break; + } case "Timer": shapes.add(`Timer:isPassive=${Boolean(record.isPassive)}`); addDurationShapes(record.raw, "Timer", shapes); diff --git a/conformance/cases/047-temperature-note/analyzed.json b/conformance/cases/047-temperature-note/analyzed.json new file mode 100644 index 00000000..eb482b69 --- /dev/null +++ b/conformance/cases/047-temperature-note/analyzed.json @@ -0,0 +1,363 @@ +{ + "title": "Temperature Note", + "slug": "temperature-note", + "meta": { + "title": "Temperature Note" + }, + "registry": { + "ingredients": {}, + "cookware": {} + }, + "shopping_list": [], + "cookware": [], + "sections": [ + { + "title": "Bake", + "ingredients": [], + "cookware": [], + "steps": [ + { + "type": "step", + "content": [ + "Preheat ", + { + "type": "temperature", + "quantity": { + "type": "single", + "value": 160, + "text": "160" + }, + "unit": "°C", + "note": "chaleur tournante" + }, + "." + ], + "timings": { + "start": 0, + "end": 2, + "activeDuration": 2 + } + }, + { + "type": "step", + "content": [ + "Roast in the ", + { + "type": "temperature", + "name": "oven", + "quantity": { + "type": "single", + "value": 180, + "text": "180" + }, + "unit": "°C", + "note": "gril" + }, + "." + ], + "timings": { + "start": 2, + "end": 4, + "activeDuration": 2 + } + }, + { + "type": "step", + "content": [ + "Simmer on ", + { + "type": "temperature", + "text": "vif", + "note": "à couvert" + }, + "." + ], + "timings": { + "start": 4, + "end": 6, + "activeDuration": 2 + } + }, + { + "type": "step", + "content": [ + "Bake at ", + { + "type": "temperature", + "quantity": { + "type": "single", + "value": 180, + "text": "180" + }, + "unit": "°C" + }, + "(four préchauffé)." + ], + "timings": { + "start": 6, + "end": 8, + "activeDuration": 2 + } + }, + { + "type": "step", + "content": [ + "Rest at ", + { + "type": "temperature", + "quantity": { + "type": "single", + "value": 20, + "text": "20" + }, + "unit": "°C" + }, + "." + ], + "timings": { + "start": 8, + "end": 10, + "activeDuration": 2 + } + }, + { + "type": "step", + "content": [ + "Cook at ", + { + "type": "temperature", + "quantity": { + "type": "single", + "value": 200, + "text": "200" + }, + "unit": "°C" + }, + "(about 20 min" + ], + "timings": { + "start": 10, + "end": 12, + "activeDuration": 2 + } + }, + { + "type": "step", + "content": [ + "Serve (hot)." + ], + "timings": { + "start": 12, + "end": 14, + "activeDuration": 2 + } + } + ], + "metrics": { + "totalMass": 0, + "massStatus": "incomplete", + "missingMassIngredients": [] + } + } + ], + "warnings": [], + "metrics": { + "totalTime": 14, + "totalBreakdown": [ + { + "label": "section_active:Bake", + "duration": 14 + } + ], + "idleTime": 0, + "activeTime": 14, + "activeBreakdown": [ + { + "label": "section_active:Bake", + "duration": 14 + } + ], + "preparationTime": 0, + "totalMass": 0, + "massStatus": "incomplete", + "missingMassIngredients": [], + "nutrition": { + "total": { + "calories": 0, + "fat": 0, + "carbs": 0, + "protein": 0 + }, + "isEstimate": false, + "coverage": 0 + } + }, + "miseEnPlace": [], + "tasks": { + "tasks": [ + { + "id": "s0.0", + "kind": "step", + "section": 0, + "step": 0, + "duration": { + "nominal": 2 + }, + "after": [] + }, + { + "id": "s0.1", + "kind": "step", + "section": 0, + "step": 1, + "duration": { + "nominal": 2 + }, + "after": [ + "s0.0" + ] + }, + { + "id": "s0.2", + "kind": "step", + "section": 0, + "step": 2, + "duration": { + "nominal": 2 + }, + "after": [ + "s0.1" + ] + }, + { + "id": "s0.3", + "kind": "step", + "section": 0, + "step": 3, + "duration": { + "nominal": 2 + }, + "after": [ + "s0.2" + ] + }, + { + "id": "s0.4", + "kind": "step", + "section": 0, + "step": 4, + "duration": { + "nominal": 2 + }, + "after": [ + "s0.3" + ] + }, + { + "id": "s0.5", + "kind": "step", + "section": 0, + "step": 5, + "duration": { + "nominal": 2 + }, + "after": [ + "s0.4" + ] + }, + { + "id": "s0.6", + "kind": "step", + "section": 0, + "step": 6, + "duration": { + "nominal": 2 + }, + "after": [ + "s0.5" + ] + } + ], + "sections": [ + { + "day": 0 + } + ] + }, + "schedule": { + "miseEnPlace": "perSection", + "rests": "shortest", + "totalTime": 14, + "activeTime": 14, + "preparationTime": 0, + "idleTime": 0, + "blocks": [ + { + "kind": "step", + "task": "s0.0", + "section": 0, + "step": 0, + "start": 0, + "end": 2 + }, + { + "kind": "step", + "task": "s0.1", + "section": 0, + "step": 1, + "start": 2, + "end": 4 + }, + { + "kind": "step", + "task": "s0.2", + "section": 0, + "step": 2, + "start": 4, + "end": 6 + }, + { + "kind": "step", + "task": "s0.3", + "section": 0, + "step": 3, + "start": 6, + "end": 8 + }, + { + "kind": "step", + "task": "s0.4", + "section": 0, + "step": 4, + "start": 8, + "end": 10 + }, + { + "kind": "step", + "task": "s0.5", + "section": 0, + "step": 5, + "start": 10, + "end": 12 + }, + { + "kind": "step", + "task": "s0.6", + "section": 0, + "step": 6, + "start": 12, + "end": 14 + } + ], + "days": [ + { + "day": 0, + "start": 0, + "end": 14, + "sections": [ + 0 + ] + } + ] + } +} diff --git a/conformance/cases/047-temperature-note/ast.json b/conformance/cases/047-temperature-note/ast.json new file mode 100644 index 00000000..8965dd93 --- /dev/null +++ b/conformance/cases/047-temperature-note/ast.json @@ -0,0 +1,277 @@ +{ + "type": "Recipe", + "meta": { + "title": "Temperature Note" + }, + "imports": [], + "children": [ + { + "type": "Section", + "title": "Bake", + "retroPlanning": null, + "intermediateDecl": null, + "children": [ + { + "type": "Step", + "action": null, + "children": [ + { + "type": "Text", + "value": "Preheat ", + "loc": { + "start": 42, + "end": 50 + } + }, + { + "type": "Temperature", + "name": null, + "loc": { + "start": 50, + "end": 77 + }, + "note": "chaleur tournante", + "value": { + "type": "single", + "value": 160, + "text": "160" + }, + "unit": "°C" + }, + { + "type": "Text", + "value": ".", + "loc": { + "start": 77, + "end": 78 + } + } + ], + "loc": { + "start": 42, + "end": 80 + } + }, + { + "type": "Step", + "action": null, + "children": [ + { + "type": "Text", + "value": "Roast in the ", + "loc": { + "start": 80, + "end": 93 + } + }, + { + "type": "Temperature", + "name": "oven", + "loc": { + "start": 93, + "end": 111 + }, + "note": "gril", + "value": { + "type": "single", + "value": 180, + "text": "180" + }, + "unit": "°C" + }, + { + "type": "Text", + "value": ".", + "loc": { + "start": 111, + "end": 112 + } + } + ], + "loc": { + "start": 80, + "end": 114 + } + }, + { + "type": "Step", + "action": null, + "children": [ + { + "type": "Text", + "value": "Simmer on ", + "loc": { + "start": 114, + "end": 124 + } + }, + { + "type": "Temperature", + "name": null, + "loc": { + "start": 124, + "end": 141 + }, + "note": "à couvert", + "text": "vif" + }, + { + "type": "Text", + "value": ".", + "loc": { + "start": 141, + "end": 142 + } + } + ], + "loc": { + "start": 114, + "end": 144 + } + }, + { + "type": "Step", + "action": null, + "children": [ + { + "type": "Text", + "value": "Bake at ", + "loc": { + "start": 144, + "end": 152 + } + }, + { + "type": "Temperature", + "name": null, + "loc": { + "start": 152, + "end": 160 + }, + "value": { + "type": "single", + "value": 180, + "text": "180" + }, + "unit": "°C" + }, + { + "type": "Text", + "value": "(four préchauffé).", + "loc": { + "start": 161, + "end": 179 + } + } + ], + "loc": { + "start": 144, + "end": 181 + } + }, + { + "type": "Step", + "action": null, + "children": [ + { + "type": "Text", + "value": "Rest at ", + "loc": { + "start": 181, + "end": 189 + } + }, + { + "type": "Temperature", + "name": null, + "loc": { + "start": 189, + "end": 198 + }, + "value": { + "type": "single", + "value": 20, + "text": "20" + }, + "unit": "°C" + }, + { + "type": "Text", + "value": ".", + "loc": { + "start": 198, + "end": 199 + } + } + ], + "loc": { + "start": 181, + "end": 201 + } + }, + { + "type": "Step", + "action": null, + "children": [ + { + "type": "Text", + "value": "Cook at ", + "loc": { + "start": 201, + "end": 209 + } + }, + { + "type": "Temperature", + "name": null, + "loc": { + "start": 209, + "end": 217 + }, + "value": { + "type": "single", + "value": 200, + "text": "200" + }, + "unit": "°C" + }, + { + "type": "Text", + "value": "(about 20 min", + "loc": { + "start": 217, + "end": 230 + } + } + ], + "loc": { + "start": 201, + "end": 232 + } + }, + { + "type": "Step", + "action": null, + "children": [ + { + "type": "Text", + "value": "Serve (hot).", + "loc": { + "start": 232, + "end": 244 + } + } + ], + "loc": { + "start": 232, + "end": 245 + } + } + ], + "loc": { + "start": 33, + "end": 245 + } + } + ] +} diff --git a/conformance/cases/047-temperature-note/compiled.json b/conformance/cases/047-temperature-note/compiled.json new file mode 100644 index 00000000..e67c9b07 --- /dev/null +++ b/conformance/cases/047-temperature-note/compiled.json @@ -0,0 +1,345 @@ +{ + "title": "Temperature Note", + "slug": "temperature-note", + "meta": { + "title": "Temperature Note" + }, + "registry": { + "ingredients": {}, + "cookware": {} + }, + "shopping_list": [], + "cookware": [], + "sections": [ + { + "title": "Bake", + "ingredients": [], + "cookware": [], + "steps": [ + { + "type": "step", + "content": [ + "Preheat ", + { + "type": "temperature", + "quantity": { + "type": "single", + "value": 160, + "text": "160" + }, + "unit": "°C", + "note": "chaleur tournante" + }, + "." + ], + "timings": { + "start": 0, + "end": 2, + "activeDuration": 2 + } + }, + { + "type": "step", + "content": [ + "Roast in the ", + { + "type": "temperature", + "name": "oven", + "quantity": { + "type": "single", + "value": 180, + "text": "180" + }, + "unit": "°C", + "note": "gril" + }, + "." + ], + "timings": { + "start": 2, + "end": 4, + "activeDuration": 2 + } + }, + { + "type": "step", + "content": [ + "Simmer on ", + { + "type": "temperature", + "text": "vif", + "note": "à couvert" + }, + "." + ], + "timings": { + "start": 4, + "end": 6, + "activeDuration": 2 + } + }, + { + "type": "step", + "content": [ + "Bake at ", + { + "type": "temperature", + "quantity": { + "type": "single", + "value": 180, + "text": "180" + }, + "unit": "°C" + }, + "(four préchauffé)." + ], + "timings": { + "start": 6, + "end": 8, + "activeDuration": 2 + } + }, + { + "type": "step", + "content": [ + "Rest at ", + { + "type": "temperature", + "quantity": { + "type": "single", + "value": 20, + "text": "20" + }, + "unit": "°C" + }, + "." + ], + "timings": { + "start": 8, + "end": 10, + "activeDuration": 2 + } + }, + { + "type": "step", + "content": [ + "Cook at ", + { + "type": "temperature", + "quantity": { + "type": "single", + "value": 200, + "text": "200" + }, + "unit": "°C" + }, + "(about 20 min" + ], + "timings": { + "start": 10, + "end": 12, + "activeDuration": 2 + } + }, + { + "type": "step", + "content": [ + "Serve (hot)." + ], + "timings": { + "start": 12, + "end": 14, + "activeDuration": 2 + } + } + ] + } + ], + "warnings": [], + "metrics": { + "totalTime": 14, + "totalBreakdown": [ + { + "label": "section_active:Bake", + "duration": 14 + } + ], + "idleTime": 0, + "activeTime": 14, + "activeBreakdown": [ + { + "label": "section_active:Bake", + "duration": 14 + } + ], + "preparationTime": 0 + }, + "miseEnPlace": [], + "tasks": { + "tasks": [ + { + "id": "s0.0", + "kind": "step", + "section": 0, + "step": 0, + "duration": { + "nominal": 2 + }, + "after": [] + }, + { + "id": "s0.1", + "kind": "step", + "section": 0, + "step": 1, + "duration": { + "nominal": 2 + }, + "after": [ + "s0.0" + ] + }, + { + "id": "s0.2", + "kind": "step", + "section": 0, + "step": 2, + "duration": { + "nominal": 2 + }, + "after": [ + "s0.1" + ] + }, + { + "id": "s0.3", + "kind": "step", + "section": 0, + "step": 3, + "duration": { + "nominal": 2 + }, + "after": [ + "s0.2" + ] + }, + { + "id": "s0.4", + "kind": "step", + "section": 0, + "step": 4, + "duration": { + "nominal": 2 + }, + "after": [ + "s0.3" + ] + }, + { + "id": "s0.5", + "kind": "step", + "section": 0, + "step": 5, + "duration": { + "nominal": 2 + }, + "after": [ + "s0.4" + ] + }, + { + "id": "s0.6", + "kind": "step", + "section": 0, + "step": 6, + "duration": { + "nominal": 2 + }, + "after": [ + "s0.5" + ] + } + ], + "sections": [ + { + "day": 0 + } + ] + }, + "schedule": { + "miseEnPlace": "perSection", + "rests": "shortest", + "totalTime": 14, + "activeTime": 14, + "preparationTime": 0, + "idleTime": 0, + "blocks": [ + { + "kind": "step", + "task": "s0.0", + "section": 0, + "step": 0, + "start": 0, + "end": 2 + }, + { + "kind": "step", + "task": "s0.1", + "section": 0, + "step": 1, + "start": 2, + "end": 4 + }, + { + "kind": "step", + "task": "s0.2", + "section": 0, + "step": 2, + "start": 4, + "end": 6 + }, + { + "kind": "step", + "task": "s0.3", + "section": 0, + "step": 3, + "start": 6, + "end": 8 + }, + { + "kind": "step", + "task": "s0.4", + "section": 0, + "step": 4, + "start": 8, + "end": 10 + }, + { + "kind": "step", + "task": "s0.5", + "section": 0, + "step": 5, + "start": 10, + "end": 12 + }, + { + "kind": "step", + "task": "s0.6", + "section": 0, + "step": 6, + "start": 12, + "end": 14 + } + ], + "days": [ + { + "day": 0, + "start": 0, + "end": 14, + "sections": [ + 0 + ] + } + ] + } +} diff --git a/conformance/cases/047-temperature-note/input.gram b/conformance/cases/047-temperature-note/input.gram new file mode 100644 index 00000000..96979cf5 --- /dev/null +++ b/conformance/cases/047-temperature-note/input.gram @@ -0,0 +1,19 @@ +--- +title: Temperature Note +--- + +## Bake + +Preheat ^{160°C}(chaleur tournante). + +Roast in the ^oven{180°C}(gril). + +Simmer on ^{vif}(à couvert). + +Bake at ^{180°C} (four préchauffé). + +Rest at ^{20°C}(). + +Cook at ^{200°C}(about 20 min + +Serve (hot). diff --git a/conformance/legacy-1.3.0.test.ts b/conformance/legacy-1.3.0.test.ts index 12e5541a..2a9cdb9d 100644 --- a/conformance/legacy-1.3.0.test.ts +++ b/conformance/legacy-1.3.0.test.ts @@ -38,6 +38,11 @@ const ADDED_SINCE_1_3_0 = new Set([ // the duration in minutes. const TIMER_ADDED_SINCE_1_3_0 = new Set(["raw", "minutes"]); +// Added after 1.3.0 inside a step's temperature token (1.5): the note glued +// to its brace (`^{160°C}(fan)`). Left out when absent, so no case of the tag +// moves; listed so a note never moves a digest. +const TEMPERATURE_ADDED_SINCE_1_3_0 = new Set(["note"]); + // Added after 1.3.0 on any ingredient, reference or composite parent (1.5): // the terms of a sum of quantities (`{1 cup + 1 tbsp}`). A sum did not parse // in 1.3.0, so no case of the tag has one; listed so a sum never moves a digest. @@ -52,9 +57,12 @@ const isShoppingRange = (value: object, key: string): boolean => function canonical(value: unknown): string { if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`; if (value && typeof value === "object") { - const isTimer = (value as { type?: unknown }).type === "timer"; + const type = (value as { type?: unknown }).type; + const isTimer = type === "timer"; + const isTemperature = type === "temperature"; const entries = Object.entries(value as Record) .filter(([k]) => !(isTimer && TIMER_ADDED_SINCE_1_3_0.has(k))) + .filter(([k]) => !(isTemperature && TEMPERATURE_ADDED_SINCE_1_3_0.has(k))) .filter(([k]) => !QUANTITY_ADDED_SINCE_1_3_0.has(k)) .filter(([k]) => !isShoppingRange(value, k)) .sort(([a], [b]) => (a < b ? -1 : 1)) diff --git a/packages/analyzer/src/diff.ts b/packages/analyzer/src/diff.ts index 14db01e5..aadde4d0 100644 --- a/packages/analyzer/src/diff.ts +++ b/packages/analyzer/src/diff.ts @@ -87,8 +87,16 @@ export interface TemperatureDelta { section: string | null; name?: string; change: "added" | "removed" | "changed"; - from?: { value: number; unit: string; range?: { min: number; max: number } }; - to?: { value: number; unit: string; range?: { min: number; max: number } }; + from?: TemperatureValue; + to?: TemperatureValue; +} + +/** A temperature as `diffTemperatures` compares it. `note` since 1.5.0. */ +export interface TemperatureValue { + value: number; + unit: string; + range?: { min: number; max: number }; + note?: string; } export interface TimerDelta { @@ -257,11 +265,7 @@ function fmtTimerQty( return `?${u}`; } -function getTempValue(token: ProcessedTemperature): { - value: number; - unit: string; - range?: { min: number; max: number }; -} | null { +function getTempValue(token: ProcessedTemperature): TemperatureValue | null { const q = token.quantity; if (!q) return null; const value = @@ -277,7 +281,12 @@ function getTempValue(token: ProcessedTemperature): { typeof q === "object" && "type" in q && q.type === "range" && q.range ? q.range : undefined; - return { value, unit: token.unit ?? "°", range }; + return { + value, + unit: token.unit ?? "°", + range, + ...(token.note ? { note: token.note } : {}), + }; } function isProcessedTimer(token: StepToken): token is ProcessedTimer { diff --git a/packages/analyzer/tests/diff.test.ts b/packages/analyzer/tests/diff.test.ts index 4460bf43..bdefe8db 100644 --- a/packages/analyzer/tests/diff.test.ts +++ b/packages/analyzer/tests/diff.test.ts @@ -24,6 +24,19 @@ describe("diffRecipes — temperature ranges", () => { expect(temperatures[0]?.to?.range).toEqual({ min: 100, max: 400 }); }); + it("detects a change of note on the same value (1.5)", () => { + const a = compileRecipe("## Section\n\nBake at ^{180C}(fan).\n"); + const b = compileRecipe("## Section\n\nBake at ^{180C}(grill).\n"); + const { temperatures } = diffRecipes(a, b); + expect(temperatures).toHaveLength(1); + expect(temperatures[0]?.from).toMatchObject({ value: 180, note: "fan" }); + expect(temperatures[0]?.to).toMatchObject({ value: 180, note: "grill" }); + const c = compileRecipe("## Section\n\nBake at ^{180C}.\n"); + const added = diffRecipes(c, a).temperatures; + expect(added).toHaveLength(1); + expect(added[0]?.from && "note" in added[0].from).toBe(false); + }); + it("reports no change when both value and range are identical", () => { const a = compileRecipe("## Section\nBake at ^{200-300C}.\n"); const b = compileRecipe("## Section\nBake at ^{200-300C}.\n"); diff --git a/packages/cli/src/prompts/gram-spec.ts b/packages/cli/src/prompts/gram-spec.ts index bdedd075..6c3b7a80 100644 --- a/packages/cli/src/prompts/gram-spec.ts +++ b/packages/cli/src/prompts/gram-spec.ts @@ -432,7 +432,7 @@ RULE — active vs passive vs sequential: ### Temperatures -Syntax: \`^name?{value}\` +Syntax: \`^name?{value}(note)?\` \`^\` is the ONLY valid temperature sigil — never \`°\`, which is not a recognized element trigger. The degree sign is still used inside the unit itself (\`°C\`/\`°F\`), and is also accepted bare (\`C\`/\`F\`), case-insensitively. @@ -441,10 +441,13 @@ Syntax: \`^name?{value}\` | Exact | \`^{180C}\` | Numeric temperature; unit mandatory, one of \`C\`, \`F\`, \`°C\`, \`°F\` (case-insensitive) | | Semantic | \`^{medium heat}\` | Stove settings, water state, etc. | | Named | \`^oven{180C}\` | When multiple heat sources are active | +| With note | \`^{160C}(fan)\` | Cooking mode, probe target, or condition that goes with the temperature | Range: \`^{180-200C}\` The compiler stores the raw numeric value and normalizes the unit to \`°C\`/\`°F\`; the display engine handles further formatting. Only Celsius and Fahrenheit are supported — no Kelvin or other scales. +Note: when the source gives the oven mode or what the temperature is measured on (fan, convection, broil, conventional, internal, covered), keep it in the note glued to the brace — \`^{160C}(fan)\`, \`^{63C}(internal)\`, \`^{high heat}(covered)\` — instead of leaving it in the prose. Keep the note in the recipe's language. The parenthesis must touch the \`}\`: \`^{180C} (preheated)\` with a space is ordinary text. One line, no nested parentheses. + ═════════════════════════════════════════ SECTION 6 — INTERMEDIATE PREPARATIONS diff --git a/packages/cli/src/ui/cook/StepView.tsx b/packages/cli/src/ui/cook/StepView.tsx index 42a85bc0..f1c41b79 100644 --- a/packages/cli/src/ui/cook/StepView.tsx +++ b/packages/cli/src/ui/cook/StepView.tsx @@ -1,24 +1,15 @@ import React from "react"; import { Box, Text } from "ink"; import chalk from "chalk"; -import { formatTimerDuration } from "@gram-lang/renderer"; +import { formatTemperature, formatTimerDuration } from "@gram-lang/renderer"; import type { ActiveTimer, FlatStep } from "./types"; import type { CompilationResult } from "@gram-lang/kitchen"; import { fmtQty, fmtMass, fmtCountdown, shouldShowMass } from "./prepare"; -function getQtyText(q: any): string { - if (!q) return ""; - if (typeof q === "number") return String(q); - return ( - q.text ?? - (q.value != null - ? String(typeof q.value === "object" ? q.value.value : q.value) - : "") - ); -} - -function getTempDisplay(token: any): string { - return `${getQtyText(token.quantity)}${token.unit ?? "°"}`; +/** A temperature as the views show it (`180 °C`, `vif`), with its note. */ +export function getTempDisplay(token: any): string { + const value = formatTemperature(token); + return token.note ? `${value} (${token.note})` : value; } /** A timer as the views show it (`1 h 30 min`, `1–2 h`), or as written when refused. */ diff --git a/packages/cli/src/ui/diff.ts b/packages/cli/src/ui/diff.ts index 1b93c5a2..bd84d459 100644 --- a/packages/cli/src/ui/diff.ts +++ b/packages/cli/src/ui/diff.ts @@ -29,9 +29,13 @@ function fmtMetaValue(v: unknown): string { return String(v); } -function fmtTempValue(v?: { value: number; unit: string }): string { +function fmtTempValue(v?: { + value: number; + unit: string; + note?: string; +}): string { if (!v) return "?"; - return `${v.value}${v.unit}`; + return `${v.value}${v.unit}${v.note ? ` (${v.note})` : ""}`; } const TIMING_LABELS: Record = { diff --git a/packages/cli/tests/cook-temperatures.test.ts b/packages/cli/tests/cook-temperatures.test.ts new file mode 100644 index 00000000..efc99afd --- /dev/null +++ b/packages/cli/tests/cook-temperatures.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "bun:test"; +import { compile } from "@gram-lang/kitchen"; +import { getAST } from "@gram-lang/parser"; +import { getTempDisplay } from "../src/ui/cook/StepView"; + +// biome-ignore lint/suspicious/noExplicitAny: reading a compiled step token. +const temperatureOf = (step: string): any => + compile(getAST(`## A\n\n${step}\n`)).sections[0]?.steps[0]?.content.find( + // biome-ignore lint/suspicious/noExplicitAny: reading a compiled step token. + (c: any) => c?.type === "temperature", + ); + +// `gram cook` shows a temperature the way the views do, with its note. +describe("gram cook temperatures", () => { + it("shows the value and unit like the views", () => { + expect(getTempDisplay(temperatureOf("Bake at ^{180°C}."))).toBe("180 °C"); + }); + + it("shows a temperature in words", () => { + expect(getTempDisplay(temperatureOf("Cook on ^{high}."))).toBe("high"); + }); + + it("shows the note after the value (1.5)", () => { + expect(getTempDisplay(temperatureOf("Bake at ^{160°C}(fan)."))).toBe( + "160 °C (fan)", + ); + }); +}); diff --git a/packages/docs/public/llms-full.txt b/packages/docs/public/llms-full.txt index 3cb0f343..be59b874 100644 --- a/packages/docs/public/llms-full.txt +++ b/packages/docs/public/llms-full.txt @@ -1085,6 +1085,33 @@ When the Gram compiler inspects a `^temperature` token: - If it starts with non-numeric text, it is treated as a **Semantic temperature** string. ::: +## Cooking mode and notes +*(since v1.5.0)* + +A note in parentheses, right after the closing brace, says what goes with the temperature: the oven mode, where it is measured, how to cook. It works on exact and semantic temperatures, named or not, the way a preparation follows an ingredient. + +```gram +Preheat the #oven to ^{160°C}(fan). + +Roast until the meat reaches ^{63°C}(internal). + +Cook on ^stove{high heat}(uncovered) for ~{5min}. +``` + +The note is always shown next to the temperature, on screen and on paper, since baking at 160 °C fan or conventional is not the same thing. It is words for the cook, in the recipe's language: Gram keeps it as written and never reads it. + +:::caution[No space before the parenthesis] +Only a parenthesis that touches the `}` is a note, and it ends on the same line. With a space, the parenthesis stays part of the sentence: + +```gram +Bake at ^{180°C}(fan). + +Bake at ^{180°C} (the oven must be hot). +``` + +The first temperature has the note `fan`; the second has none, and `(the oven must be hot)` is ordinary text. +::: + ## Error handling Only Celsius and Fahrenheit temperature scales are supported. The compiler emits structured warnings when encountering malformed temperature values: @@ -1540,6 +1567,7 @@ Specialized patterns for flexible culinary instructions: | **Passive timer** | `~_` | `~_{1h}` | Represents resting/rising time without blocking the cook. | | **Named timer** | `~name{...}` | `~eggs{3min}`, `~_oven{45min}` | Queues resource-constrained steps (named tracks). | | **Semantic temperature** | `^{text}` | `^{medium heat}`, `^{simmer}` | Expresses qualitative stove settings. | +| **Temperature note** | `^{...}(note)` | `^{160°C}(fan)`, `^{63°C}(internal)` | Oven mode or condition, always shown; the parenthesis touches the brace. Since 1.5.0. | | **Fractions** | `n/d` or Unicode | `@flour{1 1/2 cups}`, `@sugar{½ cup}` | Fully supported across imperial and metric systems. | | **Sum of quantities** | `a + b`, `a - b` | `@flour{1 cup + 1 tbsp}`, `@sugar{1 cup - 2 tbsp}`, `@rice{1 cup + 20 g}` | Kept as written and added up; a volume and a weight stay side by side. Since 1.5.0. | @@ -1661,6 +1689,15 @@ Quantities and timers need a real number (or empty braces for "to taste"); fuzzy ``` Write an amount the recipe gives in several measures as a [sum](/docs/reference/syntax/ingredients/#sums-of-quantities), exactly as the source says it: "1 cup plus 1 tablespoon" is `{1 cup + 1 tbsp}`, "1 cup minus 2 tablespoons" is `{1 cup - 2 tbsp}`, and a volume next to a weight is fine (`{1 cup + 20 g}`). Don't work it out into one number either (`{1.0625 cup}`, `{17 tbsp}`): Gram adds the terms itself and shows them as the cook measures them. Every term needs its unit, and a term is only an amount: no percentage (`{100g + 10%}`), no multiplication (`{2 x 100g}`), no range after `-` (a range may be a term that is added: `{1 cup + 1-2 tbsp}`). +### The oven mode left in the prose +*(since v1.5.0)* + +```gram +❌ Bake at ^{160°C} fan. → ✅ Bake at ^{160°C}(fan). +❌ Bake at ^{180°C} (fan). → ✅ Bake at ^{180°C}(fan). +``` +What goes with a temperature (the oven mode, "internal", "covered") belongs in a [note](/docs/reference/syntax/temperatures/#cooking-mode-and-notes) glued to the closing brace, in the recipe's language. With a space before it, the parenthesis is ordinary text and the note is lost. + ### Using `@&` on the first occurrence ```gram diff --git a/packages/docs/src/content/docs/docs/reference/syntax/ai-generation-notes.mdx b/packages/docs/src/content/docs/docs/reference/syntax/ai-generation-notes.mdx index 93142524..614f97a5 100644 --- a/packages/docs/src/content/docs/docs/reference/syntax/ai-generation-notes.mdx +++ b/packages/docs/src/content/docs/docs/reference/syntax/ai-generation-notes.mdx @@ -79,6 +79,15 @@ Quantities and timers need a real number (or empty braces for "to taste"); fuzzy ``` Write an amount the recipe gives in several measures as a [sum](/docs/reference/syntax/ingredients/#sums-of-quantities), exactly as the source says it: "1 cup plus 1 tablespoon" is `{1 cup + 1 tbsp}`, "1 cup minus 2 tablespoons" is `{1 cup - 2 tbsp}`, and a volume next to a weight is fine (`{1 cup + 20 g}`). Don't work it out into one number either (`{1.0625 cup}`, `{17 tbsp}`): Gram adds the terms itself and shows them as the cook measures them. Every term needs its unit, and a term is only an amount: no percentage (`{100g + 10%}`), no multiplication (`{2 x 100g}`), no range after `-` (a range may be a term that is added: `{1 cup + 1-2 tbsp}`). +### The oven mode left in the prose + + +```gram +❌ Bake at ^{160°C} fan. → ✅ Bake at ^{160°C}(fan). +❌ Bake at ^{180°C} (fan). → ✅ Bake at ^{180°C}(fan). +``` +What goes with a temperature (the oven mode, "internal", "covered") belongs in a [note](/docs/reference/syntax/temperatures/#cooking-mode-and-notes) glued to the closing brace, in the recipe's language. With a space before it, the parenthesis is ordinary text and the note is lost. + ### Using `@&` on the first occurrence ```gram diff --git a/packages/docs/src/content/docs/docs/reference/syntax/cheatsheet.mdx b/packages/docs/src/content/docs/docs/reference/syntax/cheatsheet.mdx index cede41d4..1784294a 100644 --- a/packages/docs/src/content/docs/docs/reference/syntax/cheatsheet.mdx +++ b/packages/docs/src/content/docs/docs/reference/syntax/cheatsheet.mdx @@ -45,6 +45,7 @@ Specialized patterns for flexible culinary instructions: | **Passive timer** | `~_` | `~_{1h}` | Represents resting/rising time without blocking the cook. | | **Named timer** | `~name{...}` | `~eggs{3min}`, `~_oven{45min}` | Queues resource-constrained steps (named tracks). | | **Semantic temperature** | `^{text}` | `^{medium heat}`, `^{simmer}` | Expresses qualitative stove settings. | +| **Temperature note** | `^{...}(note)` | `^{160°C}(fan)`, `^{63°C}(internal)` | Oven mode or condition, always shown; the parenthesis touches the brace. Since 1.5.0. | | **Fractions** | `n/d` or Unicode | `@flour{1 1/2 cups}`, `@sugar{½ cup}` | Fully supported across imperial and metric systems. | | **Sum of quantities** | `a + b`, `a - b` | `@flour{1 cup + 1 tbsp}`, `@sugar{1 cup - 2 tbsp}`, `@rice{1 cup + 20 g}` | Kept as written and added up; a volume and a weight stay side by side. Since 1.5.0. | diff --git a/packages/docs/src/content/docs/docs/reference/syntax/temperatures.mdx b/packages/docs/src/content/docs/docs/reference/syntax/temperatures.mdx index 293290ab..19f27f48 100644 --- a/packages/docs/src/content/docs/docs/reference/syntax/temperatures.mdx +++ b/packages/docs/src/content/docs/docs/reference/syntax/temperatures.mdx @@ -4,6 +4,7 @@ description: "Define exact or semantic ^temperatures in Celsius or Fahrenheit, w --- import { CardGrid, LinkCard, Tabs, TabItem } from '@astrojs/starlight/components'; +import Since from '../../../../../components/Since.astro'; You can declare thermal instructions in your recipes using the `^` symbol. @@ -46,6 +47,33 @@ When the Gram compiler inspects a `^temperature` token: - If it starts with non-numeric text, it is treated as a **Semantic temperature** string. ::: +## Cooking mode and notes + + +A note in parentheses, right after the closing brace, says what goes with the temperature: the oven mode, where it is measured, how to cook. It works on exact and semantic temperatures, named or not, the way a preparation follows an ingredient. + +```gram +Preheat the #oven to ^{160°C}(fan). + +Roast until the meat reaches ^{63°C}(internal). + +Cook on ^stove{high heat}(uncovered) for ~{5min}. +``` + +The note is always shown next to the temperature, on screen and on paper, since baking at 160 °C fan or conventional is not the same thing. It is words for the cook, in the recipe's language: Gram keeps it as written and never reads it. + +:::caution[No space before the parenthesis] +Only a parenthesis that touches the `}` is a note, and it ends on the same line. With a space, the parenthesis stays part of the sentence: + +```gram +Bake at ^{180°C}(fan). + +Bake at ^{180°C} (the oven must be hot). +``` + +The first temperature has the note `fan`; the second has none, and `(the oven must be hot)` is ordinary text. +::: + ## Error handling Only Celsius and Fahrenheit temperature scales are supported. The compiler emits structured warnings when encountering malformed temperature values: diff --git a/packages/docs/src/content/docs/fr/docs/reference/syntax/ai-generation-notes.mdx b/packages/docs/src/content/docs/fr/docs/reference/syntax/ai-generation-notes.mdx index 729b9395..b672726b 100644 --- a/packages/docs/src/content/docs/fr/docs/reference/syntax/ai-generation-notes.mdx +++ b/packages/docs/src/content/docs/fr/docs/reference/syntax/ai-generation-notes.mdx @@ -79,6 +79,15 @@ Les quantités et les minuteurs ont besoin d'un vrai nombre (ou d'accolades vide ``` Une quantité que la recette donne en plusieurs mesures s'écrit en [somme](/fr/docs/reference/syntax/ingredients/#sommes-de-quantités), telle que la source la formule : « 1 tasse plus 1 cuillère à soupe » donne `{1 cup + 1 tbsp}`, « 1 tasse moins 2 cuillères à soupe » donne `{1 cup - 2 tbsp}`, et un volume peut côtoyer une masse (`{1 cup + 20 g}`). Ne la convertissez pas non plus en un seul nombre (`{1.0625 cup}`, `{17 tbsp}`) : Gram additionne les termes lui-même et les affiche comme on les mesure. Chaque terme a son unité, et un terme n'est qu'une quantité : pas de pourcentage (`{100g + 10%}`), pas de multiplication (`{2 x 100g}`), pas de fourchette après un `-` (une fourchette peut être un terme ajouté : `{1 cup + 1-2 tbsp}`). +### Le mode du four laissé dans la phrase + + +```gram +❌ Cuire à ^{160°C} chaleur tournante. → ✅ Cuire à ^{160°C}(chaleur tournante). +❌ Cuire à ^{180°C} (chaleur tournante). → ✅ Cuire à ^{180°C}(chaleur tournante). +``` +Ce qui accompagne une température (le mode du four, « à cœur », « à couvert ») va dans une [précision](/fr/docs/reference/syntax/temperatures/#mode-de-cuisson-et-précisions) collée à l'accolade fermante, dans la langue de la recette. Avec un espace devant, la parenthèse reste du texte et la précision est perdue. + ### Utiliser `@&` dès la première occurrence ```gram diff --git a/packages/docs/src/content/docs/fr/docs/reference/syntax/cheatsheet.mdx b/packages/docs/src/content/docs/fr/docs/reference/syntax/cheatsheet.mdx index 0f0d85a3..fb440d28 100644 --- a/packages/docs/src/content/docs/fr/docs/reference/syntax/cheatsheet.mdx +++ b/packages/docs/src/content/docs/fr/docs/reference/syntax/cheatsheet.mdx @@ -45,6 +45,7 @@ Formulations complémentaires pour enrichir la description des étapes : | **Minuteur passif** | `~_` | `~_{1h}` | Modélise un repos ou une pousse sans monopoliser le cuisinier. | | **Minuteur nommé** | `~nom{...}` | `~œufs{3min}`, `~_four{45min}` | Linéarise l'accès à un équipement partagé (piste dédiée). | | **Température sémantique** | `^{texte}` | `^{feu moyen}`, `^{frémissement}` | Exprime une intensité de chauffe qualitative. | +| **Précision de température** | `^{...}(précision)` | `^{160°C}(chaleur tournante)`, `^{63°C}(à cœur)` | Mode du four ou condition, toujours affichée ; la parenthèse est collée à l'accolade. Depuis la 1.5.0. | | **Fractions** | `n/d` ou Unicode | `@farine{1 1/2 tasse}`, `@sucre{½ tasse}` | Prises en charge complètes en système métrique comme impérial. | | **Somme de quantités** | `a + b`, `a - b` | `@farine{1 kg + 200 g}`, `@lait{1 l - 10 cl}`, `@riz{1 tasse + 20 g}` | Gardée telle qu'écrite et additionnée ; un volume et une masse restent côte à côte. Depuis la 1.5.0. | diff --git a/packages/docs/src/content/docs/fr/docs/reference/syntax/temperatures.mdx b/packages/docs/src/content/docs/fr/docs/reference/syntax/temperatures.mdx index b3ece00e..65713d83 100644 --- a/packages/docs/src/content/docs/fr/docs/reference/syntax/temperatures.mdx +++ b/packages/docs/src/content/docs/fr/docs/reference/syntax/temperatures.mdx @@ -4,6 +4,7 @@ description: "Définissez des ^températures exactes ou sémantiques en Celsius --- import { CardGrid, LinkCard, Tabs, TabItem } from '@astrojs/starlight/components'; +import Since from '../../../../../../components/Since.astro'; Les consignes thermiques de cuisson se déclarent au sein des étapes de recette à l'aide du symbole `^`. @@ -46,6 +47,33 @@ Lorsque le compilateur Gram traite un élément `^température` : - S'il commence par une lettre ou un mot, l'ensemble du contenu est traité comme une **température sémantique**. ::: +## Mode de cuisson et précisions + + +Une précision entre parenthèses, collée à l'accolade fermante, accompagne la température : le mode du four, l'endroit où on la mesure, la façon de cuire. Elle s'écrit sur les températures exactes comme sémantiques, nommées ou non, comme la préparation d'un ingrédient. + +```gram +Préchauffer le #four à ^{160°C}(chaleur tournante). + +Rôtir jusqu'à ^{63°C}(à cœur). + +Faire revenir sur ^plaque{feu vif}(à découvert) pendant ~{5min}. +``` + +La précision s'affiche toujours à côté de la température, à l'écran comme sur papier : cuire à 160 °C en chaleur tournante ou en statique, ce n'est pas la même chose. C'est un mot pour le cuisinier, dans la langue de la recette : Gram la garde telle quelle et ne l'interprète jamais. + +:::caution[Pas d'espace avant la parenthèse] +Seule une parenthèse collée à la `}` est une précision, et elle se termine sur la même ligne. Avec un espace, la parenthèse reste dans la phrase : + +```gram +Cuire à ^{180°C}(chaleur tournante). + +Cuire à ^{180°C} (le four doit être bien chaud). +``` + +La première température porte la précision `chaleur tournante` ; la seconde n'en a pas, et `(le four doit être bien chaud)` reste du texte. +::: + ## Gestion des erreurs Seules les échelles Celsius et Fahrenheit sont prises en charge. Le compilateur émet des avertissements structurés en présence de formats inattendus : diff --git a/packages/format/tests/formatter.test.ts b/packages/format/tests/formatter.test.ts index a9714243..29ed28c3 100644 --- a/packages/format/tests/formatter.test.ts +++ b/packages/format/tests/formatter.test.ts @@ -392,3 +392,17 @@ describe("formatGram and sums of quantities", () => { expect(quantities(formatGram(source).content)).toEqual(before); }); }); + +describe("a temperature's note (1.5)", () => { + it("keeps a glued note while fixing the braces", () => { + expect( + formatGram("## T\n\n^{160.0°C}(chaleur tournante)\n").content, + ).toContain("^{160°C}(chaleur tournante)"); + }); + + it("leaves the space before a parenthesis of prose", () => { + expect( + formatGram("## T\n\nCuire à ^{180°C} (four préchauffé).\n").content, + ).toContain("^{180°C} (four préchauffé)."); + }); +}); diff --git a/packages/kitchen/src/processor.ts b/packages/kitchen/src/processor.ts index ce10f98d..20d2ed45 100644 --- a/packages/kitchen/src/processor.ts +++ b/packages/kitchen/src/processor.ts @@ -754,6 +754,7 @@ function processTemperature( }); } } + if (item.note) obj.note = item.note; return obj; } diff --git a/packages/kitchen/src/types.ts b/packages/kitchen/src/types.ts index 80c416df..b2db250f 100644 --- a/packages/kitchen/src/types.ts +++ b/packages/kitchen/src/types.ts @@ -156,6 +156,11 @@ export interface ProcessedTemperature { text?: string; quantity?: QuantityValueAST; unit?: string; + /** + * The note glued to the temperature (`^{160°C}(fan)`): words for the + * cook, never read by Gram. Omitted when there is none. Since 1.5.0. + */ + note?: string; } /** diff --git a/packages/kitchen/tests/temperature-and-slugify.test.ts b/packages/kitchen/tests/temperature-and-slugify.test.ts index cdfa0c73..d78687d2 100644 --- a/packages/kitchen/tests/temperature-and-slugify.test.ts +++ b/packages/kitchen/tests/temperature-and-slugify.test.ts @@ -93,3 +93,34 @@ describe("slugify", () => { expect(slug).toBe(slugify("🔥🔥🔥")); }); }); + +describe("a temperature's note (1.5)", () => { + // biome-ignore lint/suspicious/noExplicitAny: reading a compiled step token. + const temperature = (line: string): any => + compile( + getAST(`## Section\n\n${line}\n`), + ).sections[0]?.steps[0]?.content.find( + // biome-ignore lint/suspicious/noExplicitAny: reading a compiled step token. + (c: any) => c?.type === "temperature", + ); + + it("is carried into the compiled token", () => { + expect(temperature("Bake at ^oven{160°C}(fan).")).toEqual({ + type: "temperature", + name: "oven", + quantity: { type: "single", value: 160, text: "160" }, + unit: "°C", + note: "fan", + }); + expect(temperature("Cook on ^{high}(covered).")).toEqual({ + type: "temperature", + text: "high", + note: "covered", + }); + }); + + it("is left out when there is none, or when it is empty", () => { + expect("note" in temperature("Bake at ^{160°C}.")).toBe(false); + expect("note" in temperature("Bake at ^{160°C}().")).toBe(false); + }); +}); diff --git a/packages/language-server/src/features/semantic-tokens.ts b/packages/language-server/src/features/semantic-tokens.ts index feafb63d..f8ed4d87 100644 --- a/packages/language-server/src/features/semantic-tokens.ts +++ b/packages/language-server/src/features/semantic-tokens.ts @@ -245,7 +245,9 @@ function walkTemperature( const body = text.slice(bodyStart, temp.loc.end); const braceOpen = body.indexOf("{"); if (braceOpen >= 0) { - const braceClose = body.lastIndexOf("}"); + // The first `}` after `{`, not the last one: a note glued to the + // brace (`^{180°C}(mode } spécial)`) may hold one. A quantity cannot. + const braceClose = body.indexOf("}", braceOpen + 1); const absOpen = bodyStart + braceOpen; const absClose = bodyStart + (braceClose >= 0 ? braceClose : body.length - 1); diff --git a/packages/language-server/tests/semantic-tokens.test.ts b/packages/language-server/tests/semantic-tokens.test.ts index b120b584..65b24a73 100644 --- a/packages/language-server/tests/semantic-tokens.test.ts +++ b/packages/language-server/tests/semantic-tokens.test.ts @@ -27,3 +27,26 @@ describe("provideSemanticTokens on non-Section top-level content", () => { expect(data.length).toBeGreaterThan(0); }); }); + +describe("provideSemanticTokens on a temperature's note (1.5)", () => { + // The start column of each token of a one-line document. + const starts = (text: string): number[] => { + const { data } = provideSemanticTokens(parseDocument(text)); + const out: number[] = []; + let col = 0; + for (let i = 0; i < data.length; i += 5) { + col = data[i] === 0 ? col + (data[i + 1] ?? 0) : (data[i + 1] ?? 0); + out.push(col); + } + return out; + }; + + it("marks the temperature's own braces, not a brace in its note", () => { + // ^ at 0, { at 1, } at 7: the `}` inside the note is left alone. + expect(starts("^{180°C}(mode } x)\n")).toEqual([0, 1, 7]); + }); + + it("emits nothing on the note itself", () => { + expect(starts("^{180°C}(fan)\n")).toEqual([0, 1, 7]); + }); +}); diff --git a/packages/parser/grammar.ohm b/packages/parser/grammar.ohm index a05171f2..e3d7362f 100644 --- a/packages/parser/grammar.ohm +++ b/packages/parser/grammar.ohm @@ -94,7 +94,7 @@ GRAM { | Ingredient | Cookware | Timer - | Temperature + | temperature | Reference | CommentBlock | Comment @@ -204,7 +204,18 @@ GRAM { timerText = "{" (~("}" | nl) any)* "}" // Temperature - Temperature = "^" name? (ingredientQuantity | textQuantity) + // Lexical, so only a note glued to `}` is one: `^{180°C}(fan)` has a note, + // `^{180°C} (preheated)` keeps its parenthesis in the prose. `name` may + // start with a space, as it could when the rule was syntactic: `^ {180°C}` + // and `^oven {180°C}` read as before (`clean` drops the space). The note + // since 1.5.0. + temperature = "^" name? (ingredientQuantity | textQuantity) gluedNote? + + // A note glued to an element's closing brace, on one line: an unclosed + // `(` is prose, never the start of a note that would run to the next `)` + // further down the recipe. Meant to be shared by the elements to come + // (the sensory checkpoints). + gluedNote = "(" (~(")" | nl) any)* ")" // Comments diff --git a/packages/parser/src/grammar-content.ts b/packages/parser/src/grammar-content.ts index 81627ef7..052b7ef9 100644 --- a/packages/parser/src/grammar-content.ts +++ b/packages/parser/src/grammar-content.ts @@ -1,2 +1,2 @@ // AUTO-GENERATED FILE. DO NOT EDIT. -export const grammarContent = "GRAM {\n Recipe = Frontmatter? UseBlock? Content?\n\n Content =\n | (nl* Block)* (nl* Section)+ -- explicit\n | (nl* Block)+ -- implicit\n\n Frontmatter = \"---\" nl KeyValue* \"---\" (nl | end)\n emptyLine = sp* nl\n KeyValue = emptyLine* key \":\" sp* value nl\n key = (alnum | \"_\" | \"-\")+\n value = (~nl any)*\n\n // Import directives, constrained between the frontmatter and the content --\n // this is what makes \"@use\" unambiguous with an ingredient literally named\n // \"use\" that happens to appear in a step (unchanged, still parses as such).\n // The block must open with a real `UseDirective`: a leading `UseComment` on\n // its own (no `@use` anywhere in the block) is deliberately NOT swallowed\n // here, so a document with no imports at all keeps treating its opening\n // comment as ordinary content, exactly as before this feature existed. Once\n // the block has started, a comment between two directives doesn't break it.\n UseBlock = nl* useDirective (nl* (useDirective | useComment))*\n useComment = applySyntactic nl\n useDirective = \"@use\" sp+ moduleSpecifier sp+ \"as\" sp+ bindings sp* retroPlanning? sp* (nl | end)\n moduleSpecifier = \"\\\"\" (~(\"\\\"\" | nl) any)+ \"\\\"\"\n bindings =\n | \"{\" sp* binding moreBindings* sp* \"}\" -- named\n | binding -- default\n moreBindings = sp* \",\" sp* binding\n binding = \"&\" bindingName (sp+ \"as\" sp+ \"&\" bindingName)?\n bindingName =\n | bindingFullName \"{}\" -- full\n | bindingBareName -- bare\n // Unlike `name`, this must stop at \",\" and \"&\" -- a `{}`-delimited multi-word\n // binding sits inside a comma-separated list (`{ &a, &b multi{} }`) and can be\n // followed by a rename (`&a as &b multi{}`), so it must not swallow past the\n // next binding's separator or sigil while scanning ahead for its own \"{}\".\n bindingFullName = (~bindingFullNameStop any)+\n bindingFullNameStop = syntaxChar | nl | \",\" | refSigil\n bindingBareName = (~bindingStop any)+\n bindingStop = space | nl | syntaxChar | sentencePunct | \"~{\"\n\n Section = header Block*\n header =\n | \"##\" sp+ title headerExtension? sp* (nl+ | end) -- ok\n | \"##\" sp+ title headerExtension sp* headerTrailing (nl+ | end) -- trailing\n // Text left after a header's `~{...}` / `->&name` (most often the second\n // word of a multi-word intermediate written without `{}`). Without this\n // branch the whole `##` line silently fell back to a step: the section\n // vanished, or its `~{-1d}` anchor surfaced as a misleading timer error.\n // Matched only to raise a readable error (see `header_trailing`).\n headerTrailing = (~nl any)+\n headerExtension = \n | retroPlanning sp* intermediateDecl? -- retro\n | intermediateDecl sp* retroPlanning? -- decl\n titleStop = nl | \"->&\" | \"~{\"\n title = (~titleStop any)*\n \n retroPlanning = \"~{\" (~\"}\" any)+ \"}\"\n \n Block = \n | Comment nl* -- comment\n | (~header step) -- step\n \n step = startAction? line (nl line)* (nl+ | end)\n startAction = \"[\" (~\"]\" any)+ \"]\" sp*\n line = stepContent+\n stepContent =\n | invalidUseDirective\n | invalidComposite\n | invalidAlternativeBar\n | text\n | ws\n | intermediateDecl\n | applySyntactic\n | fallback\n\n // A `@use \"...\"` past the import block (after the first step, misspelled,\n // or otherwise misplaced) would otherwise silently parse as an ingredient\n // literally named \"use\" followed by prose -- this turns it into a readable\n // error instead. Only triggers on the exact `@use \"` prefix, so an actual\n // ingredient named \"use\" followed by unrelated quoted text is unaffected.\n invalidUseDirective = \"@use\" sp+ \"\\\"\"\n\n invalidComposite = space+ \"<\" space* \"@\" name\n\n invalidAlternativeBar = \"|\"\n\n ws = space+\n\n fallback = ~nl any\n\n Element = \n | Ingredient\n | Cookware\n | Timer\n | Temperature\n | Reference\n | CommentBlock\n | Comment\n\n intermediateDecl =\n | \"->&\" name \"{}\" -- full\n | \"->&\" singleWordName -- bare\n\n // Ingredients\n Ingredient = \n | Alternative\n | simpleIngredient\n\n Alternative = simpleIngredient (\"|\" simpleIngredient)+\n \n // Rule: Quantity is mandatory unless it's a single word name\n // Uses refName (not name) so a bare @&chicken mention can't have its name\n // greedily swallow everything up to an unrelated later {...} that happens\n // to close a valid ingredientAmount -- e.g. \"@&chicken for ~{3min}\" must\n // stop at \"~\" and fall back to the bare alternative, not consume \"chicken\n // for ~\" as a bogus multi-word name with the timer's quantity attached.\n simpleIngredient =\n | \"@\" modifier* refName alias? ingredientAmount preparation? composite? -- full\n | \"@\" modifier* refName alias? malformedBraces -- malformed\n | \"@\" modifier* singleWordName alias? preparation? composite? -- bare\n\n modifier = \"?\" | \"-\" | \"*\" | \"&\" | \"=\"\n alias = \":\" refName\n ingredientQuantity = \"{\" space* (relativeQuantity | absoluteQuantity) space* \"}\"\n // The amount of an ingredient, a composite parent or a reference: an\n // ingredientQuantity, or a sum of quantities (`{1 cup + 1 tbsp}`,\n // `{1 cup - 2 tbsp}`). Since 1.5.0. Timers and temperatures keep\n // ingredientQuantity. PEG order matters: a choice that matches a prefix is\n // final, so a plain quantity is only taken when the braces close right\n // after it (`&`), otherwise it would take `1 cup` from `{1 cup + 1 tbsp}`\n // and fail on the `+`. Tried before the sum, it also keeps its range\n // (`{1 - 2 cup}` is one range, not 1 minus 2 cups) and its AST.\n ingredientAmount = \"{\" space* (relativeQuantity | closedQuantity | compoundQuantity) space* \"}\"\n closedQuantity = absoluteQuantity &(space* \"}\")\n compoundQuantity = quantityTerm (space* compoundOp space* quantityTerm)+\n // The unit is optional so `{1 + 1 cup}` reaches the compiler, which says\n // what is wrong with it, instead of failing as a syntax error.\n quantityTerm = (range | number) (space* unit)?\n compoundOp = \"+\" | \"-\"\n relativeQuantity = number space* \"%\" space* (\"@&\" | \"&\") space* name\n absoluteQuantity = (range | number)? space* (unit space*)?\n textQuantity = \"{\" space* (~\"}\" any)+ space* \"}\"\n fixed = \"=\"\n // A unit is one or more words. A word may contain \".\" or an apostrophe after\n // its first character (c.à.s, fl. oz., d'eau) but never starts with one, so a\n // stray \"{1. kg}\" or \"{.5 g}\" is still rejected rather than half-parsed.\n unit = unitName\n unitName = unitWord (sp+ unitWord)*\n unitWord = unitLead unitChar*\n unitLead = alnum | \"°\" | \"%\"\n unitChar = unitLead | \".\" | \"'\" | \"’\"\n\n // A \"{...}\" glued to an element that did not parse as a valid quantity. Without\n // this, the element silently fell back to its bare form (name truncated to its\n // first word) and the braces leaked into prose -- merging distinct ingredients.\n // Each \"-- malformed\" branch below turns that into a readable error instead.\n malformedBraces = \"{\" (~(\"}\" | nl) any)* (\"}\" | &nl | end)\n preparation = \"(\" (~\")\" any)* \")\"\n // `modifier*` mirrors simpleIngredient: a composite parent is an ingredient\n // reference like any other, and authors (and AI importers) write `<@&parent`\n // to mark a parent already introduced earlier. Without it, `refName` rejected\n // the leading \"&\" (it is a refSigil), the `bare` branch fell through to\n // `singleWordName` -- which does allow \"&\" -- and a multi-word parent silently\n // truncated at the first space, registering a phantom ingredient literally\n // named \"&citron\" alongside the real one. The modifiers are parsed and then\n // ignored (see composite_full/composite_bare): \"&\" is redundant on a parent\n // because the MAX rule already collapses repeat draws into one purchase.\n composite =\n | \"<@\" modifier* refName ingredientAmount preparation? -- full\n | \"<@\" modifier* refName malformedBraces -- malformed\n | \"<@\" modifier* singleWordName preparation? -- bare\n\n // Cookware\n Cookware =\n | CookwareAlternative\n | simpleCookware\n\n CookwareAlternative = simpleCookware (\"|\" simpleCookware)+\n // Same refName fix as simpleIngredient above -- a bare #pan mention must not\n // swallow an unrelated later {...} (e.g. another ingredient's integer-only\n // quantity) into its own name.\n simpleCookware =\n | \"#\" modifier* refName alias? cookwareQuantity preparation? -- full\n | \"#\" modifier* refName alias? malformedBraces -- malformed\n | \"#\" modifier* singleWordName alias? preparation? -- bare\n\n // Cookware quantity is numbers only, no units (e.g. {}, {2}) -- unlike ingredientQuantity.\n cookwareQuantity = \"{\" space* number? space* \"}\"\n\n // Timer\n // `ingredientQuantity` comes first (PEG order) so a plain timer keeps its\n // AST: `~{10 min}`, and also `~{1h30}`, read as 1 + unit \"h30\". Anything\n // else closed on the same line (`1:30 h`, `5'30\"`, `1h + 30min`, `1h30-2h`)\n // is kept as text. Either way the AST carries `raw`, the text between the\n // braces, and the compiler reads the duration from it (`parseDuration` in\n // @gram-lang/i18n), never from the quantity. Only an unclosed brace is\n // still a syntax error.\n Timer =\n | \"~\" \"_\"? name? ingredientQuantity -- full\n | \"~\" \"_\"? name? timerText -- text\n | \"~\" \"_\"? name? malformedBraces -- malformed\n timerText = \"{\" (~(\"}\" | nl) any)* \"}\"\n \n // Temperature\n Temperature = \"^\" name? (ingredientQuantity | textQuantity)\n\n\n // Comments\n Comment = \"//\" (~nl any)*\n CommentBlock = \"/*\" (~\"*/\" any)* \"*/\"\n\n // Primitives\n name = (~(syntaxChar | nl) any)+\n singleWordName = (~(syntaxChar | space | nl | sentencePunct) any)+\n sentencePunct = \",\" | \";\" | \"!\" | \"?\" | \".\"\n // Like name, but also stops at element sigils so a bare &dough is not consumed\n // into a Reference -- full when a sigil like # or @ appears later on the line.\n refName = (~(syntaxChar | refSigil | nl) any)+\n refSigil = \"@\" | \"#\" | \"~\" | \"^\" | \"&\"\n\n number = mixedFraction | unicodeFraction | plainNumber\n // \".\" or \",\" between two digits is a decimal separator (1.5, 1,5): Gram has\n // no thousands separator. A comma not between two digits ({1, 5 kg}) still\n // fails, so the commas of the prose around an element are never touched.\n plainNumber = digit+ ((\".\" | \",\") digit+)? (\"/\" digit+)?\n mixedFraction = digit+ sp+ digit+ \"/\" digit+\n unicodeFraction =\n | digit+ unicodeFractionChar -- mixed\n | unicodeFractionChar -- bare\n unicodeFractionChar = \"¼\" | \"½\" | \"¾\" | \"⅓\" | \"⅔\" | \"⅕\" | \"⅖\" | \"⅗\" | \"⅘\" | \"⅙\" | \"⅚\" | \"⅛\" | \"⅜\" | \"⅝\" | \"⅞\"\n range = number space* \"-\" space* number\n\n text = space* (~(elementStart | nl | \"|\") any)+\n\n Reference =\n | \"&\" refName ingredientAmount -- full\n | \"&\" refName malformedBraces -- malformed\n | \"&\" singleWordName -- bare\n\n // Delimiters that end a name (start of quantity/alias/preparation/composite/alternative).\n // @, #, ~, !, &, ?, * are deliberately absent here, so names may contain them freely --\n // only elementStart (below) treats those as starting a new element, and only in free text.\n syntaxChar = \"{\" | \"}\" | \"[\" | \"]\" | \"(\" | \")\" | \"<\" | \"|\" | \":\"\n\n // Stricter than syntaxChar: used to detect where an element starts within free text.\n elementStart = \"@\" | \"#\" | \"~\" | \"^\" | \"//\" | \"/*\" | \"->&\" | \"&\"\n \n nl = \"\\r\"? \"\\n\"\n sp = \" \" | \"\\t\"\n space := sp\n}\n"; +export const grammarContent = "GRAM {\n Recipe = Frontmatter? UseBlock? Content?\n\n Content =\n | (nl* Block)* (nl* Section)+ -- explicit\n | (nl* Block)+ -- implicit\n\n Frontmatter = \"---\" nl KeyValue* \"---\" (nl | end)\n emptyLine = sp* nl\n KeyValue = emptyLine* key \":\" sp* value nl\n key = (alnum | \"_\" | \"-\")+\n value = (~nl any)*\n\n // Import directives, constrained between the frontmatter and the content --\n // this is what makes \"@use\" unambiguous with an ingredient literally named\n // \"use\" that happens to appear in a step (unchanged, still parses as such).\n // The block must open with a real `UseDirective`: a leading `UseComment` on\n // its own (no `@use` anywhere in the block) is deliberately NOT swallowed\n // here, so a document with no imports at all keeps treating its opening\n // comment as ordinary content, exactly as before this feature existed. Once\n // the block has started, a comment between two directives doesn't break it.\n UseBlock = nl* useDirective (nl* (useDirective | useComment))*\n useComment = applySyntactic nl\n useDirective = \"@use\" sp+ moduleSpecifier sp+ \"as\" sp+ bindings sp* retroPlanning? sp* (nl | end)\n moduleSpecifier = \"\\\"\" (~(\"\\\"\" | nl) any)+ \"\\\"\"\n bindings =\n | \"{\" sp* binding moreBindings* sp* \"}\" -- named\n | binding -- default\n moreBindings = sp* \",\" sp* binding\n binding = \"&\" bindingName (sp+ \"as\" sp+ \"&\" bindingName)?\n bindingName =\n | bindingFullName \"{}\" -- full\n | bindingBareName -- bare\n // Unlike `name`, this must stop at \",\" and \"&\" -- a `{}`-delimited multi-word\n // binding sits inside a comma-separated list (`{ &a, &b multi{} }`) and can be\n // followed by a rename (`&a as &b multi{}`), so it must not swallow past the\n // next binding's separator or sigil while scanning ahead for its own \"{}\".\n bindingFullName = (~bindingFullNameStop any)+\n bindingFullNameStop = syntaxChar | nl | \",\" | refSigil\n bindingBareName = (~bindingStop any)+\n bindingStop = space | nl | syntaxChar | sentencePunct | \"~{\"\n\n Section = header Block*\n header =\n | \"##\" sp+ title headerExtension? sp* (nl+ | end) -- ok\n | \"##\" sp+ title headerExtension sp* headerTrailing (nl+ | end) -- trailing\n // Text left after a header's `~{...}` / `->&name` (most often the second\n // word of a multi-word intermediate written without `{}`). Without this\n // branch the whole `##` line silently fell back to a step: the section\n // vanished, or its `~{-1d}` anchor surfaced as a misleading timer error.\n // Matched only to raise a readable error (see `header_trailing`).\n headerTrailing = (~nl any)+\n headerExtension = \n | retroPlanning sp* intermediateDecl? -- retro\n | intermediateDecl sp* retroPlanning? -- decl\n titleStop = nl | \"->&\" | \"~{\"\n title = (~titleStop any)*\n \n retroPlanning = \"~{\" (~\"}\" any)+ \"}\"\n \n Block = \n | Comment nl* -- comment\n | (~header step) -- step\n \n step = startAction? line (nl line)* (nl+ | end)\n startAction = \"[\" (~\"]\" any)+ \"]\" sp*\n line = stepContent+\n stepContent =\n | invalidUseDirective\n | invalidComposite\n | invalidAlternativeBar\n | text\n | ws\n | intermediateDecl\n | applySyntactic\n | fallback\n\n // A `@use \"...\"` past the import block (after the first step, misspelled,\n // or otherwise misplaced) would otherwise silently parse as an ingredient\n // literally named \"use\" followed by prose -- this turns it into a readable\n // error instead. Only triggers on the exact `@use \"` prefix, so an actual\n // ingredient named \"use\" followed by unrelated quoted text is unaffected.\n invalidUseDirective = \"@use\" sp+ \"\\\"\"\n\n invalidComposite = space+ \"<\" space* \"@\" name\n\n invalidAlternativeBar = \"|\"\n\n ws = space+\n\n fallback = ~nl any\n\n Element = \n | Ingredient\n | Cookware\n | Timer\n | temperature\n | Reference\n | CommentBlock\n | Comment\n\n intermediateDecl =\n | \"->&\" name \"{}\" -- full\n | \"->&\" singleWordName -- bare\n\n // Ingredients\n Ingredient = \n | Alternative\n | simpleIngredient\n\n Alternative = simpleIngredient (\"|\" simpleIngredient)+\n \n // Rule: Quantity is mandatory unless it's a single word name\n // Uses refName (not name) so a bare @&chicken mention can't have its name\n // greedily swallow everything up to an unrelated later {...} that happens\n // to close a valid ingredientAmount -- e.g. \"@&chicken for ~{3min}\" must\n // stop at \"~\" and fall back to the bare alternative, not consume \"chicken\n // for ~\" as a bogus multi-word name with the timer's quantity attached.\n simpleIngredient =\n | \"@\" modifier* refName alias? ingredientAmount preparation? composite? -- full\n | \"@\" modifier* refName alias? malformedBraces -- malformed\n | \"@\" modifier* singleWordName alias? preparation? composite? -- bare\n\n modifier = \"?\" | \"-\" | \"*\" | \"&\" | \"=\"\n alias = \":\" refName\n ingredientQuantity = \"{\" space* (relativeQuantity | absoluteQuantity) space* \"}\"\n // The amount of an ingredient, a composite parent or a reference: an\n // ingredientQuantity, or a sum of quantities (`{1 cup + 1 tbsp}`,\n // `{1 cup - 2 tbsp}`). Since 1.5.0. Timers and temperatures keep\n // ingredientQuantity. PEG order matters: a choice that matches a prefix is\n // final, so a plain quantity is only taken when the braces close right\n // after it (`&`), otherwise it would take `1 cup` from `{1 cup + 1 tbsp}`\n // and fail on the `+`. Tried before the sum, it also keeps its range\n // (`{1 - 2 cup}` is one range, not 1 minus 2 cups) and its AST.\n ingredientAmount = \"{\" space* (relativeQuantity | closedQuantity | compoundQuantity) space* \"}\"\n closedQuantity = absoluteQuantity &(space* \"}\")\n compoundQuantity = quantityTerm (space* compoundOp space* quantityTerm)+\n // The unit is optional so `{1 + 1 cup}` reaches the compiler, which says\n // what is wrong with it, instead of failing as a syntax error.\n quantityTerm = (range | number) (space* unit)?\n compoundOp = \"+\" | \"-\"\n relativeQuantity = number space* \"%\" space* (\"@&\" | \"&\") space* name\n absoluteQuantity = (range | number)? space* (unit space*)?\n textQuantity = \"{\" space* (~\"}\" any)+ space* \"}\"\n fixed = \"=\"\n // A unit is one or more words. A word may contain \".\" or an apostrophe after\n // its first character (c.à.s, fl. oz., d'eau) but never starts with one, so a\n // stray \"{1. kg}\" or \"{.5 g}\" is still rejected rather than half-parsed.\n unit = unitName\n unitName = unitWord (sp+ unitWord)*\n unitWord = unitLead unitChar*\n unitLead = alnum | \"°\" | \"%\"\n unitChar = unitLead | \".\" | \"'\" | \"’\"\n\n // A \"{...}\" glued to an element that did not parse as a valid quantity. Without\n // this, the element silently fell back to its bare form (name truncated to its\n // first word) and the braces leaked into prose -- merging distinct ingredients.\n // Each \"-- malformed\" branch below turns that into a readable error instead.\n malformedBraces = \"{\" (~(\"}\" | nl) any)* (\"}\" | &nl | end)\n preparation = \"(\" (~\")\" any)* \")\"\n // `modifier*` mirrors simpleIngredient: a composite parent is an ingredient\n // reference like any other, and authors (and AI importers) write `<@&parent`\n // to mark a parent already introduced earlier. Without it, `refName` rejected\n // the leading \"&\" (it is a refSigil), the `bare` branch fell through to\n // `singleWordName` -- which does allow \"&\" -- and a multi-word parent silently\n // truncated at the first space, registering a phantom ingredient literally\n // named \"&citron\" alongside the real one. The modifiers are parsed and then\n // ignored (see composite_full/composite_bare): \"&\" is redundant on a parent\n // because the MAX rule already collapses repeat draws into one purchase.\n composite =\n | \"<@\" modifier* refName ingredientAmount preparation? -- full\n | \"<@\" modifier* refName malformedBraces -- malformed\n | \"<@\" modifier* singleWordName preparation? -- bare\n\n // Cookware\n Cookware =\n | CookwareAlternative\n | simpleCookware\n\n CookwareAlternative = simpleCookware (\"|\" simpleCookware)+\n // Same refName fix as simpleIngredient above -- a bare #pan mention must not\n // swallow an unrelated later {...} (e.g. another ingredient's integer-only\n // quantity) into its own name.\n simpleCookware =\n | \"#\" modifier* refName alias? cookwareQuantity preparation? -- full\n | \"#\" modifier* refName alias? malformedBraces -- malformed\n | \"#\" modifier* singleWordName alias? preparation? -- bare\n\n // Cookware quantity is numbers only, no units (e.g. {}, {2}) -- unlike ingredientQuantity.\n cookwareQuantity = \"{\" space* number? space* \"}\"\n\n // Timer\n // `ingredientQuantity` comes first (PEG order) so a plain timer keeps its\n // AST: `~{10 min}`, and also `~{1h30}`, read as 1 + unit \"h30\". Anything\n // else closed on the same line (`1:30 h`, `5'30\"`, `1h + 30min`, `1h30-2h`)\n // is kept as text. Either way the AST carries `raw`, the text between the\n // braces, and the compiler reads the duration from it (`parseDuration` in\n // @gram-lang/i18n), never from the quantity. Only an unclosed brace is\n // still a syntax error.\n Timer =\n | \"~\" \"_\"? name? ingredientQuantity -- full\n | \"~\" \"_\"? name? timerText -- text\n | \"~\" \"_\"? name? malformedBraces -- malformed\n timerText = \"{\" (~(\"}\" | nl) any)* \"}\"\n \n // Temperature\n // Lexical, so only a note glued to `}` is one: `^{180°C}(fan)` has a note,\n // `^{180°C} (preheated)` keeps its parenthesis in the prose. `name` may\n // start with a space, as it could when the rule was syntactic: `^ {180°C}`\n // and `^oven {180°C}` read as before (`clean` drops the space). The note\n // since 1.5.0.\n temperature = \"^\" name? (ingredientQuantity | textQuantity) gluedNote?\n\n // A note glued to an element's closing brace, on one line: an unclosed\n // `(` is prose, never the start of a note that would run to the next `)`\n // further down the recipe. Meant to be shared by the elements to come\n // (the sensory checkpoints).\n gluedNote = \"(\" (~(\")\" | nl) any)* \")\"\n\n\n // Comments\n Comment = \"//\" (~nl any)*\n CommentBlock = \"/*\" (~\"*/\" any)* \"*/\"\n\n // Primitives\n name = (~(syntaxChar | nl) any)+\n singleWordName = (~(syntaxChar | space | nl | sentencePunct) any)+\n sentencePunct = \",\" | \";\" | \"!\" | \"?\" | \".\"\n // Like name, but also stops at element sigils so a bare &dough is not consumed\n // into a Reference -- full when a sigil like # or @ appears later on the line.\n refName = (~(syntaxChar | refSigil | nl) any)+\n refSigil = \"@\" | \"#\" | \"~\" | \"^\" | \"&\"\n\n number = mixedFraction | unicodeFraction | plainNumber\n // \".\" or \",\" between two digits is a decimal separator (1.5, 1,5): Gram has\n // no thousands separator. A comma not between two digits ({1, 5 kg}) still\n // fails, so the commas of the prose around an element are never touched.\n plainNumber = digit+ ((\".\" | \",\") digit+)? (\"/\" digit+)?\n mixedFraction = digit+ sp+ digit+ \"/\" digit+\n unicodeFraction =\n | digit+ unicodeFractionChar -- mixed\n | unicodeFractionChar -- bare\n unicodeFractionChar = \"¼\" | \"½\" | \"¾\" | \"⅓\" | \"⅔\" | \"⅕\" | \"⅖\" | \"⅗\" | \"⅘\" | \"⅙\" | \"⅚\" | \"⅛\" | \"⅜\" | \"⅝\" | \"⅞\"\n range = number space* \"-\" space* number\n\n text = space* (~(elementStart | nl | \"|\") any)+\n\n Reference =\n | \"&\" refName ingredientAmount -- full\n | \"&\" refName malformedBraces -- malformed\n | \"&\" singleWordName -- bare\n\n // Delimiters that end a name (start of quantity/alias/preparation/composite/alternative).\n // @, #, ~, !, &, ?, * are deliberately absent here, so names may contain them freely --\n // only elementStart (below) treats those as starting a new element, and only in free text.\n syntaxChar = \"{\" | \"}\" | \"[\" | \"]\" | \"(\" | \")\" | \"<\" | \"|\" | \":\"\n\n // Stricter than syntaxChar: used to detect where an element starts within free text.\n elementStart = \"@\" | \"#\" | \"~\" | \"^\" | \"//\" | \"/*\" | \"->&\" | \"&\"\n \n nl = \"\\r\"? \"\\n\"\n sp = \" \" | \"\\t\"\n space := sp\n}\n"; diff --git a/packages/parser/src/index.ts b/packages/parser/src/index.ts index 5375ec46..1b53c847 100644 --- a/packages/parser/src/index.ts +++ b/packages/parser/src/index.ts @@ -595,6 +595,9 @@ semantics.addOperation("toAST", { preparation(_lp, text, _rp): string { return clean(text.sourceString); }, + gluedNote(_lp, text, _rp): string { + return clean(text.sourceString); + }, unit(name): string { return clean(name.sourceString); }, @@ -863,14 +866,20 @@ semantics.addOperation("toAST", { }; }, - Temperature(_1, name, qty): TemperatureAST { + temperature(_1, name, qty, noteNode): TemperatureAST { const child = name.children[0]; - const n = child ? clean(child.sourceString) : null; + // `|| null`: the rule is lexical, so `^ {180°C}` reads a name of one + // space, which the syntactic rule used to skip. + const n = (child && clean(child.sourceString)) || null; const qAST = qty.toAST(); + // Omitted when absent or empty (`^{160°C}()`), so a temperature + // without a note keeps the AST it had before 1.5.0. + const note = getOpt(noteNode); const base = { type: ASTNodeType.Temperature as const, name: n, loc: { start: this.source.startIdx, end: this.source.endIdx }, + ...(note ? { note } : {}), }; if (qAST.type === ASTNodeType.TextQuantity) { diff --git a/packages/parser/src/types.ts b/packages/parser/src/types.ts index 49c7b7f5..0efe1401 100644 --- a/packages/parser/src/types.ts +++ b/packages/parser/src/types.ts @@ -301,6 +301,11 @@ export interface TemperatureAST extends NodeAST { value?: QuantityValueAST | null; unit?: string | null; text?: string | null; + /** + * The note glued to the closing brace (`^{160°C}(fan)`), on one line. + * Omitted when there is none. Since 1.5.0. + */ + note?: string; } export interface AlternativeAST extends NodeAST { diff --git a/packages/parser/syntaxes/gram.tmLanguage.json b/packages/parser/syntaxes/gram.tmLanguage.json index d9c1a0b9..750048d0 100644 --- a/packages/parser/syntaxes/gram.tmLanguage.json +++ b/packages/parser/syntaxes/gram.tmLanguage.json @@ -221,9 +221,10 @@ "2": { "name": "constant.numeric.temperature.gram" }, "3": { "name": "punctuation.section.embedded.begin.gram" } }, - "end": "(\\})", + "end": "(\\})(?:\\(([^)\\n]+)\\))?", "endCaptures": { - "1": { "name": "punctuation.section.embedded.end.gram" } + "1": { "name": "punctuation.section.embedded.end.gram" }, + "2": { "name": "string.other.preparation.gram" } }, "patterns": [ { "include": "#temperature-content" } ] }, diff --git a/packages/parser/tests/temperature-note.test.ts b/packages/parser/tests/temperature-note.test.ts new file mode 100644 index 00000000..9e93c0a6 --- /dev/null +++ b/packages/parser/tests/temperature-note.test.ts @@ -0,0 +1,116 @@ +import { describe, expect, it } from "bun:test"; +import grammar from "../syntaxes/gram.tmLanguage.json"; +import { ASTNodeType, getAST } from "../src/index"; + +// The children of the only step of a one-step recipe. +// biome-ignore lint/suspicious/noExplicitAny: walking a parsed AST in tests. +function stepChildren(src: string): any[] { + const ast = getAST(`## T\n\n${src}\n`); + // biome-ignore lint/suspicious/noExplicitAny: walking a parsed AST in tests. + return (ast.children[0] as any).children[0].children; +} + +// biome-ignore lint/suspicious/noExplicitAny: walking a parsed AST in tests. +const temperatures = (src: string): any[] => + stepChildren(src).filter((c) => c.type === ASTNodeType.Temperature); + +const texts = (src: string): string[] => + stepChildren(src) + .filter((c) => c.type === ASTNodeType.Text) + .map((c) => c.value); + +describe("a note glued to a temperature", () => { + it("is read on an exact temperature", () => { + const [t] = temperatures("Cuire à ^{160°C}(chaleur tournante)."); + expect(t.value.value).toBe(160); + expect(t.unit).toBe("°C"); + expect(t.note).toBe("chaleur tournante"); + expect(texts("Cuire à ^{160°C}(chaleur tournante).")).toEqual([ + "Cuire à ", + ".", + ]); + }); + + it("is read on a named temperature", () => { + const [t] = temperatures("^four{180°C}(gril)"); + expect(t.name).toBe("four"); + expect(t.note).toBe("gril"); + }); + + it("is read on a temperature in words", () => { + const [t] = temperatures("^{vif}(à couvert)"); + expect(t.text).toBe("vif"); + expect(t.note).toBe("à couvert"); + }); + + it("spans the whole location of the element", () => { + const src = "^{160°C}(chaleur tournante)"; + const [t] = temperatures(src); + expect(t.loc.end - t.loc.start).toBe(src.length); + }); + + it("is not a note when a space comes before the parenthesis", () => { + const src = "Cuire à ^{180°C} (four préchauffé)."; + const [t] = temperatures(src); + expect("note" in t).toBe(false); + expect(texts(src).join("")).toContain("(four préchauffé)."); + }); + + it("is left out when empty", () => { + const [t] = temperatures("^{160°C}()"); + expect("note" in t).toBe(false); + }); + + it("is left out of a temperature without one", () => { + const [t] = temperatures("^{180°C}"); + expect(Object.keys(t).sort()).toEqual([ + "loc", + "name", + "type", + "unit", + "value", + ]); + }); + + it("stops at the end of the line: an unclosed parenthesis is prose", () => { + const ast = getAST( + "## T\n\nCuire à ^{180°C}(environ 20 min\n\nServir (chaud).\n", + ); + // biome-ignore lint/suspicious/noExplicitAny: walking a parsed AST in tests. + const [first, second] = (ast.children[0] as any).children; + // biome-ignore lint/suspicious/noExplicitAny: walking a parsed AST in tests. + const temp = first.children.find((c: any) => c.type === "Temperature"); + expect("note" in temp).toBe(false); + expect(second.type).toBe("Step"); + // biome-ignore lint/suspicious/noExplicitAny: walking a parsed AST in tests. + expect(second.children.map((c: any) => c.value).join("")).toBe( + "Servir (chaud).", + ); + }); + + it("keeps the spaced forms of the name as before", () => { + const [spaced] = temperatures("^ {180°C}"); + expect(spaced.name).toBeNull(); + expect(spaced.value.value).toBe(180); + const [named] = temperatures("^four {180°C}(gril)"); + expect(named.name).toBe("four"); + expect(named.note).toBe("gril"); + }); +}); + +describe("TextMate: a temperature's note", () => { + const end = new RegExp(grammar.repository.temperatures.end); + + it("captures a glued note as a preparation", () => { + const m = end.exec("}(chaleur tournante)."); + expect(m?.[2]).toBe("chaleur tournante"); + expect(grammar.repository.temperatures.endCaptures["2"].name).toBe( + "string.other.preparation.gram", + ); + }); + + it("leaves a spaced or an unclosed parenthesis alone", () => { + expect(end.exec("} (four préchauffé)")?.[0]).toBe("}"); + expect(end.exec("}(environ 20 min")?.[0]).toBe("}"); + }); +}); diff --git a/packages/renderer/src/index.ts b/packages/renderer/src/index.ts index 11d513c8..2e8ca63d 100644 --- a/packages/renderer/src/index.ts +++ b/packages/renderer/src/index.ts @@ -142,6 +142,7 @@ export { formatDuration, formatTimer, formatTimerDuration, + formatTemperature, formatDurationRange, toCommonFraction, escapeHtml, diff --git a/packages/renderer/src/shared/element.ts b/packages/renderer/src/shared/element.ts index 408c59a8..0efb7b9f 100644 --- a/packages/renderer/src/shared/element.ts +++ b/packages/renderer/src/shared/element.ts @@ -3,7 +3,7 @@ import { escapeHtml, escapeMarkdownHtml, getQty, - formatQuantityValue, + formatTemperature, formatTimerDuration, largerAmount, isWrittenInMetricMass, @@ -470,30 +470,28 @@ const strategies: Record< (format === "html" ? DEFAULT_ICONS.html.thermometer : DEFAULT_ICONS.md.thermometer); - const className = context.classes?.temperature || "temp"; + const value = formatTemperature(item, context.lang); + // The note (`^{160°C}(fan)`, 1.5) is an instruction: always in the + // sentence, on paper too, never only in a tooltip. + const note = item.note ? String(item.note) : ""; if (format === "text") { - const value = item.text - ? String(item.text) - : `${formatQuantityValue(item.quantity || { value: "" }, context.lang)}${item.unit ? ` ${item.unit}` : ""}`; - return styled(context, "timer", value); + return styled(context, "timer", value) + (note ? ` (${note})` : ""); } - if (item.text) { - const textVal = item.text; - if (format === "html") { - return `${termIcon} ${escapeHtml(textVal)}`; - } else { - return `${termIcon}${escapeMarkdownHtml(textVal)}`; - } - } else { - const q = item.quantity || { value: "" }; - const qVal = formatQuantityValue(q, context.lang); - const unitStr = item.unit ? ` ${item.unit}` : ""; - if (format === "html") { - return `${termIcon} ${escapeHtml(qVal)}${escapeHtml(unitStr)}`; - } else { - return `${termIcon}${escapeMarkdownHtml(qVal)}${escapeMarkdownHtml(unitStr)}`; - } + if (format !== "html") { + return `${termIcon}${escapeMarkdownHtml(value)}${note ? ` (${escapeMarkdownHtml(note)})` : ""}`; } + const className = context.classes?.temperature || "temp"; + const data = item.text + ? `data-semantic="${escapeHtml(item.text)}"` + : `data-value="${escapeHtml((item.quantity || { value: "" }).value)}" data-unit="${escapeHtml(item.unit || "")}"`; + const html = `${termIcon} ${escapeHtml(value)}`; + if (!note) return html; + // The note sits outside the pill, which never wraps: held in a group of + // its own, it may go to the next line (`.gram-nobr` only keeps its + // direct text unbreakable). + const groupClass = context.classes?.temperatureGroup || "temp-group"; + const prepClass = context.classes?.prepText || "prep"; + return `${html} (${escapeHtml(note)})`; }, reference: (item, format, context) => { diff --git a/packages/renderer/src/shared/utils.ts b/packages/renderer/src/shared/utils.ts index d8d74924..82e7af49 100644 --- a/packages/renderer/src/shared/utils.ts +++ b/packages/renderer/src/shared/utils.ts @@ -354,6 +354,21 @@ export function joinDurationRange( return `${format(min)}${NBSP}– ${format(max)}`; } +/** + * Displays a compiled temperature the way the views do: its value and unit + * (`160 °C`, `180–200 °C`), or its words when it has no number (`vif`). The + * note (`^{160°C}(fan)`) is left to the caller, which shows it its own way. + * Since 1.5.0. + */ +export function formatTemperature( + item: { text?: string | null; quantity?: unknown; unit?: string | null }, + lang?: string, +): string { + if (item.text) return String(item.text); + const value = formatQuantityValue(item.quantity, lang); + return item.unit ? `${value} ${item.unit}` : value; +} + /** * Displays a compiled timer the way Gram displays every time (`formatDuration`, * `formatDurationRange`), from its minutes. A timer is exact where a computed diff --git a/packages/renderer/src/types.ts b/packages/renderer/src/types.ts index 3ea4c8b3..e41a194f 100644 --- a/packages/renderer/src/types.ts +++ b/packages/renderer/src/types.ts @@ -113,6 +113,12 @@ export interface RendererClasses { cookware?: string; timer?: string; temperature?: string; + /** + * What holds a temperature and its note together, so the note may wrap + * apart from the value (default `temp-group`). The note itself takes + * `prepText`. Since 1.5.0. + */ + temperatureGroup?: string; declaration?: string; massBadge?: string; /** A quantity written in the text of a step (default `step-quantity`). */ diff --git a/packages/renderer/tests/temperature-note.test.ts b/packages/renderer/tests/temperature-note.test.ts new file mode 100644 index 00000000..5132aadb --- /dev/null +++ b/packages/renderer/tests/temperature-note.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, it } from "bun:test"; +import { getAST } from "@gram-lang/parser"; +import { compile } from "@gram-lang/kitchen"; +import { + formatElement, + formatTemperature, + toHTML, + toMarkdown, +} from "../src/index"; + +// A temperature's note (`^{160°C}(fan)`, 1.5) is an instruction: it stays in +// the sentence in every format, never only in a tooltip. + +const exact = { + type: "temperature", + quantity: { type: "single", value: 160, text: "160" }, + unit: "°C", + note: "fan", +}; +const inWords = { type: "temperature", text: "high", note: "covered" }; +const icons = { thermometer: "T" }; + +describe("formatTemperature", () => { + it("gives the value and unit, or the words, never the note", () => { + expect(formatTemperature(exact)).toBe("160 °C"); + expect(formatTemperature(inWords)).toBe("high"); + expect( + formatTemperature( + { quantity: { type: "single", value: 37.5 }, unit: "°C" }, + "fr", + ), + ).toBe("37,5 °C"); + }); +}); + +describe("a temperature's note in each format", () => { + it("text: after the value", () => { + expect(formatElement(exact, "text")).toBe("160 °C (fan)"); + expect(formatElement(inWords, "text")).toBe("high (covered)"); + }); + + it("Markdown: after the value, escaped", () => { + expect(formatElement(exact, "md", { icons })).toBe("T160 °C (fan)"); + expect( + formatElement({ ...exact, note: "fan" }, "md", { icons }), + ).not.toContain(""); + }); + + it("HTML: outside the pill, in a group the line may break inside", () => { + expect(formatElement(exact, "html", { icons })).toBe( + 'T 160 °C (fan)', + ); + expect(formatElement(inWords, "html", { icons })).toBe( + 'T high (covered)', + ); + }); + + it("HTML: takes the classes of the context", () => { + const html = formatElement(exact, "html", { + icons, + classes: { temperatureGroup: "g", prepText: "n" }, + }); + expect(html).toStartWith(''); + expect(html).toContain('(fan)'); + }); + + it("HTML: a temperature without a note keeps its single pill", () => { + const { note: _, ...plain } = exact; + expect(formatElement(plain, "html", { icons })).toBe( + 'T 160 °C', + ); + }); +}); + +describe("a temperature's note in the recipe views", () => { + const compiled = compile( + getAST("## Four\n\nCuire à ^{160°C}(chaleur tournante).\n"), + ); + + it("is in the HTML, the punctuation glued to its parenthesis", () => { + const html = toHTML(compiled); + expect(html).toContain( + '(chaleur tournante).', + ); + }); + + it("is in the Markdown", () => { + expect(toMarkdown(compiled)).toContain("160 °C (chaleur tournante)."); + }); +});