From 9d47e896cd1eebc2bf1ece6897e6aa60a847f85f Mon Sep 17 00:00:00 2001 From: abiwab Date: Wed, 18 Nov 2026 12:16:23 +0100 Subject: [PATCH 01/24] docs: tighten and clarify v1.5 documentation across EN and FR --- packages/docs/public/llms-full.txt | 281 +++++++----------- .../docs/docs/explanation/mass-and-yield.mdx | 4 +- .../content/docs/docs/explanation/scaling.mdx | 16 +- .../explanation/shopping-list-aggregation.mdx | 10 +- .../docs/docs/how-to/manage-database.mdx | 4 +- .../docs/docs/how-to/scale-recipes.mdx | 2 +- .../docs/docs/how-to/weekly-shopping-list.mdx | 2 +- .../docs/docs/reference/api/data-formats.mdx | 10 +- .../content/docs/docs/reference/api/i18n.mdx | 4 +- .../docs/docs/reference/api/warnings.mdx | 51 ++-- .../reference/syntax/ai-generation-notes.mdx | 8 +- .../docs/docs/reference/syntax/cheatsheet.mdx | 18 +- .../docs/reference/syntax/ingredients.mdx | 38 ++- .../reference/syntax/relative-quantities.mdx | 51 ++-- .../docs/reference/syntax/target-states.mdx | 43 ++- .../docs/reference/syntax/temperatures.mdx | 6 +- .../docs/docs/reference/syntax/times.mdx | 99 ++---- .../docs/docs/reference/tooling/cli.mdx | 14 +- .../reference/tooling/language-server.mdx | 28 +- .../reference/tooling/vscode-extension.mdx | 7 +- .../fr/docs/explanation/mass-and-yield.mdx | 4 +- .../docs/fr/docs/explanation/scaling.mdx | 16 +- .../explanation/shopping-list-aggregation.mdx | 10 +- .../docs/fr/docs/how-to/manage-database.mdx | 4 +- .../docs/fr/docs/how-to/scale-recipes.mdx | 2 +- .../fr/docs/how-to/weekly-shopping-list.mdx | 2 +- .../fr/docs/reference/api/data-formats.mdx | 10 +- .../docs/fr/docs/reference/api/i18n.mdx | 4 +- .../docs/fr/docs/reference/api/warnings.mdx | 51 ++-- .../reference/syntax/ai-generation-notes.mdx | 14 +- .../fr/docs/reference/syntax/cheatsheet.mdx | 16 +- .../fr/docs/reference/syntax/ingredients.mdx | 48 ++- .../reference/syntax/relative-quantities.mdx | 55 ++-- .../docs/reference/syntax/target-states.mdx | 43 ++- .../fr/docs/reference/syntax/temperatures.mdx | 6 +- .../docs/fr/docs/reference/syntax/times.mdx | 107 ++----- .../docs/fr/docs/reference/tooling/cli.mdx | 14 +- .../reference/tooling/language-server.mdx | 34 +-- .../reference/tooling/vscode-extension.mdx | 7 +- 39 files changed, 484 insertions(+), 659 deletions(-) diff --git a/packages/docs/public/llms-full.txt b/packages/docs/public/llms-full.txt index a6672ce8..57333f93 100644 --- a/packages/docs/public/llms-full.txt +++ b/packages/docs/public/llms-full.txt @@ -525,7 +525,7 @@ Add @butter{1½ sticks}. ### Decimal numbers *(since v1.5.0)* -A decimal number takes a point or a comma, whichever you are used to: `{1.5 kg}` and `{1,5 kg}` are the same quantity. This holds for every number in braces: ingredients, ranges (`{0,5-0,75 l}`), relative quantities (`{12,5% &dough}`), cookware, temperatures (`^{37,5°C}`), timers and section anchors. +Decimals accept either a period or a comma: `{1.5 kg}` and `{1,5 kg}` mean the same thing. This applies to every number inside braces—ingredients, ranges (`{0,5-0,75 l}`), relative quantities (`{12,5% &dough}`), cookware, temperatures (`^{37,5°C}`), timers, and section anchors. ```gram Add @flour{1,5 kg} and @salt{0.125 kg}. @@ -533,12 +533,12 @@ Add @flour{1,5 kg} and @salt{0.125 kg}. Pour @milk{0,5-0,75 l}. ``` -Gram has no thousands separator: write `{1500 g}`, never `{1,500 g}`. A comma followed by exactly three digits is read as a decimal like any other (`{1,000 g}` is 1 g), but since a reader could mean a thousand, the compiler warns `AMBIGUOUS_NUMBER` and says how it read the number. A point keeps the meaning it has always had: `{1.000 kg}` is 1 kg, with no warning. +Gram has no thousands separator: write `{1500 g}`, never `{1,500 g}`. A comma followed by three digits like `{1,000 g}` is parsed as a decimal (`1 g`) and triggers an `AMBIGUOUS_NUMBER` warning; a period (`{1.000 kg}`) always means `1 kg` with no warning. ### Sums of quantities *(since v1.5.0)* -A measure that doesn't fit one unit is written the way a recipe says it: terms joined by `+`, or `-` for an amount taken away. +When a measurement combines more than one unit, write it as a sum with `+`, or `-` for an amount subtracted: ```gram Add @flour{1 cup + 1 tbsp} and @sugar{1 cup - 2 tbsp}. @@ -548,38 +548,36 @@ Pour @milk{1 cup + 1-2 tbsp}. Mix in @butter{2 1/2 tbsp + ½ tsp} and @rice{1 cup + 20 g}. ``` -Each term is a number (or a range, or a fraction) with its unit. Gram keeps the terms as written and works out their total: `{1 cup + 1 tbsp}` is 17 tbsp, `{1 cup - 2 tbsp}` is 14 tbsp. The recipe shows the sum as you wrote it; once scaled, it is worked out again into amounts a cook can measure (`{1 cup + 1 tbsp}` doubled reads `2 cup + 2 tbsp`, never `2 1/8 cup`). The `=` modifier locks a sum like any other quantity (`@=salt{1,5 g + 1 pinch}`). +Each term is a quantity (number, range, or fraction) with its unit. Gram preserves the sum as written in the unscaled recipe, and recomputes it into practical kitchen measures when scaling (for example, doubling `{1 cup + 1 tbsp}` gives `2 cup + 2 tbsp`). Adding `=` locks the entire sum (`@=salt{1,5 g + 1 pinch}`). -A sum counts as **separate mentions** of the ingredient: `@rice{1 cup + 20 g}` goes into the shopping list exactly like `@rice{1 cup}` followed by `@&rice{20 g}`. Terms of the same kind of unit add up (cups and spoons, kilos and grams); a volume next to a weight, or two units Gram doesn't know (`{1 head + 2 cloves}`), stay side by side. +In the shopping list, a sum behaves like separate mentions of the ingredient: compatible units add up (cups and spoons, grams and kilograms), while a volume and a weight (`{1 cup + 20 g}`) or unrecognized units stay side by side. -A few rules keep a sum readable: +A few rules keep sums unambiguous: -- **Every term has its unit**: `{1 + 1 cup}` is refused. -- **Only amounts**: no percentage (`{100 g + 10%}`, write `{110 g}`, or a [relative quantity](/docs/reference/syntax/relative-quantities/)), no multiplication (`{2 x 100 g + 50 g}`). -- **Take away from the same kind**: `{1 cup - 2 tbsp}` works, `{1 cup - 20 g}` doesn't, and what is taken away must leave something (`{1 tbsp - 1 cup}` is refused). -- **No range after `-`**: `{1 cup - 1-2 tbsp}` would swap its bounds; write the range on a term that is added. +- **Every term needs a unit**: `{1 + 1 cup}` is rejected. +- **Plain quantities only**: no percentages (`{100 g + 10%}`) or multiplications (`{2 x 100 g}`). +- **Subtract within the same kind**: `{1 cup - 2 tbsp}` works, `{1 cup - 20 g}` does not, and the result must remain positive (`{1 tbsp - 1 cup}` is rejected). +- **No range after `-`**: put ranges on added terms (`{1 cup + 1-2 tbsp}`), never subtracted ones. -Each kind of amount adds up and takes away **on its own**, because a volume and a weight can't be compared without a density. In `{1 cup - 2 tbsp + 30 g}`, the 2 tbsp come off the cup and the 30 g are added beside them: the sum is 14 tbsp of volume plus 30 g of weight. In `{1 cup - 20 g}`, there is no weight to take the 20 g from, so Gram refuses it rather than guess. Hover a sum in the editor to see what each kind comes to. +An invalid sum still compiles with an `INVALID_QUANTITY` warning explaining why, and is excluded from shopping list and nutrition totals. See [Scaling sums of quantities](/docs/explanation/scaling/#scaling-sums-of-quantities) for details. -A refused sum compiles with an `INVALID_QUANTITY` warning that says why, and counts for nothing in the shopping list and the nutrition. Two quantities written side by side without an operator (`{1 cup 5 tbsp}`) raise `INVALID_UNIT`; the editor offers to insert the ` + `. - -:::caution[oz is a weight] -In `{1 cup + 2 oz}`, `oz` is an ounce of weight, not of volume: Gram reads it as written and adds a note (`OZ_AFTER_VOLUME`). Write `fl oz` for a fluid ounce. +:::caution[`oz` means weight] +In `{1 cup + 2 oz}`, `oz` is parsed as weight (ounces), not fluid volume (`OZ_AFTER_VOLUME`). Write `fl oz` for fluid ounces. ::: ## 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. +Some syntax errors stop parsing before compilation: an unreadable quantity in braces (`@salt{1 g/l}`) or an unclosed brace. The error points to the exact spot to fix. -The compiler checks for semantic errors in your `@ingredient` declarations and will output specific warnings: +The compiler checks for semantic errors in your `@ingredient` declarations and emits structured warnings: - **Invalid Modifier**: If you combine incompatible modifiers (like `?*`), the compiler warns `INVALID_MODIFIER_COMBINATION` and ignores them. -- **Undefined Reference**: If you use a reference (`@&ingredient`) but that item hasn't been declared previously in the recipe, the compiler warns `UNDEFINED_REFERENCE`. +- **Undefined Reference**: If you use a reference (`@&ingredient`) before it has been declared in the recipe, the compiler warns `UNDEFINED_REFERENCE`. - **Database Missing**: If you compile with a database and the `@ingredient` is not found, it warns `MISSING_INGREDIENT`. - **Missing Macros**: If the database lacks nutritional information for the `@ingredient`, it warns `MISSING_MACROS`. - **Unknown Mass**: If it cannot convert a volume or count into grams to estimate nutrition, it warns `UNKNOWN_MASS`. -- **Invalid Quantity**: If a sum of quantities can't be read (a term without a unit, a percentage, an amount taken away from another kind…), it warns `INVALID_QUANTITY` and gives the reason. -- **Ambiguous Number**: If a comma is followed by exactly three digits (`{1,000 g}`), it reads a decimal and warns `AMBIGUOUS_NUMBER`, in case a thousand was meant. +- **Invalid Quantity**: If a sum of quantities breaks one of the rules above, it warns `INVALID_QUANTITY` with the reason. +- **Ambiguous Number**: If a comma is followed by three digits (`{1,000 g}`), it parses a decimal and warns `AMBIGUOUS_NUMBER`. ## Related resources @@ -721,7 +719,7 @@ You can define `~timer` declarations and durations in your recipes using the `~` ## Basic declaration -A `~timer` **must** state its unit inside the braces. Words are not durations: `~{about 10 minutes}` or `~{half an hour}` are not read, and the compiler warns about them. +A `~timer` **must** state its unit inside the braces. Free-text durations like `~{about 10 minutes}` or `~{half an hour}` are not supported and trigger a compiler warning. ```gram Bake for ~{25min}. @@ -737,7 +735,7 @@ Bake for ~{25min}. Shorthand `m` or the word `minutes` are automatically normalized to `min` by the compiler. ::: -These units are resolved through Gram's multi-language time dictionary: localized aliases below are recognized natively regardless of the recipe language (e.g. in a French recipe, `~{2j}` resolves identically to `~{2d}`, and `~{1 hr}` reads in any recipe). +These units resolve through Gram's multi-language time dictionary, so localized aliases work regardless of the recipe language (`~{2j}` equals `~{2d}`, and `~{1 hr}` works anywhere). | Canonical | Aliases | | --- | --- | @@ -749,7 +747,7 @@ These units are resolved through Gram's multi-language time dictionary: localize ## Writing a duration *(since v1.5.0)* -Write a duration the way a recipe does, in American or British English, in French or in international notation. Spaces carry no meaning: `~{1h30}`, `~{1 h 30}`, `~{1hr 30}` and `~{1 hr. 30 mins}` all read as 1 hour 30 minutes. +Write durations the way recipes naturally do—spaces don't matter (`~{1h30}`, `~{1 h 30}`, `~{1 hr 30 mins}` all mean 1 h 30 min), and every view formats them consistently in the reader's language. ```gram Simmer the @stock{2 l} for ~{1h30}. @@ -759,66 +757,24 @@ Let the @dough{} rise ~_{1 hr 30 mins}. Age the @ham{1} in the cellar ~_{2d 4h}. ``` -Whatever the writing, the views display every duration the same way, in the reader's language (`1 h 30 min`), and hovering a timer in your editor shows how Gram read it. - -### Several units - -A duration can chain several units, optionally joined by `+`: `~{1h30min}`, `~{1 h 30 min}`, `~{2 d 4 h}`, `~{1h + 30min}`. - -- Units go **from the largest to the smallest**, each one once: `~{30min 1h}` and `~{1h 2h}` are not read. -- A **last number without a unit** is allowed right after hours (it counts minutes) or minutes (it counts seconds), when it is a whole number under 60: `~{1h30}`, `~{2min30}`. `~{1h75}` is not read: write `~{2h15}`. -- **Decimals and fractions** only work in a duration of a single unit: `~{1.5 h}`, `~{1½ h}`, `~{1 1/2 hours}`. `~{1.5h30}` is not read. - -### Clock notation - -A clock with three parts always reads: `~{1:30:00}` is 1 hour 30 minutes, `~{0:04:30}` is 4 minutes 30 seconds. With two parts, a unit says what the first part is: `~{1:30 h}` is 1 hour 30 minutes, `~{4:30 min}` is 4 minutes 30 seconds. - -```gram -Steam the @pudding{1} for ~_{1:30 h}. -``` - -`~{1:30}` alone is not read: it could be 1 hour 30 or 1 minute 30. Write `~{1h30}` or `~{1:30 min}`. After the first part, each part has two digits and stays under 60. - -### Prime notation - -Common in Italian and French recipes, `'` counts minutes and `"` seconds: `~{5'}`, `~{5'30"}`, `~{45"}`, `~{90'}`. A last number without a prime counts seconds (`~{5'30}`). Primes only count minutes and seconds, in whole numbers. - -```gram -Cook the @spaghetti{500g} for ~{9'}, then toss for ~{1'30"}. -``` - -The typographic variants read too: the curly apostrophe `’` that word processors put in place of `'`, the primes `′` and `″`, and two apostrophes `''` for seconds. - -### Decimal numbers - -A duration can be a decimal, with a point or a comma (`~{1.5 h}`, `~{1,5 h}`; see [decimal numbers](/docs/reference/syntax/ingredients/#decimal-numbers)). +- **Compound units** (`~{1h30min}`, `~{2 d 4 h}`, `~{1h + 30min}`): list units from largest to smallest, each once. A trailing number without a unit is allowed right after hours (minutes) or minutes (seconds) if it is a whole number under 60 (`~{1h30}`, `~{2min30}`, not `~{1h75}`). Decimals and fractions only apply to single-unit durations (`~{1.5 h}`, `~{1½ h}`, not `~{1.5h30}`). +- **Clock notation** (`~{1:30:00}`, `~{1:30 h}`, `~{4:30 min}`): three parts always work (`hh:mm:ss`); two parts require a leading unit so `1:30` isn't ambiguous between hours and minutes. +- **Prime notation** (`~{5'}`, `~{5'30"}`, `~{45"}`): `'` counts whole minutes and `"` counts whole seconds (typographic quotes `’`, `′`, `″`, and `''` also work). +- **Decimals** (`~{1.5 h}`, `~{1,5 h}`): periods and commas both work (see [decimal numbers](/docs/reference/syntax/ingredients/#decimal-numbers)). :::caution -A decimal is a fraction of the unit, not minutes: `~{1.30 h}` (or `~{1,30 h}`) is 1 hour 18 minutes, not 1 hour 30. Write `~{1h30}` or `~{1.5 h}` for an hour and a half. +A decimal is a fraction of the unit, not minutes: `~{1.30 h}` is 1 h 18 min, not 1 h 30 min. Write `~{1h30}` or `~{1.5 h}` for an hour and a half. ::: -### What Gram reads, at a glance - -| Written | Read as | -| :--- | :--- | -| `~{90min}`, `~{1.5 h}`, `~{1,5 h}`, `~{1½ h}`, `~{1 1/2 hours}` | 1 h 30 min | -| `~{1h30}`, `~{1 h 30}`, `~{1hr 30}`, `~{1 hr 30 mins}`, `~{1 hour 30 minutes}`, `~{1h30m}` | 1 h 30 min | -| `~{1 heure 30}`, `~{1h + 30min}`, `~{1:30 h}`, `~{1:30:00}` | 1 h 30 min | -| `~{4min30}`, `~{4:30 min}`, `~{4'30"}`, `~{0:04:30}` | 4 min 30 s | -| `~{2 d 4 h}`, `~{2 j 4 h}` | 2 days 4 hours | -| `~{45 min - 1 h}`, `~{1h30-2h}`, `~{5-7'}` | a range (see below) | - -| Not read | Why | Write instead | +| Accepted | Rejected | Use instead | | :--- | :--- | :--- | -| `~{1:30}` | hours or minutes? | `~{1h30}` or `~{1:30 min}` | -| `~{1h75}` | 60 minutes or more after the hours | `~{2h15}` | -| `~{30min 1h}` | units from the smallest to the largest | `~{1h30}` | -| `~{1.5h30}` | a decimal in a duration of several units | `~{1h30}` or `~{1.5 h}` | -| `~{half an hour}`, `~{2 to 3 hours}` | words | `~{30min}`, `~{2-3h}` | -| `~{2 * 2 min}` | a multiplication | the total, `~{4min}` | -| `~{PT1H30M}` | ISO 8601, a notation for machines | `~{1h30}` | +| `~{1h30}`, `~{1 hr 30}`, `~{1h + 30min}` | `~{1:30}` *(ambiguous)* | `~{1h30}` or `~{1:30 min}` | +| `~{1:30 h}`, `~{1:30:00}` | `~{1h75}` *(≥ 60 min)* | `~{2h15}` | +| `~{4'30"}`, `~{4min30}` | `~{30min 1h}` *(wrong order)* | `~{1h30}` | +| `~{1.5 h}`, `~{1,5 h}`, `~{1½ h}` | `~{1.5h30}` *(decimal in compound)* | `~{1h30}` or `~{1.5 h}` | +| `~{45 min - 1 h}`, `~{1h30-2h}` | `~{half an hour}` *(words)* | `~{30min}` | -A duration Gram does not read raises a [warning](#error-handling) with a suggestion, and is not counted in the total time: Gram never guesses. +Unrecognized durations raise an `INVALID_DURATION` warning with a suggested fix and are excluded from total times. ### Timer names You can assign an explicit name to a `~timer`. This is especially useful for passive background tasks: when multiple timers run concurrently (like a dough fermenting while a stock simmers), named timers allow user interfaces and production run sheets to track each process simultaneously without confusion. @@ -838,7 +794,7 @@ Let the dough rest in the fridge ~_{12-24h}. Roast the chicken for ~{40-50min}. ``` -Each side of a range follows the rules above, and the shorter duration comes first. The left side takes the unit of the right side only when it is a bare number and the right side has a single unit: `~{1-2 h}`, `~{5-7'}`, `~{1.5-2 h}` (and two clocks before a unit: `~{1:30-2:00 h}`). Otherwise, write both sides in full (since 1.5.0): +Each side of a range follows the rules above, with the shorter duration first. You can omit the unit on the left only when it is a bare number and the right side has a single unit (`~{1-2 h}`, `~{5-7'}`, `~{1:30-2:00 h}`). For compound or mixed-unit bounds, write both sides in full (*(since v1.5.0)*): ```gram Braise the @beef cheeks{1 kg} ~_{2h30-3h}. @@ -846,7 +802,7 @@ Braise the @beef cheeks{1 kg} ~_{2h30-3h}. Poach the @pears{4} for ~{45 min - 1 h}. ``` -`~{1-2h30}` is not read (is the left side 1 hour or 1 hour 30?): write `~{1h-2h30}`. Neither is `~{2-1 h}`: write `~{1-2 h}`. +Ambiguous or reversed ranges like `~{1-2h30}` or `~{2-1 h}` are rejected—write `~{1h-2h30}` or `~{1-2 h}` instead. The interpretation of a range differs fundamentally based on timer type: @@ -861,7 +817,7 @@ Deprecated fields of the compiled recipe (`steps[].timings`, `steps[].background ### Proportional times *(since v1.5.0)* -Some times follow a weight: 15 minutes per 500 g of roast, 4 minutes per cutlet. Write the duration, a slash, then the amount of an ingredient written earlier in the section, as in a [ratio with units](/docs/reference/syntax/relative-quantities/#ratios-with-units): +Some cooking times scale with weight or count—such as 15 minutes per 500 g of roast, or 4 minutes per cutlet. Write the duration, a slash, and the reference amount of an ingredient declared earlier in the section, following the same syntax as a [ratio with units](/docs/reference/syntax/relative-quantities/#ratios-with-units): ```gram Season the @roast{1.2 kg} and roast ~{15 min / 500 g @&roast}. // 36 min @@ -871,7 +827,10 @@ Braise the @shoulder{2 kg} ~_{1:30 h / 1 kg @&shoulder}. // 3 h Fry the @cutlets{4} ~{4 min / @&cutlets}. // 16 min ``` -The duration takes every form above (`1h30`, `1:30 h`, a range such as `15-20 min`), the target amount a single number. A time per piece counted from a weight (`~{4 min / @&cutlets}` with `@cutlets{800 g}`) uses the `unit_weight` of the ingredient database, and stays uncounted, with a warning, when there is none. Scaling the recipe computes the time again, and the schedule with it. A multiplier after a proportional time (`~{15 min / 500 g @&roast * 2}`) is not read yet, nor is a proportional section anchor. +- The duration accepts any standard format (`1h30`, `1:30 h`, or a range like `15-20 min`), while the target amount must be a single number. +- A time per piece applied to a weight (`~{4 min / @&cutlets}` with `@cutlets{800 g}`) relies on `unit_weight` in your ingredient database; if missing, the timer stays uncomputed with a warning. +- Scaling the recipe recalculates proportional times and updates the schedule automatically. +- Multipliers (`~{15 min / 500 g @&roast * 2}`) and proportional section anchors are not supported yet. ## Active vs passive @@ -997,8 +956,8 @@ Working days are designed to fit within a 24-hour span: if a long passive durati Section header retro-planning annotations require a **strictly negative** duration: - A **required** leading `-` sign. -- A non-zero duration, written like a timer (see [Writing a duration](#writing-a-duration)) in days, hours and minutes (compound and clock forms since 1.5.0). -- A single duration: an anchor is never a range, and never counts seconds. +- A non-zero duration in days, hours, or minutes (including compound and clock forms since 1.5.0; see [Writing a duration](#writing-a-duration)). +- A single duration—anchors cannot be ranges or include seconds. ```gram ## Puff pastry ~{-2d} @@ -1012,15 +971,9 @@ Knead the @flour{500g}. ## Ganache ~{-1h30} Pour the @cream{200ml} over the @chocolate{200g}. - -## Custard ~{-1:30 h} - -Whisk the @yolks{4} with the @sugar{80g}. ``` -An anchor written with days stays in days (`~{-1d 12h}` is a day and a half, and opens a working day); otherwise it counts in its smallest unit (`~{-1h30}` is 90 minutes, `~{-1:30 h}` too). - -Free prose (`~{the day before}`), positive values (`~{2h}`), and zero values (`~{0h}`) are invalid. Existing recipes using legacy formats still compile for backward compatibility, but produce compiler warnings. +Free prose (`~{the day before}`), positive values (`~{2h}`), and zero values (`~{0h}`) are invalid and trigger compiler warnings. Units resolve through the multi-language time dictionary used by `~timer`: `j`, `jour`, and `jours` are recognized aliases for `d`. @@ -1034,8 +987,8 @@ The compiler validates `~timer` declarations and section retro-planning annotati - **Invalid Unit** (`~timer`): Unrecognized units (e.g. `~{30 lightyears}`) trigger `INVALID_UNIT`. - **Missing Unit** (section retro-planning): `~{-2}`, free text, positive (`~{2h}`), or zero values (`~{0h}`) trigger `MISSING_UNIT`. - **Invalid Unit** (section retro-planning): Unrecognized units trigger `INVALID_UNIT`. -- **Invalid Duration** *(Since 1.5.0)*: A duration in a shape Gram does not read (`~{1:30}`, `~{1h75}`, `~{30min 1h}`, `~{1-2h30}`, `~{half an hour}`, or a range or seconds in an anchor) triggers `INVALID_DURATION`. The message says why and how to write it; the timer is not counted in the total time, and the section is not anchored. See [Writing a duration](#writing-a-duration). -- **Ambiguous Number** *(Since 1.5.0)*: A comma followed by exactly three digits (`~{1,000 min}`, `~{-1,000h}`) is read as a decimal, one minute or one hour, and triggers `AMBIGUOUS_NUMBER` in case a thousand was meant. +- **Invalid Duration** *(Since 1.5.0)*: Unrecognized or ambiguous duration formats (`~{1:30}`, `~{1h75}`, `~{30min 1h}`, `~{1-2h30}`, `~{half an hour}`, or ranges/seconds in anchors) trigger `INVALID_DURATION` with a suggested fix; the timer is excluded from total time and the anchor is ignored. +- **Ambiguous Number** *(Since 1.5.0)*: A comma followed by three digits (`~{1,000 min}`, `~{-1,000h}`) is parsed as a decimal (`1`) and triggers `AMBIGUOUS_NUMBER`. - **Time Paradox**: Anchors conflicting with dependency order (e.g. an ingredient anchored at `-10 min` needed by a section anchored at `-1 h`) trigger `TIME_PARADOX`. - **Track Contention**: Concurrent passive timers delayed on the same named track trigger `TRACK_CONTENTION`. - **Day overflow** *(Since 1.4.0)*: Passive durations pushing working day tasks beyond the 24-hour window trigger `DAY_OVERFLOW`. @@ -1113,7 +1066,7 @@ When the Gram compiler inspects a `^temperature` token: ## 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. +Add a parenthetical note right after the closing brace to specify the oven mode, measurement point, or cooking condition. This works on both exact and semantic temperatures, named or unnamed, just like ingredient preparation notes: ```gram Preheat the #oven to ^{160°C}(fan). @@ -1123,9 +1076,9 @@ 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. +The note is always shown next to the temperature on screen and in print, and is preserved as written in your recipe's language without being parsed. -As with ingredients and cookware, keep the opening `(` glued to the `}` on the same line: with a space (`^{180°C} (preheated)`), the parenthesis stays ordinary text in the sentence. +As with ingredients and cookware, keep the opening `(` attached to `}` on the same line: with a space (`^{180°C} (preheated)`), the parentheses remain ordinary step text. ## Error handling @@ -1314,12 +1267,12 @@ When the compiler resolves a relative quantity, it follows four strict scoping a | **Section scoping** | Current section only | You cannot directly target a base `@ingredient` declared in a different section. To bridge sections, capture the result into a globally scoped `&variable`. | | **Accumulation** | Sums all occurrences | If the target `@ingredient` appears multiple times within the same section, the percentage applies to their **cumulative total**. | | **Mass-based** | Evaluated in grams | Calculations are always performed against **physical mass in grams**. For example, 50% of "2 eggs" (each standardized at 50g) produces **50g**, not 1 egg. | -| **Alternatives** | One option at a time | Each option of an alternative gets its own amount, never added to the others: `@butter{10% @&flour}\|@oil{8% @&flour}` reads "20 g of butter or 16 g of oil" for 200 g of flour. An option can also take a share of an earlier option of the same group: `@butter{100g}\|@oil{80% @&butter}`. | +| **Alternatives** | One option at a time | Each option in an alternative group computes independently (`@butter{10% @&flour}\|@oil{8% @&flour}` gives 20 g of butter or 16 g of oil for 200 g of flour). An option may also target an earlier option in the same group (`@butter{100g}\|@oil{80% @&butter}`). | ## Ratios with units *(since v1.5.0)* -A percentage weighs grams against grams. A relates two amounts in any units, the way recipes state their rules: one egg per 100 g of flour, 15 g of salt per liter of water, 15 minutes per 500 g of roast. +While a percentage compares mass to mass, a relates two quantities in any compatible units—just as recipes state them: 1 egg per 100 g of flour, 15 g of salt per liter of water, or 15 minutes per 500 g of roast. ```gram Mix @flour{500 g} with @eggs{1 / 100 g @&flour}. // 5 eggs @@ -1329,46 +1282,31 @@ Pour @water{2 l} and @salt{15 g / 1 L @&water}. // 30 g of salt Crush @garlic{3 cloves} with @parsley{1 tsp / 2 cloves @&garlic}. // 1.5 tsp ``` -**Pattern:** `@name{ amount / target amount @&TargetIngredient }`, or `&TargetVariable` for an intermediate. The amount takes its unit (`15 g`) or none (`1` egg); the target amount is a number and a unit (`100 g`), a unit alone (`L`), or nothing for one piece (`{1 / @&cutlet}`). A range works as the amount (`{15-20 g / 100 g @&flour}`), never as the target amount. +**Pattern:** `@name{ amount / targetAmount @&TargetIngredient }` (or `&TargetVariable`). -Write a space on at least one side of the slash: `{1/100g @&flour}` reads as the fraction `1/100` and is refused with a message that shows the spaced form. Write the unit alone, too: in `{1 / 100 g of @&flour}` the unit is `g of`, which Gram refuses. +- `amount` takes its unit (`15 g`) or none for counts (`1` egg), and may be a range (`15-20 g`). +- `targetAmount` is a single number and unit (`100 g`), a unit alone (`L`), or omitted for one piece (`{1 / @&cutlet}`). +- **Always put a space around `/`** (at least on one side) and write the unit alone before the target: `{1/100g @&flour}` parses as the fraction `1/100`, and `{1 / 100 g of @&flour}` treats `g of` as the unit. -### The unit guardrail +### Unit compatibility -A ratio is computed only when its units can be compared, never guessed: +Gram only computes a ratio when its units can be compared safely—it never guesses: | Target amount | Target written in | Result | | :--- | :--- | :--- | -| A weight (`100 g`) | A weight (`1 kg`) | Computed by the compiler | -| A weight | A volume, or pieces | Computed with the density or the `unit_weight` of the ingredient database | -| Pieces (`2 cloves`, nothing) | The same pieces (`3 clove`, `4`) | Computed by the compiler: singular and plural match | -| Pieces | Other pieces (`2 slices` for garlic in cloves) | Refused | +| Weight (`100 g`) | Weight (`1 kg`) | Computed directly | +| Weight | Volume or count | Computed using density or `unit_weight` from the ingredient database | +| Count (`2 cloves`, or none) | Same count (`3 clove`, `4`) | Computed directly (singular/plural matched) | +| Count | Different count (`2 slices` for cloves) | Refused (`RELATIVE_QUANTITY_UNKNOWN_MASS`) | -A ratio that cannot be computed keeps its writing (`1 / 100 ml @&flour` in the views and the shopping list) and raises `RELATIVE_QUANTITY_UNKNOWN_MASS` with the reason. Unlike a percentage, a computed ratio keeps the unit of its amount: `5` eggs, `15 g` of salt, merged with the other uses of the ingredient in the shopping list. +If a ratio cannot be resolved, it remains as written in views and shopping lists and raises `RELATIVE_QUANTITY_UNKNOWN_MASS`. Unlike percentages, a resolved ratio keeps the unit of its own `amount` (e.g. `5` eggs, `15 g` of salt) and merges normally in the shopping list. -### Where the target is +### Scope, intermediates & scaling -The same rules as a percentage: an `@&ingredient` written earlier in the section with an amount (every amount in the section adds up), or an `&intermediate`. An option of an alternative may take an earlier option as its target. When the section uses an intermediate whole, with no amount (`Roll out the &dough`), the ratio counts from the mass of the section that makes it, an estimate of what went into the bowl, before cooking. Gram refuses when another section uses the intermediate too, since it cannot tell who takes what: - -```gram -## Dough ->&dough - -Mix @flour{500 g} and @water{60% @&flour}. - -## Bake - -Roll out the &dough, sprinkle @salt{2 g / 100 g &dough}. // 16 g of 800 g -``` - -This applies to a percentage as well (`@sugar{5% &dough}`), which used to give up there. - -### On references and composites - -A reference to a homemade preparation takes a ratio or a percentage too: `&stock{250 ml / 100 g @&rice}`, `&stock{250% @&rice}`. A composite parent does not yet (`<@box{1 / 100 g @&flour}>` is refused until composites are reworked). - -### Scaling - -Scaling a recipe computes its ratios again on the scaled amounts: twice the flour, twice the eggs. A ratio whose target is fixed (`@=pepper{2 g}`) stays as it is. `=` on a ratio itself is refused: a ratio always follows its target. +- **Same scope as percentages**: target an `@&ingredient` declared earlier in the section (repeated uses sum up), an earlier option in an alternative group, or an `&intermediate`. +- **Whole intermediates**: if a section consumes an intermediate without a quantity (`Roll out the &dough`), ratios and percentages (`@salt{2 g / 100 g &dough}`, `@sugar{5% &dough}`) resolve against the total mass of the section that produces it—provided only that section consumes it. +- **References & composites**: ratios and percentages work on homemade intermediate references (`&stock{250 ml / 100 g @&rice}`), but are not yet supported on composite parents (`@eggs{1}<@box{1 / 100 g @&flour}>`). +- **Scaling**: scaling a recipe recalculates ratios from the scaled targets (unless the target is fixed with `@=`). Marking a ratio itself with `=` is not allowed. ## Mass calculation rules @@ -1607,9 +1545,9 @@ Essential markup tokens used directly inside recipe steps: | :--- | :--- | :--- | :--- | :--- | | **Ingredient** | `@` | `@name[{quantity}]` | `@flour{200g}` | Declares an ingredient. Omitting `{}` indicates no specific quantity (e.g. `@salt`). | | **Cookware** | `#` | `#name[{quantity}]` | `#pan{2}`, `#whisk` | Specifies kitchen equipment. Omitting `{}` defaults to a single item (`1`). | -| **Timer** | `~` | `~{time}` | `~{30min}`, `~{1h30}` | Defines an active cooking or preparation duration, written as in a recipe (`1 hr 30 mins`, `1:30 h`, `5'30"`). | -| **Temperature** | `^` | `^{temperature}` | `^{180°C}`, `^{350°F}` | Declares an exact heat setting (`C` or `F`, case-insensitive). | -| **Target state** | `=` | `={state}` | `={ribbon stage}`, `={golden}` | The state to reach, in the cook's words, anywhere in the step. Since 1.5.0. | +| **Timer** | `~` | `~{time}` | `~{30min}`, `~{1h30}` | Active cooking or preparation duration (`1 hr 30 mins`, `1:30 h`, `5'30"`). | +| **Temperature** | `^` | `^{temperature}` | `^{180°C}`, `^{350°F}` | Exact heat setting (`C` or `F`, case-insensitive). | +| **Target state** | `=` | `={state}` | `={ribbon stage}`, `={golden}` | Sensory cue to reach, placed anywhere in the step. | ## Modifiers @@ -1634,18 +1572,18 @@ Specialized patterns for flexible culinary instructions: | **Short-hand prep** | `(...)` | `@butter{10g}(room temp)` | Notes prep techniques without cluttering names. | | **Component alias** | `:slug` | `@dry white wine:wine{10ml}` | Displays user-friendly text while mapping to a canonical ID. | | **Relative quantity** | `% @&target` | `@water{70% @&flour}` | Computes amount relative to a reference ingredient mass. | -| **Ratio with units** | `a / b @&target` | `@eggs{1 / 100 g @&flour}`, `@salt{15 g / L @&water}` | An amount per amount of another ingredient, in any units; a space around the slash. Since 1.5.0. | +| **Ratio with units** | `a / b @&target` | `@eggs{1 / 100 g @&flour}`, `@salt{15 g / L @&water}` | Amount per reference amount of another ingredient, in any compatible units (space around `/`). | | **Composite child** | `<@parent` | `@lemon zest{1}<@lemon` | Bundles parts (zest, juice) into a single shopping item. | | **Passive timer** | `~_` | `~_{1h}` | Represents resting/rising time without blocking the cook. | -| **Proportional time** | `~{time / b @&target}` | `~{15 min / 500 g @&roast}`, `~{4 min / @&cutlet}` | A time that follows a weight or a count, computed again when scaled. Since 1.5.0. | +| **Proportional time** | `~{time / b @&target}` | `~{15 min / 500 g @&roast}`, `~{4 min / @&cutlet}` | Duration scaled dynamically by an ingredient's weight or count. | | **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. Since 1.5.0. | -| **Target state note** | `={...}(note)` | `={it coats the spoon}(a finger leaves a clean line)` | How to check the state, always shown. Since 1.5.0. | +| **Temperature note** | `^{...}(note)` | `^{160°C}(fan)`, `^{63°C}(internal)` | Oven mode or measurement condition, always displayed. | +| **Target state note** | `={...}(note)` | `={it coats the spoon}(a finger leaves a clean line)` | How to verify the target state, always displayed. | | **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. | +| **Sum of quantities** | `a + b`, `a - b` | `@flour{1 cup + 1 tbsp}`, `@sugar{1 cup - 2 tbsp}`, `@rice{1 cup + 20 g}` | Preserved as written and summed; incompatible kinds stay side by side. | -Every parenthetical note `(...)` — on an ingredient, cookware, a temperature, or a target state — must touch the element before it on the same line; with a space, it stays ordinary text. +Every parenthetical note `(...)`—on an ingredient, cookware, temperature, or target state—must touch the preceding token on the same line; with a space, it remains ordinary text. ## Intermediate variables @@ -1763,7 +1701,7 @@ Quantities and timers need a real number (or empty braces for "to taste"); fuzzy ```gram ❌ @flour{1 cup 5 tbsp} → ✅ @flour{1 cup + 5 tbsp} ``` -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}`). +Write multi-measure amounts as a [sum](/docs/reference/syntax/ingredients/#sums-of-quantities) (`{1 cup + 1 tbsp}`, `{1 cup - 2 tbsp}`, `{1 cup + 20 g}`) rather than collapsing them into decimals (`{1.0625 cup}`). Every term needs a unit, and only plain quantities are allowed (no `%`, no `×`, and no range after `-`). ### The oven mode left in the prose *(since v1.5.0)* @@ -1772,7 +1710,7 @@ Write an amount the recipe gives in several measures as a [sum](/docs/reference/ ❌ 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. +Attach oven modes and conditions ("fan", "internal", "covered") as a [parenthetical note](/docs/reference/syntax/temperatures/#cooking-mode-and-notes) directly touching `}`, in the recipe's language. Any space before `(` leaves it as plain text. ### The target state left in the prose *(since v1.5.0)* @@ -1781,7 +1719,7 @@ What goes with a temperature (the oven mode, "internal", "covered") belongs in a ❌ Whisk until ribbon stage. → ✅ Whisk until ={ribbon stage}. ❌ Cook until ={82°C} or ={5 min}. → ✅ Cook at ^{82°C}(internal) for ~{5 min}, until ={it coats the spoon}. ``` -When the source says what state the cook should reach (a texture, a color, a smell), mark it as a [target state](/docs/reference/syntax/target-states/), wherever it sits in the step: only the state between the braces, the linking words ("until", "as soon as", "when") left in the sentence, a test in a glued note if the source gives one. Never a temperature, a time or a quantity inside, and never a cue the source does not give. +Mark visual or sensory cues stated by the source as [target states](/docs/reference/syntax/target-states/) (`={...}`), keeping linking words ("until", "when") outside the braces and putting any verification test in a glued `(...)` note. Never put temperatures, durations, or quantities inside `={...}`, and never invent cues absent from the source. ### A proportional rule computed by hand *(since v1.5.0)* @@ -1791,7 +1729,7 @@ When the source says what state the cook should reach (a texture, a color, a sme ❌ Roast ~{36 min} (15 min per 500 g). → ✅ Roast ~{15 min / 500 g @&roast}. ❌ Add @eggs{1/100g @&flour}. → ✅ Add @eggs{1 / 100 g @&flour}. ``` -When the source states a proportional rule ("per 100 g", "per liter", "per pound", "per piece"), write it as a [ratio with units](/docs/reference/syntax/relative-quantities/#ratios-with-units): it follows the target when the recipe is scaled. Only then: an amount the source gives as such stays an amount. Always a space around the slash, the unit alone before the target (never `100 g of @&flour`), and no multiplier after a proportional time. +When the source states a proportional rule ("per 100 g", "per liter", "per piece"), write it as a [ratio with units](/docs/reference/syntax/relative-quantities/#ratios-with-units) so it scales with its target. Always leave a space around `/`, write the unit alone before the target (never `100 g of @&flour`), and omit multipliers on proportional times. ### Using `@&` on the first occurrence @@ -2188,7 +2126,7 @@ Mix @flour{200g} and @milk{200ml}. Note the compiler's `StepToken` vocabulary inside `content`: narrative text is a bare `string`; ingredients, cookware, and intermediate references share the `Usage` structure (no `type` field, identified by the presence of an `id`); timers, temperatures, target states (`checkpoint`, since 1.5.0: `{ type, state, note? }`), comments, and declarations each carry an explicit lowercase `type`. This distinction from the parser's PascalCase `ASTNodeType` is intentional: it describes compiled *output*, not parsed source syntax. See [How to build a custom UI](/docs/how-to/build-custom-ui) for a tutorial on consuming this structure in frontend frameworks. -*(since v1.5.0)* A timer token carries `raw`, the duration as written between the braces, and `minutes`, the duration the schedule uses (the middle of a range). `quantity` and `unit` stay, in the smallest unit written (`1h20` gives `80` `min`), so a program that reads them stays right; a duration written as before 1.5 (`1.5h`) keeps them unchanged. A timer Gram does not read keeps only `raw` (and `name`, `isPassive`): show it as written. +*(since v1.5.0)* A timer token carries `raw` (the duration as written inside the braces) and `minutes` (the scheduled duration, or the midpoint of a range). `quantity` and `unit` remain populated in the smallest written unit (`1h20` produces `80` `min`) for backwards compatibility, while pre-1.5 single-unit formats (`1.5h`) stay unchanged. Unrecognized timers keep only `raw` (plus `name` and `isPassive`) so views can display them as written. ```json { "type": "timer", "raw": "1h30", "quantity": { "type": "single", "value": 90 }, "unit": "min", "minutes": 90 } @@ -2196,11 +2134,11 @@ Note the compiler's `StepToken` vocabulary inside `content`: narrative text is a { "type": "timer", "raw": "1:30" } ``` -*(since v1.5.0)* A [sum of quantities](/docs/reference/syntax/ingredients/#sums-of-quantities) (`@flour{1 cup + 1 tbsp}`) adds `parts` to its `Usage`: each term as written, with its `qty` (a number or a `QuantityValue`) and `unit`, and `minus: true` on a term taken away. **`parts` is the only source of truth**; `qty` and `unit` are a total kept so that a program reading them stays right: +*(since v1.5.0)* A [sum of quantities](/docs/reference/syntax/ingredients/#sums-of-quantities) (`@flour{1 cup + 1 tbsp}`) adds `parts` to its `Usage`: each written term with `qty` (a number or `QuantityValue`), `unit`, and `minus: true` for subtracted terms. **`parts` is the source of truth**; `qty` and `unit` retain a compatibility summary: -- **One kind of unit**: `qty` / `unit` hold the total, in the smallest unit written when the units share a scale (`{1 cup + 1 tbsp}` gives `17` `tbsp`), in `ml` or `g` otherwise. A range in a term makes the total a range. -- **Several kinds** (a volume and a weight, or units Gram doesn't know): no `qty`, and `unit` holds the sum written out (`"1 cup + 20 g"`), like a quantity in words (`{a pinch}`). Read `parts` rather than parsing it. -- **Refused** (an `INVALID_QUANTITY` warning): `parts` alone, no `qty` nor `unit`. +- **Single unit family**: `qty` and `unit` hold the total, in the smallest written unit when terms share a scale (`{1 cup + 1 tbsp}` → `17` `tbsp`), or in `ml` / `g` otherwise. Any range term makes the total a range. +- **Multiple families** (a volume and a weight, or unknown units): `qty` is omitted and `unit` holds the written expression (`"1 cup + 20 g"`), similar to text quantities (`{a pinch}`). Read `parts` instead of parsing this string. +- **Invalid** (`INVALID_QUANTITY`): `parts` only, with neither `qty` nor `unit`. ```json { "id": "flour", "_usageId": "1", "qty": 17, "unit": "tbsp", "parts": [ { "qty": 1, "unit": "cup" }, { "qty": 1, "unit": "tbsp" } ] } @@ -2385,7 +2323,7 @@ interface Warning { `compile()` returns them on `CompilationResult.warnings`; `analyze()` carries those through and may push additional ones onto the same array on `AnalyzedCompilationResult.warnings`. Never a bare string — `.message` is always present. -*(since v1.5.0)* A few codes also carry `data`, the facts a tool needs to act on the warning without parsing `.message`: the language server passes it on as the diagnostic's `data`, and its Quick Fixes read it. Only `INVALID_QUANTITY` (`{ reason, suggestion? }`), `OZ_AFTER_VOLUME` (`{ suggestion }`) and an ingredient's `INVALID_UNIT` (`{ reason, suggestion? }`) set it; for the other codes it is absent. +*(since v1.5.0)* Certain codes also attach structured `data` so tools and language-server quick fixes can act without parsing `.message`. Only `INVALID_QUANTITY` (`{ reason, suggestion? }`), `OZ_AFTER_VOLUME` (`{ suggestion }`), and ingredient `INVALID_UNIT` (`{ reason, suggestion? }`) populate `data`. ## Severity & `--strict` @@ -2453,7 +2391,13 @@ A relative quantity references an ingredient (`50% of @name`) that hasn't appear ### `RELATIVE_QUANTITY_UNKNOWN_MASS` Pushed during analysis: the target of a relative quantity was found, but its own mass couldn't be computed (no resolvable unit/density), so the percentage can't be applied. **Fix**: give the target ingredient a standardizable unit, or a density/`unit_weight` entry in the ingredient database. -For a ratio with units (`1 / 100 g @&flour`, `~{15 min / 500 g @&roast}`, since 1.5.0) it carries a `reason` and points at the ratio: `noTargetQuantity` (the target has no amount), `incompatibleUnits` (`2 slices` against garlic counted in cloves, a weight against a named piece, or a unit followed by a word, `100 g of`), `missingDensity` (a weight against a volume, with no density), `missingUnitWeight` (pieces against a weight, with no `unit_weight`), and for an intermediate used whole (`Roll out the &dough`) `wholeUseAmbiguous` (another section uses it too) or `producerMassUnknown` (the mass of the section that makes it is incomplete). Gram never guesses a ratio it cannot compute: the amount stays unresolved. **Fix**: write the ratio in the unit the target is written in, add the density or `unit_weight` to the ingredient database, or write the amount of the intermediate used (`&dough{500 g}`). +For a [ratio with units](/docs/reference/syntax/relative-quantities/#ratios-with-units) (`1 / 100 g @&flour`, `~{15 min / 500 g @&roast}`, *(since v1.5.0)*), it includes a `reason` pointing to the ratio and leaves the amount unresolved: +- `noTargetQuantity`: the target has no quantity. +- `incompatibleUnits`: mismatched counts (`2 slices` against cloves), a weight against a named piece, or trailing words (`100 g of`). +- `missingDensity` / `missingUnitWeight`: converting between weight and volume or pieces requires `density` or `unit_weight` in the database. +- `wholeUseAmbiguous` / `producerMassUnknown`: for an intermediate used whole (`&dough`), either another section also consumes it or the producing section's mass is incomplete. + +**Fix**: match the target's unit, add `density` or `unit_weight` to the database, or specify the intermediate's used quantity (`&dough{500 g}`). ### `CIRCULAR_REFERENCE` An ingredient's relative quantity targets itself (`@flour{50% of @flour}`). **Fix**: remove the self-reference — a percentage-based quantity must target a *different* ingredient or variable. @@ -2465,37 +2409,35 @@ A bare reference (`&name`) or a referenceable ingredient (`@&name`) points to so A `Timer` or `Temperature` was written without an explicit unit (e.g. `~{10}` instead of `~{10 min}`). **Fix**: add an explicit unit. ### `INVALID_UNIT` -Either the word right after a number in a `Timer` (or a section's anchor) is not a time unit, as in `~{3 bananas}`, or a `Temperature` was given a unit other than Celsius/Fahrenheit. **Fix**: use a recognized time unit for timers (`h`, `hr`, `min`, `heures`…); use `°C` or `°F` for temperatures. +Either a word after a number in a `Timer` or section anchor is not a recognized time unit (`~{3 bananas}`), or a `Temperature` uses a unit other than Celsius or Fahrenheit. **Fix**: use a recognized time unit (`h`, `hr`, `min`, `heures`…), or `°C` / `°F` for temperatures. -*(since v1.4.1)* It also flags an ingredient whose unit reads as two quantities: a known unit, a number and another known unit, as in `@flour{1 cup 5 tbsp}` or `@flour{1 kg 200 g}`. The whole `cup 5 tbsp` is taken as one unknown unit: no mass, and a scaled recipe reads `2 cup 5 tbsp`. **Fix**: *(since v1.5.0)* write the two quantities as a [sum](/docs/reference/syntax/ingredients/#sums-of-quantities), `@flour{1 cup + 5 tbsp}`; the editor offers this fix, and `data.suggestion` holds the unit to write (`cup + 5 tbsp`). A number that only describes the unit, as in `@tomatoes{1 tin of 400 g}`, raises nothing: scaling the number of tins stays right. +*(since v1.4.1)* Also flags an ingredient whose unit looks like two quantities without an operator (`@flour{1 cup 5 tbsp}` or `@flour{1 kg 200 g}`), where `cup 5 tbsp` would otherwise be treated as one unknown unit with no mass. **Fix**: *(since v1.5.0)* write it as a [sum](/docs/reference/syntax/ingredients/#sums-of-quantities) (`@flour{1 cup + 5 tbsp}`); `data.suggestion` provides the corrected unit (`cup + 5 tbsp`) for editor quick fixes. Descriptive unit text like `@tomatoes{1 tin of 400 g}` is unaffected. -It flags as well a unit that hides a quantity, as in `@flour{about 200g}`: a quantity starts with its number, so with words in front the whole text was read as a unit, with no mass, and the quantity vanished from a scaled recipe. **Fix**: write the quantity alone (`@flour{200g}`), and the "about" in the step if it matters. Words with no number, such as `{a pinch}` or `{to taste}`, raise nothing. +Also flags units hiding a leading quantity (`@flour{about 200g}`), since quantities must start with a number. **Fix**: write `@flour{200g}` and keep `"about"` in the prose. Pure text quantities (`{a pinch}`, `{to taste}`) raise nothing. ### `INVALID_QUANTITY` *(since v1.5.0)* -A [sum of quantities](/docs/reference/syntax/ingredients/#sums-of-quantities) Gram refuses to add up. The recipe still compiles and the sum is shown as written, but it counts for nothing in the shopping list and the nutrition. The message and `data.reason` name the problem: +Emitted when a [sum of quantities](/docs/reference/syntax/ingredients/#sums-of-quantities) or number expression cannot be evaluated. The recipe still compiles and renders the text as written, but the value is excluded from shopping list and nutrition totals. `data.reason` identifies the cause: | `reason` | Example | Fix | | :--- | :--- | :--- | -| `unitlessTerm` | `{1 + 1 cup}` | Give every term its unit: `{1 cup + 1 tbsp}`. | -| `percentTerm` | `{100 g + 10%}` | Write the result (`{110 g}`, given in `data.suggestion` and offered by the editor), or a relative quantity such as `{10% &flour}`. | -| `expressionTerm` | `{2 x 100 g + 50 g}` | A sum only adds or takes away: write `{250 g}`. | -| `quantityInUnit` | `{1 tin of 400 g + 50 g}` | Write the amount in one unit: `{450 g}`. | -| `nonPositiveTotal` | `{1 tbsp - 1 cup}` | What is taken away is as much as what is added, or more: check the terms. | -| `rangeAfterMinus` | `{1 cup - 1-2 tbsp}` | A range taken away would swap its bounds: put it on a term that is added, or write the total as a range. | -| `minusAcrossFamilies` | `{1 cup - 20 g}` | Take an amount away from one of its kind only (a volume from a volume, a weight from a weight). | +| `unitlessTerm` | `{1 + 1 cup}` | Give every term a unit (`{1 cup + 1 tbsp}`). | +| `percentTerm` | `{100 g + 10%}` | Write the computed total (`{110 g}`, provided in `data.suggestion`) or use a relative quantity (`{10% &flour}`). | +| `expressionTerm` | `{2 x 100 g + 50 g}` | Sums only support `+` and `-`; write `{250 g}`. | +| `quantityInUnit` | `{1 tin of 400 g + 50 g}` | Express the amount in a single unit (`{450 g}`). | +| `nonPositiveTotal` | `{1 tbsp - 1 cup}` | Subtracted amount equals or exceeds what was added. | +| `rangeAfterMinus` | `{1 cup - 1-2 tbsp}` | Put ranges on added terms, or write the total as a range. | +| `minusAcrossFamilies` | `{1 cup - 20 g}` | Subtract only from the same unit family (volume from volume, weight from weight). | +| `zeroDenominator` | `{1/0 cup}`, `{1/0% &dough}`, `#pan{1/0}`, `^{1/0 °C}` | Division by zero is ignored; write a valid fraction (`1/2`). | +| `relativeNotSupported` | `@eggs{3}<@box{50% @&flour}`, `@eggs{1}<@box{1 / 100 g @&flour}` | Percentages and ratios are not supported on composite parents yet; specify the parent's quantity (`@eggs{3}<@box{1}`). | -Subtraction is checked kind by kind: each kind of amount adds up and takes away on its own, so `{1 cup - 2 tbsp + 30 g}` is fine (the 2 tbsp come off the cup), while `{1 cup - 20 g}` has no weight to take the 20 g from. The editor's hover on a sum shows what each kind comes to. - -It also flags, with `reason: "zeroDenominator"`, a fraction over zero anywhere a number is written (`@flour{1/0 cup}`, `{1 1/0 cup}`, a term of a sum, `{1/0% &dough}`, `#pan{1/0}`, `^{1/0 °C}`). Such a number has no value: Gram leaves it out, as if no number had been written (`cup` alone, a sum without that term, an ingredient with no quantity for a percentage), where it used to vanish without a word. **Fix**: write the fraction you meant (`1/2`). A timer says it through `INVALID_DURATION`. - -With `reason: "relativeNotSupported"`, it flags a percentage on a composite parent (`@eggs{3}<@box{50% @&flour}>`), which Gram does not support yet: the parent is read with no quantity, where the percentage used to vanish without a word. **Fix**: write the parent's amount (`<@box{1}>`). A ratio on a parent (`<@box{1 / 100 g @&flour}>`) is refused the same way, and a ratio over zero (`{1 / 0 g @&flour}`) raises `zeroDenominator`: the ingredient reads with no amount. +Subtraction is checked per unit family: `{1 cup - 2 tbsp + 30 g}` is valid (2 tbsp are subtracted from 1 cup), while `{1 cup - 20 g}` has no weight to subtract from. ### `OZ_AFTER_VOLUME` *(since v1.5.0)* -Information: a sum puts `oz` after a volume, as in `@water{1 cup + 2 oz}`. `oz` is an ounce of weight, so Gram reads it as one: the sum is a volume plus a weight. **Fix**: write `fl oz` if a fluid ounce was meant (`data.suggestion`, offered by the editor); otherwise there's nothing to do. +Informational notice when `oz` follows a volume in a sum (`@water{1 cup + 2 oz}`). Because `oz` denotes weight, Gram keeps it separate from the volume. **Fix**: change to `fl oz` if fluid ounces were intended (`data.suggestion` offers this quick fix). ### `DURATION_OUT_OF_RANGE` *(since v1.4.0)* @@ -2505,12 +2447,17 @@ A timer or a section's retro-planning offset lasts longer than 1000 years. **Fix ### `AMBIGUOUS_NUMBER` *(since v1.5.0)* -A comma followed by exactly three digits, after a whole part of one to three digits, as in `@flour{1,000 g}` or `@flour{12,500 g}`. Gram reads a comma between two digits as a decimal and has no thousands separator, so this is 1 g (and 12.5 g); the warning says how the number was read, because an English reader would see a thousand. The quantity stays usable either way. **Fix**: write `{1000 g}` if a thousand was meant, or `{1 g}` otherwise. A number that cannot be a thousands separator, such as `{0,125 kg}` or `{1,25 kg}`, raises nothing, and neither does a point: `{1.000 kg}` has always meant 1 kg. Every number of a recipe is checked: quantities, timers and temperatures, but also a percentage (`{1,000% &dough}`) and a section's anchor (`~{-1,000h}`, read as one hour), including one written on `@use`. An anchor that is dropped anyway, positive or with no valid unit, only raises `MISSING_UNIT`, `INVALID_UNIT` or `INVALID_DURATION`. +A comma followed by three digits after one to three integer digits (`@flour{1,000 g}`, `@flour{12,500 g}`). Because Gram supports decimal commas and has no thousands separator, `{1,000 g}` is parsed as `1 g` (and `{12,500 g}` as `12.5 g`). Checked across quantities, timers, temperatures, percentages, and section anchors (including on `@use`). **Fix**: write `{1000 g}` if a thousand was meant, or `{1 g}` otherwise. Periods (`{1.000 kg}`) always parse as decimals without warning. ### `INVALID_DURATION` *(since v1.5.0)* -A timer or a section's anchor is written with numbers and units Gram knows, but in a way it will not guess: `~{1:30}` (hours or minutes?), `~{30min 1h}` (units out of order), `~{1h75}` (75 minutes after an hour), `~{1-2h30}` (is the left side `1 h` or `1 h 30`?), `~{2-1 h}` (a range starts with the shorter duration), `~{2 * 2 min}` or `~{1 heure et demie}`. The message gives the reason and an example to write instead. The timer is not counted in the total time (only what was written is kept in the compiled JSON, as `raw`), and the anchor is dropped. A section anchor is also refused when it is a range (`~{-1-2d}`) or counts seconds (`~{-1min30}`, `~{-5'}`). A proportional time is refused with a multiplier (`~{15 min / 500 g @&roast * 2}`, `reason: "ratioMultiplication"`) or a range as its target amount (`~{15 min / 1-2 kg @&roast}`, `"ratioShape"`), and an anchor can never be one (`"anchorRatio"`). **Fix**: write the duration the way the message suggests, e.g. `~{1h30}`, `~{1:30 min}` or `~{1h30-2h}`. A word right after a number is an unknown unit and keeps raising `INVALID_UNIT`, and a number alone keeps raising `MISSING_UNIT`. +A timer or section anchor uses numbers and units Gram recognizes, but in an ambiguous or unsupported shape: +- **Ambiguous or malformed timers**: `~{1:30}` (hours or minutes?), `~{30min 1h}` (wrong order), `~{1h75}` (`≥ 60` after hours), `~{1-2h30}` (ambiguous range bound), `~{2-1 h}` (reversed range), `~{2 * 2 min}`, or prose (`~{half an hour}`). The timer is excluded from total time while keeping its `raw` string. +- **Unsupported anchors**: ranges (`~{-1-2d}`), seconds (`~{-1min30}`, `~{-5'}`), or proportional anchors (`reason: "anchorRatio"`). +- **Proportional timer limits**: multipliers (`~{15 min / 500 g @&roast * 2}`, `reason: "ratioMultiplication"`) or ranged targets (`~{15 min / 1-2 kg @&roast}`, `reason: "ratioShape"`). + +**Fix**: follow the suggested format in `.message` (e.g. `~{1h30}`, `~{1:30 min}`, `~{1h30-2h}`). Unknown units after a number still raise `INVALID_UNIT`, and bare numbers raise `MISSING_UNIT`. ### `SCOPE_CONFLICT` Two sections declare the same intermediate/global variable name (`>> name`). Variable names must be unique across the whole recipe, not just within a section. **Fix**: rename one of the two declarations. diff --git a/packages/docs/src/content/docs/docs/explanation/mass-and-yield.mdx b/packages/docs/src/content/docs/docs/explanation/mass-and-yield.mdx index 6ccb9cb8..1d614861 100644 --- a/packages/docs/src/content/docs/docs/explanation/mass-and-yield.mdx +++ b/packages/docs/src/content/docs/docs/explanation/mass-and-yield.mdx @@ -42,9 +42,9 @@ When the Analyzer encounters an ingredient, it runs it through a strict priority ### Weighing a sum of quantities -A [sum of quantities](/docs/reference/syntax/ingredients/#sums-of-quantities) is weighed kind by kind. The terms of one kind are added up first, then converted with the algorithm above: `@sugar{1 cup - 2 tbsp}` weighs exactly what `@sugar{14 tbsp}` weighs, and `@butter{1 cup + 30 g}` adds the weight of a cup (through the density) to 30 g. The yield applies kind by kind too, since a unit weight is a gross mass and grams written in the recipe are net. +A [sum of quantities](/docs/reference/syntax/ingredients/#sums-of-quantities) is weighed by unit family. Terms in the same family are summed first, then converted using the priority order above: `@sugar{1 cup - 2 tbsp}` weighs the same as `@sugar{14 tbsp}`, while `@butter{1 cup + 30 g}` adds the converted cup weight to 30 g. Yield applies per family as well, since a `unit_weight` reflects gross mass whereas explicit grams are net. -If one kind can't be weighed (`@rice{1 cup + 20 g}` with no density for rice), the whole sum gets **no** mass rather than a partial one: the shopping list merges entries by mass, and a partial mass would have you buy 20 g of rice and forget the cup. The grams still count where they are bought, in their own shopping-list entry. A sum Gram refuses (`INVALID_QUANTITY`) counts for nothing in the nutrition, like a missing quantity. +If any family cannot be weighed (such as `@rice{1 cup + 20 g}` without a density for rice), the sum receives **no** total mass rather than a partial one—otherwise shopping-list merging could keep the 20 g and lose the cup. The gram term still appears in its own shopping-list entry, while invalid sums (`INVALID_QUANTITY`) are excluded from nutrition totals. ## Yield calculation (the waste factor) diff --git a/packages/docs/src/content/docs/docs/explanation/scaling.mdx b/packages/docs/src/content/docs/docs/explanation/scaling.mdx index d8de112a..1ca5cce5 100644 --- a/packages/docs/src/content/docs/docs/explanation/scaling.mdx +++ b/packages/docs/src/content/docs/docs/explanation/scaling.mdx @@ -58,7 +58,7 @@ function resolveScaleFactor( ## Scaling sums of quantities -A [sum of quantities](/docs/reference/syntax/ingredients/#sums-of-quantities) scales term by term: `applyScale` multiplies each of its `parts`, then works out the total again. Showing it is the renderer's job, and it follows one rule: an unscaled recipe shows each sum as written; once scaled, an amount is written the way a cook measures it. +A [sum of quantities](/docs/reference/syntax/ingredients/#sums-of-quantities) scales term by term: `applyScale` multiplies each entry in `parts` and recomputes the total. The renderer preserves sums as written when unscaled, and recomposes scaled amounts into practical kitchen measures: | Written | Scaled | Shown | | :--- | :--- | :--- | @@ -70,19 +70,19 @@ A [sum of quantities](/docs/reference/syntax/ingredients/#sums-of-quantities) sc | `{1 kg + 200 g}` | × 2 | `2.4 kg` | | `{1 cup + 50 ml}` | × 2 | `2 cup + 100 ml` | -- **US and imperial units are recomposed** only when needed, into fractions a measuring cup or spoon actually has (¼, ⅓, ½, ⅔, ¾ of a cup; ½ tbsp; ⅛, ¼, ½ tsp…), never above the largest unit written, with spoons (`cup → tbsp → tsp`) and liquid measures (`gal → qt → pt → fl oz`) kept apart. Terms that can already be measured as they are stay. -- **Metric units stay in the largest unit written**, in decimals: you weigh in grams, so `{800 g + 200 g}` reads `1000 g`, not `1 kg`. Only the shopping list moves up to the unit you buy in (`1500 g` → `1.5 kg`). -- **A range** keeps the part both bounds share, and the spread goes on the last term. -- **Two systems** (`cup` and `ml`) stay term by term. +- **US and imperial units** are recomposed only when needed into standard measuring fractions (`¼`, `⅓`, `½`, `⅔`, `¾` cup; `½` tbsp; `⅛`, `¼`, `½` tsp…), staying within the largest unit written and keeping spoons (`cup → tbsp → tsp`) separate from liquid measures (`gal → qt → pt → fl oz`). +- **Metric units** keep the largest unit written using decimals (`{800 g + 200 g}` renders as `1000 g`, not `1 kg`); only the shopping list promotes totals to buying units (`1500 g` → `1.5 kg`). +- **Ranges** factor out the shared base and keep the spread on the final term. +- **Mixed systems** (`cup` and `ml`) scale term by term. -**Reverse scaling against a sum** (`--scale flour=500g`) uses its total when every term is of one kind; a volume next to a weight leaves two shopping-list entries, which raises `AMBIGUOUS_MULTI_UNIT`, as two separate mentions would. +**Reverse scaling against a sum** (`--scale flour=500g`) uses the combined total when all terms belong to the same family; mixing a volume and a weight produces two shopping-list entries and raises `AMBIGUOUS_MULTI_UNIT`. ## Scaling ratios and proportional times -A [ratio with units](/docs/reference/syntax/relative-quantities/#ratios-with-units) is never multiplied by the factor: `applyScale` scales the targets, then resolves every ratio again from what was written (`resolveRatios`, the same pass `compile` runs), so `@eggs{1 / 100 g @&flour}` follows the flour, and a ratio of a fixed target (`@=pepper{2 g}`) does not move. The shopping list is then built again from the scaled sections, so a fixed and a ratio use of one ingredient merge as they do at compile time. +A [ratio with units](/docs/reference/syntax/relative-quantities/#ratios-with-units) is never multiplied directly by the scale factor: `applyScale` scales the targets first, then re-runs `resolveRatios` from the original formula so `@eggs{1 / 100 g @&flour}` follows the scaled flour while a ratio pointing to a fixed target (`@=pepper{2 g}`) stays unchanged. The shopping list is rebuilt from the scaled sections so fixed and ratio-based uses merge just as they do at compile time. -When a [proportional time](/docs/reference/syntax/times/#proportional-times) changes (`~{15 min / 500 g @&roast}` for twice the roast), the schedule is laid out again by the same functions as `compile`: the `schedule`, the task graph, `metrics` and the deprecated `timings` describe the scaled recipe exactly as the rewritten source would compile. A recipe with no ratio scales as before. The warnings still describe the recipe as written. +When a [proportional time](/docs/reference/syntax/times/#proportional-times) changes (`~{15 min / 500 g @&roast}` for twice the roast), the schedule, task graph, `metrics`, and deprecated `timings` are recomputed by the same scheduling functions used by `compile()`, matching what the rescaled source would produce. Compiler warnings still reflect the unscaled source as written. ## Immutability diff --git a/packages/docs/src/content/docs/docs/explanation/shopping-list-aggregation.mdx b/packages/docs/src/content/docs/docs/explanation/shopping-list-aggregation.mdx index 8ca78929..436b24a6 100644 --- a/packages/docs/src/content/docs/docs/explanation/shopping-list-aggregation.mdx +++ b/packages/docs/src/content/docs/docs/explanation/shopping-list-aggregation.mdx @@ -38,13 +38,13 @@ import Term from '../../../../components/Term.astro'; Alias resolution happens one layer up, in `@gram-lang/analyzer`, which does have access to the ingredient database. If `beurre` is listed as an alias of `butter` in `ingredients.yaml`, the analyzer re-groups kitchen's raw entries by this canonical id, merging `@butter` and `@beurre` into a single `butter` entry. **This step only runs when an ingredient database is supplied** — without one (compiling with `@gram-lang/kitchen` alone, or a CLI command run without a database), aliases are not resolved and the two ingredients stay separate. 2. ### Unit merging - `@gram-lang/kitchen` merges what it can add up exactly, with no database, at three levels: + `@gram-lang/kitchen` merges exact quantities without a database across three levels: - - **Same unit**: `100g` and `50g` are summed (`150g`). Spellings of one unit count as one (`cup` and `cups`, `tbsp` and `tablespoon`). - - **Same scale**: units that convert by a whole ratio add up in the smallest unit written. US spoons and cups (`tsp`, `tbsp`, `fl oz`, `cup`, `pt`, `qt`, `gal`), ounces and pounds, grams and kilograms, milliliters and liters each form a scale: `1 cup` and `2 tbsp` give `18 tbsp` (shown as `1 cup + 2 tbsp`), `1 kg` and `200 g` give `1200 g` (shown as `1.2 kg`). - - **Different systems or kinds** (`cup` and `ml`, a volume and a weight): separate entries, flagged `multiUnit: true`. `pinch` and `dash` stay off every scale, since they are not exact measures. + - **Same unit**: `100g` and `50g` sum to `150g`, and spelling variants (`cup`/`cups`, `tbsp`/`tablespoon`) collapse together. + - **Same scale**: units with exact integer conversions sum in the smallest unit written. US kitchen measures (`tsp`, `tbsp`, `fl oz`, `cup`, `pt`, `qt`, `gal`), imperial weights (`oz`, `lb`), metric weights (`mg`, `g`, `kg`), and metric volumes (`ml`, `cl`, `dl`, `l`) each form a scale: `1 cup` and `2 tbsp` sum to `18 tbsp` (formatted as `1 cup + 2 tbsp`), and `1 kg` and `200 g` sum to `1200 g` (formatted as `1.2 kg`). + - **Different systems or kinds** (`cup` and `ml`, or volume and weight): kept as separate entries flagged `multiUnit: true`. Imprecise measures like `pinch` and `dash` stay off every scale. - A [sum of quantities](/docs/reference/syntax/ingredients/#sums-of-quantities) counts as separate mentions: `@milk{1 cup + 50 ml}` is bought as `1 cup` and `50 ml`, exactly like `@milk{1 cup}` then `@&milk{50 ml}`, so the shopping list never depends on how the author grouped the amounts. Ranges add up bound by bound (`2-3 g` and `200 g` give `202-203 g`, no longer the middle `202.5 g`). A unit Gram doesn't know is kept as written: `clove` and `cloves` stay two entries. + A [sum of quantities](/docs/reference/syntax/ingredients/#sums-of-quantities) behaves like separate mentions (`@milk{1 cup + 50 ml}` acts just like `@milk{1 cup}` followed by `@&milk{50 ml}`), so shopping lists never depend on how quantities were grouped. Ranges sum bound by bound (`2-3 g` and `200 g` yield `202-203 g`), while unrecognized units stay as written (`clove` and `cloves` remain distinct). Entries in different kinds of units (e.g., `100g` and `1 cup`) can only be summed converting through mass, which — like aliasing — depends on the ingredient database and therefore happens in `@gram-lang/analyzer`. If every contributing quantity resolves to a mass (density known, from the database or a recipe-level override), the analyzer converts them all to grams and merges them into a single entry. diff --git a/packages/docs/src/content/docs/docs/how-to/manage-database.mdx b/packages/docs/src/content/docs/docs/how-to/manage-database.mdx index 6c9c5b72..66b01a8c 100644 --- a/packages/docs/src/content/docs/docs/how-to/manage-database.mdx +++ b/packages/docs/src/content/docs/docs/how-to/manage-database.mdx @@ -10,10 +10,8 @@ This guide explains the standard workflow for maintaining your database using th import { Steps, LinkCard, CardGrid } from '@astrojs/starlight/components'; import Since from '../../../../components/Since.astro'; - - :::tip[See it in the playground] -The [playground](/play) shows the database its examples use, in its `ingredients.yaml` tab, beside the recipe files. It is the same format as your own file, read-only: an ingredient you add to a recipe there has no mass and no nutrition until it is in such a database. + The [playground](/play) displays the example `ingredients.yaml` database in a read-only tab alongside the recipe files. Any new ingredient you add there will have no mass or nutrition data unless it exists in this database. ::: ## The database workflow diff --git a/packages/docs/src/content/docs/docs/how-to/scale-recipes.mdx b/packages/docs/src/content/docs/docs/how-to/scale-recipes.mdx index 46d5861a..826b9299 100644 --- a/packages/docs/src/content/docs/docs/how-to/scale-recipes.mdx +++ b/packages/docs/src/content/docs/docs/how-to/scale-recipes.mdx @@ -71,7 +71,7 @@ gram view bread.gram --scale flour=400g Gram will compute the global factor (400/500 = 0.8), scale the anchor (flour) to 400g, and the relative ingredients will perfectly evaluate against this new base (Water: 70% of 400g = 280g). -Ratios with units scale the same way (since 1.5.0): `@eggs{1 / 100 g @&flour}` gives 4 eggs for 400 g of flour, and a proportional time such as `~{15 min / 500 g @&roast}` follows the roast, the schedule with it. +Ratios with units work the same way (since 1.5.0): `@eggs{1 / 100 g @&flour}` scales to 4 eggs for 400 g of flour, and a proportional timer like `~{15 min / 500 g @&roast}` adjusts both the duration and the schedule automatically. ### Limits of reference scaling diff --git a/packages/docs/src/content/docs/docs/how-to/weekly-shopping-list.mdx b/packages/docs/src/content/docs/docs/how-to/weekly-shopping-list.mdx index 8ad95d9f..7bd58c5d 100644 --- a/packages/docs/src/content/docs/docs/how-to/weekly-shopping-list.mdx +++ b/packages/docs/src/content/docs/docs/how-to/weekly-shopping-list.mdx @@ -53,7 +53,7 @@ gram shop "menus/*.gram" --format md --output shopping-list.md gram shop "menus/*.gram" --format json --output shopping-list.json ``` -Besides the amount as you read it (`qty`), the JSON gives each ingredient's amount as numbers (`amount`, `unit`), so a script or an app can sort, add up or compare them without reading the text. The [CLI reference](/docs/reference/tooling/cli/#gram-shop-pattern) describes every field. +Alongside the formatted `qty` string, `--format json` exports numeric fields (`amount`, `unit`, `range`, `parts`) so scripts and apps can sort, sum, or compare quantities without parsing text. See the [CLI reference](/docs/reference/tooling/cli/#gram-shop-pattern) for the full schema. ## Related resources diff --git a/packages/docs/src/content/docs/docs/reference/api/data-formats.mdx b/packages/docs/src/content/docs/docs/reference/api/data-formats.mdx index 4683f152..10617f52 100644 --- a/packages/docs/src/content/docs/docs/reference/api/data-formats.mdx +++ b/packages/docs/src/content/docs/docs/reference/api/data-formats.mdx @@ -287,7 +287,7 @@ Mix @flour{200g} and @milk{200ml}. Note the compiler's `StepToken` vocabulary inside `content`: narrative text is a bare `string`; ingredients, cookware, and intermediate references share the `Usage` structure (no `type` field, identified by the presence of an `id`); timers, temperatures, target states (`checkpoint`, since 1.5.0: `{ type, state, note? }`), comments, and declarations each carry an explicit lowercase `type`. This distinction from the parser's PascalCase `ASTNodeType` is intentional: it describes compiled *output*, not parsed source syntax. See [How to build a custom UI](/docs/how-to/build-custom-ui) for a tutorial on consuming this structure in frontend frameworks. - A timer token carries `raw`, the duration as written between the braces, and `minutes`, the duration the schedule uses (the middle of a range). `quantity` and `unit` stay, in the smallest unit written (`1h20` gives `80` `min`), so a program that reads them stays right; a duration written as before 1.5 (`1.5h`) keeps them unchanged. A timer Gram does not read keeps only `raw` (and `name`, `isPassive`): show it as written. + A timer token carries `raw` (the duration as written inside the braces) and `minutes` (the scheduled duration, or the midpoint of a range). `quantity` and `unit` remain populated in the smallest written unit (`1h20` produces `80` `min`) for backwards compatibility, while pre-1.5 single-unit formats (`1.5h`) stay unchanged. Unrecognized timers keep only `raw` (plus `name` and `isPassive`) so views can display them as written. ```json { "type": "timer", "raw": "1h30", "quantity": { "type": "single", "value": 90 }, "unit": "min", "minutes": 90 } @@ -295,11 +295,11 @@ Note the compiler's `StepToken` vocabulary inside `content`: narrative text is a { "type": "timer", "raw": "1:30" } ``` - A [sum of quantities](/docs/reference/syntax/ingredients/#sums-of-quantities) (`@flour{1 cup + 1 tbsp}`) adds `parts` to its `Usage`: each term as written, with its `qty` (a number or a `QuantityValue`) and `unit`, and `minus: true` on a term taken away. **`parts` is the only source of truth**; `qty` and `unit` are a total kept so that a program reading them stays right: + A [sum of quantities](/docs/reference/syntax/ingredients/#sums-of-quantities) (`@flour{1 cup + 1 tbsp}`) adds `parts` to its `Usage`: each written term with `qty` (a number or `QuantityValue`), `unit`, and `minus: true` for subtracted terms. **`parts` is the source of truth**; `qty` and `unit` retain a compatibility summary: -- **One kind of unit**: `qty` / `unit` hold the total, in the smallest unit written when the units share a scale (`{1 cup + 1 tbsp}` gives `17` `tbsp`), in `ml` or `g` otherwise. A range in a term makes the total a range. -- **Several kinds** (a volume and a weight, or units Gram doesn't know): no `qty`, and `unit` holds the sum written out (`"1 cup + 20 g"`), like a quantity in words (`{a pinch}`). Read `parts` rather than parsing it. -- **Refused** (an `INVALID_QUANTITY` warning): `parts` alone, no `qty` nor `unit`. +- **Single unit family**: `qty` and `unit` hold the total, in the smallest written unit when terms share a scale (`{1 cup + 1 tbsp}` → `17` `tbsp`), or in `ml` / `g` otherwise. Any range term makes the total a range. +- **Multiple families** (a volume and a weight, or unknown units): `qty` is omitted and `unit` holds the written expression (`"1 cup + 20 g"`), similar to text quantities (`{a pinch}`). Read `parts` instead of parsing this string. +- **Invalid** (`INVALID_QUANTITY`): `parts` only, with neither `qty` nor `unit`. ```json { "id": "flour", "_usageId": "1", "qty": 17, "unit": "tbsp", "parts": [ { "qty": 1, "unit": "cup" }, { "qty": 1, "unit": "tbsp" } ] } diff --git a/packages/docs/src/content/docs/docs/reference/api/i18n.mdx b/packages/docs/src/content/docs/docs/reference/api/i18n.mdx index bc9fb7f4..1b22d524 100644 --- a/packages/docs/src/content/docs/docs/reference/api/i18n.mdx +++ b/packages/docs/src/content/docs/docs/reference/api/i18n.mdx @@ -47,11 +47,11 @@ resolveTimeUnit('minutes'); // "m" resolveTimeUnit('heures', 'fr'); // "h" ``` -### Reading a duration +### Parsing a duration -`parseDuration` reads a duration as a timer writes it (`1h30`, `1 hr 30 mins`, `1:30 h`, `5'30"`, `45 min - 1 h`), in any language of `TIME_DICTIONARIES`, into minutes. It never guesses: a text it cannot read comes back with the reason, which kitchen turns into `MISSING_UNIT`, `INVALID_UNIT` or `INVALID_DURATION`. Each side keeps its terms (`parts`, in the unit written) and its form (`units`, `clock` or `prime`). It has no ceiling and no sign: the caller checks both. +`parseDuration` parses timer durations (`1h30`, `1 hr 30 mins`, `1:30 h`, `5'30"`, `45 min - 1 h`) into minutes across every language in `TIME_DICTIONARIES`. Unrecognized inputs return a failure reason—which `@gram-lang/kitchen` maps to `MISSING_UNIT`, `INVALID_UNIT`, or `INVALID_DURATION`—without guessing. Each side preserves its parsed `parts` and `form` (`units`, `clock`, or `prime`), with sign and upper-bound checks left to the caller. ```typescript function parseDuration(text: string): DurationResult diff --git a/packages/docs/src/content/docs/docs/reference/api/warnings.mdx b/packages/docs/src/content/docs/docs/reference/api/warnings.mdx index c4ad44d4..72d070f4 100644 --- a/packages/docs/src/content/docs/docs/reference/api/warnings.mdx +++ b/packages/docs/src/content/docs/docs/reference/api/warnings.mdx @@ -25,7 +25,7 @@ interface Warning { `compile()` returns them on `CompilationResult.warnings`; `analyze()` carries those through and may push additional ones onto the same array on `AnalyzedCompilationResult.warnings`. Never a bare string — `.message` is always present. - A few codes also carry `data`, the facts a tool needs to act on the warning without parsing `.message`: the language server passes it on as the diagnostic's `data`, and its Quick Fixes read it. Only `INVALID_QUANTITY` (`{ reason, suggestion? }`), `OZ_AFTER_VOLUME` (`{ suggestion }`) and an ingredient's `INVALID_UNIT` (`{ reason, suggestion? }`) set it; for the other codes it is absent. + Certain codes also attach structured `data` so tools and language-server quick fixes can act without parsing `.message`. Only `INVALID_QUANTITY` (`{ reason, suggestion? }`), `OZ_AFTER_VOLUME` (`{ suggestion }`), and ingredient `INVALID_UNIT` (`{ reason, suggestion? }`) populate `data`. ## Severity & `--strict` @@ -49,7 +49,13 @@ A relative quantity references an ingredient (`50% of @name`) that hasn't appear ### `RELATIVE_QUANTITY_UNKNOWN_MASS` Pushed during analysis: the target of a relative quantity was found, but its own mass couldn't be computed (no resolvable unit/density), so the percentage can't be applied. **Fix**: give the target ingredient a standardizable unit, or a density/`unit_weight` entry in the ingredient database. -For a ratio with units (`1 / 100 g @&flour`, `~{15 min / 500 g @&roast}`, since 1.5.0) it carries a `reason` and points at the ratio: `noTargetQuantity` (the target has no amount), `incompatibleUnits` (`2 slices` against garlic counted in cloves, a weight against a named piece, or a unit followed by a word, `100 g of`), `missingDensity` (a weight against a volume, with no density), `missingUnitWeight` (pieces against a weight, with no `unit_weight`), and for an intermediate used whole (`Roll out the &dough`) `wholeUseAmbiguous` (another section uses it too) or `producerMassUnknown` (the mass of the section that makes it is incomplete). Gram never guesses a ratio it cannot compute: the amount stays unresolved. **Fix**: write the ratio in the unit the target is written in, add the density or `unit_weight` to the ingredient database, or write the amount of the intermediate used (`&dough{500 g}`). +For a [ratio with units](/docs/reference/syntax/relative-quantities/#ratios-with-units) (`1 / 100 g @&flour`, `~{15 min / 500 g @&roast}`, ), it includes a `reason` pointing to the ratio and leaves the amount unresolved: +- `noTargetQuantity`: the target has no quantity. +- `incompatibleUnits`: mismatched counts (`2 slices` against cloves), a weight against a named piece, or trailing words (`100 g of`). +- `missingDensity` / `missingUnitWeight`: converting between weight and volume or pieces requires `density` or `unit_weight` in the database. +- `wholeUseAmbiguous` / `producerMassUnknown`: for an intermediate used whole (`&dough`), either another section also consumes it or the producing section's mass is incomplete. + +**Fix**: match the target's unit, add `density` or `unit_weight` to the database, or specify the intermediate's used quantity (`&dough{500 g}`). ### `CIRCULAR_REFERENCE` An ingredient's relative quantity targets itself (`@flour{50% of @flour}`). **Fix**: remove the self-reference — a percentage-based quantity must target a *different* ingredient or variable. @@ -61,37 +67,35 @@ A bare reference (`&name`) or a referenceable ingredient (`@&name`) points to so A `Timer` or `Temperature` was written without an explicit unit (e.g. `~{10}` instead of `~{10 min}`). **Fix**: add an explicit unit. ### `INVALID_UNIT` -Either the word right after a number in a `Timer` (or a section's anchor) is not a time unit, as in `~{3 bananas}`, or a `Temperature` was given a unit other than Celsius/Fahrenheit. **Fix**: use a recognized time unit for timers (`h`, `hr`, `min`, `heures`…); use `°C` or `°F` for temperatures. +Either a word after a number in a `Timer` or section anchor is not a recognized time unit (`~{3 bananas}`), or a `Temperature` uses a unit other than Celsius or Fahrenheit. **Fix**: use a recognized time unit (`h`, `hr`, `min`, `heures`…), or `°C` / `°F` for temperatures. - It also flags an ingredient whose unit reads as two quantities: a known unit, a number and another known unit, as in `@flour{1 cup 5 tbsp}` or `@flour{1 kg 200 g}`. The whole `cup 5 tbsp` is taken as one unknown unit: no mass, and a scaled recipe reads `2 cup 5 tbsp`. **Fix**: write the two quantities as a [sum](/docs/reference/syntax/ingredients/#sums-of-quantities), `@flour{1 cup + 5 tbsp}`; the editor offers this fix, and `data.suggestion` holds the unit to write (`cup + 5 tbsp`). A number that only describes the unit, as in `@tomatoes{1 tin of 400 g}`, raises nothing: scaling the number of tins stays right. + Also flags an ingredient whose unit looks like two quantities without an operator (`@flour{1 cup 5 tbsp}` or `@flour{1 kg 200 g}`), where `cup 5 tbsp` would otherwise be treated as one unknown unit with no mass. **Fix**: write it as a [sum](/docs/reference/syntax/ingredients/#sums-of-quantities) (`@flour{1 cup + 5 tbsp}`); `data.suggestion` provides the corrected unit (`cup + 5 tbsp`) for editor quick fixes. Descriptive unit text like `@tomatoes{1 tin of 400 g}` is unaffected. -It flags as well a unit that hides a quantity, as in `@flour{about 200g}`: a quantity starts with its number, so with words in front the whole text was read as a unit, with no mass, and the quantity vanished from a scaled recipe. **Fix**: write the quantity alone (`@flour{200g}`), and the "about" in the step if it matters. Words with no number, such as `{a pinch}` or `{to taste}`, raise nothing. +Also flags units hiding a leading quantity (`@flour{about 200g}`), since quantities must start with a number. **Fix**: write `@flour{200g}` and keep `"about"` in the prose. Pure text quantities (`{a pinch}`, `{to taste}`) raise nothing. ### `INVALID_QUANTITY` -A [sum of quantities](/docs/reference/syntax/ingredients/#sums-of-quantities) Gram refuses to add up. The recipe still compiles and the sum is shown as written, but it counts for nothing in the shopping list and the nutrition. The message and `data.reason` name the problem: +Emitted when a [sum of quantities](/docs/reference/syntax/ingredients/#sums-of-quantities) or number expression cannot be evaluated. The recipe still compiles and renders the text as written, but the value is excluded from shopping list and nutrition totals. `data.reason` identifies the cause: | `reason` | Example | Fix | | :--- | :--- | :--- | -| `unitlessTerm` | `{1 + 1 cup}` | Give every term its unit: `{1 cup + 1 tbsp}`. | -| `percentTerm` | `{100 g + 10%}` | Write the result (`{110 g}`, given in `data.suggestion` and offered by the editor), or a relative quantity such as `{10% &flour}`. | -| `expressionTerm` | `{2 x 100 g + 50 g}` | A sum only adds or takes away: write `{250 g}`. | -| `quantityInUnit` | `{1 tin of 400 g + 50 g}` | Write the amount in one unit: `{450 g}`. | -| `nonPositiveTotal` | `{1 tbsp - 1 cup}` | What is taken away is as much as what is added, or more: check the terms. | -| `rangeAfterMinus` | `{1 cup - 1-2 tbsp}` | A range taken away would swap its bounds: put it on a term that is added, or write the total as a range. | -| `minusAcrossFamilies` | `{1 cup - 20 g}` | Take an amount away from one of its kind only (a volume from a volume, a weight from a weight). | +| `unitlessTerm` | `{1 + 1 cup}` | Give every term a unit (`{1 cup + 1 tbsp}`). | +| `percentTerm` | `{100 g + 10%}` | Write the computed total (`{110 g}`, provided in `data.suggestion`) or use a relative quantity (`{10% &flour}`). | +| `expressionTerm` | `{2 x 100 g + 50 g}` | Sums only support `+` and `-`; write `{250 g}`. | +| `quantityInUnit` | `{1 tin of 400 g + 50 g}` | Express the amount in a single unit (`{450 g}`). | +| `nonPositiveTotal` | `{1 tbsp - 1 cup}` | Subtracted amount equals or exceeds what was added. | +| `rangeAfterMinus` | `{1 cup - 1-2 tbsp}` | Put ranges on added terms, or write the total as a range. | +| `minusAcrossFamilies` | `{1 cup - 20 g}` | Subtract only from the same unit family (volume from volume, weight from weight). | +| `zeroDenominator` | `{1/0 cup}`, `{1/0% &dough}`, `#pan{1/0}`, `^{1/0 °C}` | Division by zero is ignored; write a valid fraction (`1/2`). | +| `relativeNotSupported` | `@eggs{3}<@box{50% @&flour}`, `@eggs{1}<@box{1 / 100 g @&flour}` | Percentages and ratios are not supported on composite parents yet; specify the parent's quantity (`@eggs{3}<@box{1}`). | -Subtraction is checked kind by kind: each kind of amount adds up and takes away on its own, so `{1 cup - 2 tbsp + 30 g}` is fine (the 2 tbsp come off the cup), while `{1 cup - 20 g}` has no weight to take the 20 g from. The editor's hover on a sum shows what each kind comes to. - -It also flags, with `reason: "zeroDenominator"`, a fraction over zero anywhere a number is written (`@flour{1/0 cup}`, `{1 1/0 cup}`, a term of a sum, `{1/0% &dough}`, `#pan{1/0}`, `^{1/0 °C}`). Such a number has no value: Gram leaves it out, as if no number had been written (`cup` alone, a sum without that term, an ingredient with no quantity for a percentage), where it used to vanish without a word. **Fix**: write the fraction you meant (`1/2`). A timer says it through `INVALID_DURATION`. - -With `reason: "relativeNotSupported"`, it flags a percentage on a composite parent (`@eggs{3}<@box{50% @&flour}>`), which Gram does not support yet: the parent is read with no quantity, where the percentage used to vanish without a word. **Fix**: write the parent's amount (`<@box{1}>`). A ratio on a parent (`<@box{1 / 100 g @&flour}>`) is refused the same way, and a ratio over zero (`{1 / 0 g @&flour}`) raises `zeroDenominator`: the ingredient reads with no amount. +Subtraction is checked per unit family: `{1 cup - 2 tbsp + 30 g}` is valid (2 tbsp are subtracted from 1 cup), while `{1 cup - 20 g}` has no weight to subtract from. ### `OZ_AFTER_VOLUME` -Information: a sum puts `oz` after a volume, as in `@water{1 cup + 2 oz}`. `oz` is an ounce of weight, so Gram reads it as one: the sum is a volume plus a weight. **Fix**: write `fl oz` if a fluid ounce was meant (`data.suggestion`, offered by the editor); otherwise there's nothing to do. +Informational notice when `oz` follows a volume in a sum (`@water{1 cup + 2 oz}`). Because `oz` denotes weight, Gram keeps it separate from the volume. **Fix**: change to `fl oz` if fluid ounces were intended (`data.suggestion` offers this quick fix). ### `DURATION_OUT_OF_RANGE` @@ -101,12 +105,17 @@ A timer or a section's retro-planning offset lasts longer than 1000 years. **Fix ### `AMBIGUOUS_NUMBER` -A comma followed by exactly three digits, after a whole part of one to three digits, as in `@flour{1,000 g}` or `@flour{12,500 g}`. Gram reads a comma between two digits as a decimal and has no thousands separator, so this is 1 g (and 12.5 g); the warning says how the number was read, because an English reader would see a thousand. The quantity stays usable either way. **Fix**: write `{1000 g}` if a thousand was meant, or `{1 g}` otherwise. A number that cannot be a thousands separator, such as `{0,125 kg}` or `{1,25 kg}`, raises nothing, and neither does a point: `{1.000 kg}` has always meant 1 kg. Every number of a recipe is checked: quantities, timers and temperatures, but also a percentage (`{1,000% &dough}`) and a section's anchor (`~{-1,000h}`, read as one hour), including one written on `@use`. An anchor that is dropped anyway, positive or with no valid unit, only raises `MISSING_UNIT`, `INVALID_UNIT` or `INVALID_DURATION`. +A comma followed by three digits after one to three integer digits (`@flour{1,000 g}`, `@flour{12,500 g}`). Because Gram supports decimal commas and has no thousands separator, `{1,000 g}` is parsed as `1 g` (and `{12,500 g}` as `12.5 g`). Checked across quantities, timers, temperatures, percentages, and section anchors (including on `@use`). **Fix**: write `{1000 g}` if a thousand was meant, or `{1 g}` otherwise. Periods (`{1.000 kg}`) always parse as decimals without warning. ### `INVALID_DURATION` -A timer or a section's anchor is written with numbers and units Gram knows, but in a way it will not guess: `~{1:30}` (hours or minutes?), `~{30min 1h}` (units out of order), `~{1h75}` (75 minutes after an hour), `~{1-2h30}` (is the left side `1 h` or `1 h 30`?), `~{2-1 h}` (a range starts with the shorter duration), `~{2 * 2 min}` or `~{1 heure et demie}`. The message gives the reason and an example to write instead. The timer is not counted in the total time (only what was written is kept in the compiled JSON, as `raw`), and the anchor is dropped. A section anchor is also refused when it is a range (`~{-1-2d}`) or counts seconds (`~{-1min30}`, `~{-5'}`). A proportional time is refused with a multiplier (`~{15 min / 500 g @&roast * 2}`, `reason: "ratioMultiplication"`) or a range as its target amount (`~{15 min / 1-2 kg @&roast}`, `"ratioShape"`), and an anchor can never be one (`"anchorRatio"`). **Fix**: write the duration the way the message suggests, e.g. `~{1h30}`, `~{1:30 min}` or `~{1h30-2h}`. A word right after a number is an unknown unit and keeps raising `INVALID_UNIT`, and a number alone keeps raising `MISSING_UNIT`. +A timer or section anchor uses numbers and units Gram recognizes, but in an ambiguous or unsupported shape: +- **Ambiguous or malformed timers**: `~{1:30}` (hours or minutes?), `~{30min 1h}` (wrong order), `~{1h75}` (`≥ 60` after hours), `~{1-2h30}` (ambiguous range bound), `~{2-1 h}` (reversed range), `~{2 * 2 min}`, or prose (`~{half an hour}`). The timer is excluded from total time while keeping its `raw` string. +- **Unsupported anchors**: ranges (`~{-1-2d}`), seconds (`~{-1min30}`, `~{-5'}`), or proportional anchors (`reason: "anchorRatio"`). +- **Proportional timer limits**: multipliers (`~{15 min / 500 g @&roast * 2}`, `reason: "ratioMultiplication"`) or ranged targets (`~{15 min / 1-2 kg @&roast}`, `reason: "ratioShape"`). + +**Fix**: follow the suggested format in `.message` (e.g. `~{1h30}`, `~{1:30 min}`, `~{1h30-2h}`). Unknown units after a number still raise `INVALID_UNIT`, and bare numbers raise `MISSING_UNIT`. ### `SCOPE_CONFLICT` Two sections declare the same intermediate/global variable name (`>> name`). Variable names must be unique across the whole recipe, not just within a section. **Fix**: rename one of the two declarations. 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 cc766705..4de8f307 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 @@ -77,7 +77,7 @@ Quantities and timers need a real number (or empty braces for "to taste"); fuzzy ```gram ❌ @flour{1 cup 5 tbsp} → ✅ @flour{1 cup + 5 tbsp} ``` -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}`). +Write multi-measure amounts as a [sum](/docs/reference/syntax/ingredients/#sums-of-quantities) (`{1 cup + 1 tbsp}`, `{1 cup - 2 tbsp}`, `{1 cup + 20 g}`) rather than collapsing them into decimals (`{1.0625 cup}`). Every term needs a unit, and only plain quantities are allowed (no `%`, no `×`, and no range after `-`). ### The oven mode left in the prose @@ -86,7 +86,7 @@ Write an amount the recipe gives in several measures as a [sum](/docs/reference/ ❌ 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. +Attach oven modes and conditions ("fan", "internal", "covered") as a [parenthetical note](/docs/reference/syntax/temperatures/#cooking-mode-and-notes) directly touching `}`, in the recipe's language. Any space before `(` leaves it as plain text. ### The target state left in the prose @@ -95,7 +95,7 @@ What goes with a temperature (the oven mode, "internal", "covered") belongs in a ❌ Whisk until ribbon stage. → ✅ Whisk until ={ribbon stage}. ❌ Cook until ={82°C} or ={5 min}. → ✅ Cook at ^{82°C}(internal) for ~{5 min}, until ={it coats the spoon}. ``` -When the source says what state the cook should reach (a texture, a color, a smell), mark it as a [target state](/docs/reference/syntax/target-states/), wherever it sits in the step: only the state between the braces, the linking words ("until", "as soon as", "when") left in the sentence, a test in a glued note if the source gives one. Never a temperature, a time or a quantity inside, and never a cue the source does not give. +Mark visual or sensory cues stated by the source as [target states](/docs/reference/syntax/target-states/) (`={...}`), keeping linking words ("until", "when") outside the braces and putting any verification test in a glued `(...)` note. Never put temperatures, durations, or quantities inside `={...}`, and never invent cues absent from the source. ### A proportional rule computed by hand @@ -105,7 +105,7 @@ When the source says what state the cook should reach (a texture, a color, a sme ❌ Roast ~{36 min} (15 min per 500 g). → ✅ Roast ~{15 min / 500 g @&roast}. ❌ Add @eggs{1/100g @&flour}. → ✅ Add @eggs{1 / 100 g @&flour}. ``` -When the source states a proportional rule ("per 100 g", "per liter", "per pound", "per piece"), write it as a [ratio with units](/docs/reference/syntax/relative-quantities/#ratios-with-units): it follows the target when the recipe is scaled. Only then: an amount the source gives as such stays an amount. Always a space around the slash, the unit alone before the target (never `100 g of @&flour`), and no multiplier after a proportional time. +When the source states a proportional rule ("per 100 g", "per liter", "per piece"), write it as a [ratio with units](/docs/reference/syntax/relative-quantities/#ratios-with-units) so it scales with its target. Always leave a space around `/`, write the unit alone before the target (never `100 g of @&flour`), and omit multipliers on proportional times. ### Using `@&` on the first occurrence 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 6214c132..0a72ea1b 100644 --- a/packages/docs/src/content/docs/docs/reference/syntax/cheatsheet.mdx +++ b/packages/docs/src/content/docs/docs/reference/syntax/cheatsheet.mdx @@ -15,9 +15,9 @@ Essential markup tokens used directly inside recipe steps: | :--- | :--- | :--- | :--- | :--- | | **Ingredient** | `@` | `@name[{quantity}]` | `@flour{200g}` | Declares an ingredient. Omitting `{}` indicates no specific quantity (e.g. `@salt`). | | **Cookware** | `#` | `#name[{quantity}]` | `#pan{2}`, `#whisk` | Specifies kitchen equipment. Omitting `{}` defaults to a single item (`1`). | -| **Timer** | `~` | `~{time}` | `~{30min}`, `~{1h30}` | Defines an active cooking or preparation duration, written as in a recipe (`1 hr 30 mins`, `1:30 h`, `5'30"`). | -| **Temperature** | `^` | `^{temperature}` | `^{180°C}`, `^{350°F}` | Declares an exact heat setting (`C` or `F`, case-insensitive). | -| **Target state** | `=` | `={state}` | `={ribbon stage}`, `={golden}` | The state to reach, in the cook's words, anywhere in the step. Since 1.5.0. | +| **Timer** | `~` | `~{time}` | `~{30min}`, `~{1h30}` | Active cooking or preparation duration (`1 hr 30 mins`, `1:30 h`, `5'30"`). | +| **Temperature** | `^` | `^{temperature}` | `^{180°C}`, `^{350°F}` | Exact heat setting (`C` or `F`, case-insensitive). | +| **Target state** | `=` | `={state}` | `={ribbon stage}`, `={golden}` | Sensory cue to reach, placed anywhere in the step. | ## Modifiers @@ -42,18 +42,18 @@ Specialized patterns for flexible culinary instructions: | **Short-hand prep** | `(...)` | `@butter{10g}(room temp)` | Notes prep techniques without cluttering names. | | **Component alias** | `:slug` | `@dry white wine:wine{10ml}` | Displays user-friendly text while mapping to a canonical ID. | | **Relative quantity** | `% @&target` | `@water{70% @&flour}` | Computes amount relative to a reference ingredient mass. | -| **Ratio with units** | `a / b @&target` | `@eggs{1 / 100 g @&flour}`, `@salt{15 g / L @&water}` | An amount per amount of another ingredient, in any units; a space around the slash. Since 1.5.0. | +| **Ratio with units** | `a / b @&target` | `@eggs{1 / 100 g @&flour}`, `@salt{15 g / L @&water}` | Amount per reference amount of another ingredient, in any compatible units (space around `/`). | | **Composite child** | `<@parent` | `@lemon zest{1}<@lemon` | Bundles parts (zest, juice) into a single shopping item. | | **Passive timer** | `~_` | `~_{1h}` | Represents resting/rising time without blocking the cook. | -| **Proportional time** | `~{time / b @&target}` | `~{15 min / 500 g @&roast}`, `~{4 min / @&cutlet}` | A time that follows a weight or a count, computed again when scaled. Since 1.5.0. | +| **Proportional time** | `~{time / b @&target}` | `~{15 min / 500 g @&roast}`, `~{4 min / @&cutlet}` | Duration scaled dynamically by an ingredient's weight or count. | | **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. Since 1.5.0. | -| **Target state note** | `={...}(note)` | `={it coats the spoon}(a finger leaves a clean line)` | How to check the state, always shown. Since 1.5.0. | +| **Temperature note** | `^{...}(note)` | `^{160°C}(fan)`, `^{63°C}(internal)` | Oven mode or measurement condition, always displayed. | +| **Target state note** | `={...}(note)` | `={it coats the spoon}(a finger leaves a clean line)` | How to verify the target state, always displayed. | | **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. | +| **Sum of quantities** | `a + b`, `a - b` | `@flour{1 cup + 1 tbsp}`, `@sugar{1 cup - 2 tbsp}`, `@rice{1 cup + 20 g}` | Preserved as written and summed; incompatible kinds stay side by side. | -Every parenthetical note `(...)` — on an ingredient, cookware, a temperature, or a target state — must touch the element before it on the same line; with a space, it stays ordinary text. +Every parenthetical note `(...)`—on an ingredient, cookware, temperature, or target state—must touch the preceding token on the same line; with a space, it remains ordinary text. ## Intermediate variables diff --git a/packages/docs/src/content/docs/docs/reference/syntax/ingredients.mdx b/packages/docs/src/content/docs/docs/reference/syntax/ingredients.mdx index c56946a5..b7d99156 100644 --- a/packages/docs/src/content/docs/docs/reference/syntax/ingredients.mdx +++ b/packages/docs/src/content/docs/docs/reference/syntax/ingredients.mdx @@ -201,7 +201,7 @@ Add @butter{1½ sticks}. ### Decimal numbers -A decimal number takes a point or a comma, whichever you are used to: `{1.5 kg}` and `{1,5 kg}` are the same quantity. This holds for every number in braces: ingredients, ranges (`{0,5-0,75 l}`), relative quantities (`{12,5% &dough}`), cookware, temperatures (`^{37,5°C}`), timers and section anchors. +Decimals accept either a period or a comma: `{1.5 kg}` and `{1,5 kg}` mean the same thing. This applies to every number inside braces—ingredients, ranges (`{0,5-0,75 l}`), relative quantities (`{12,5% &dough}`), cookware, temperatures (`^{37,5°C}`), timers, and section anchors. ```gram Add @flour{1,5 kg} and @salt{0.125 kg}. @@ -209,12 +209,12 @@ Add @flour{1,5 kg} and @salt{0.125 kg}. Pour @milk{0,5-0,75 l}. ``` -Gram has no thousands separator: write `{1500 g}`, never `{1,500 g}`. A comma followed by exactly three digits is read as a decimal like any other (`{1,000 g}` is 1 g), but since a reader could mean a thousand, the compiler warns `AMBIGUOUS_NUMBER` and says how it read the number. A point keeps the meaning it has always had: `{1.000 kg}` is 1 kg, with no warning. +Gram has no thousands separator: write `{1500 g}`, never `{1,500 g}`. A comma followed by three digits like `{1,000 g}` is parsed as a decimal (`1 g`) and triggers an `AMBIGUOUS_NUMBER` warning; a period (`{1.000 kg}`) always means `1 kg` with no warning. ### Sums of quantities -A measure that doesn't fit one unit is written the way a recipe says it: terms joined by `+`, or `-` for an amount taken away. +When a measurement combines more than one unit, write it as a sum with `+`, or `-` for an amount subtracted: ```gram Add @flour{1 cup + 1 tbsp} and @sugar{1 cup - 2 tbsp}. @@ -224,38 +224,36 @@ Pour @milk{1 cup + 1-2 tbsp}. Mix in @butter{2 1/2 tbsp + ½ tsp} and @rice{1 cup + 20 g}. ``` -Each term is a number (or a range, or a fraction) with its unit. Gram keeps the terms as written and works out their total: `{1 cup + 1 tbsp}` is 17 tbsp, `{1 cup - 2 tbsp}` is 14 tbsp. The recipe shows the sum as you wrote it; once scaled, it is worked out again into amounts a cook can measure (`{1 cup + 1 tbsp}` doubled reads `2 cup + 2 tbsp`, never `2 1/8 cup`). The `=` modifier locks a sum like any other quantity (`@=salt{1,5 g + 1 pinch}`). +Each term is a quantity (number, range, or fraction) with its unit. Gram preserves the sum as written in the unscaled recipe, and recomputes it into practical kitchen measures when scaling (for example, doubling `{1 cup + 1 tbsp}` gives `2 cup + 2 tbsp`). Adding `=` locks the entire sum (`@=salt{1,5 g + 1 pinch}`). -A sum counts as **separate mentions** of the ingredient: `@rice{1 cup + 20 g}` goes into the shopping list exactly like `@rice{1 cup}` followed by `@&rice{20 g}`. Terms of the same kind of unit add up (cups and spoons, kilos and grams); a volume next to a weight, or two units Gram doesn't know (`{1 head + 2 cloves}`), stay side by side. +In the shopping list, a sum behaves like separate mentions of the ingredient: compatible units add up (cups and spoons, grams and kilograms), while a volume and a weight (`{1 cup + 20 g}`) or unrecognized units stay side by side. -A few rules keep a sum readable: +A few rules keep sums unambiguous: -- **Every term has its unit**: `{1 + 1 cup}` is refused. -- **Only amounts**: no percentage (`{100 g + 10%}`, write `{110 g}`, or a [relative quantity](/docs/reference/syntax/relative-quantities/)), no multiplication (`{2 x 100 g + 50 g}`). -- **Take away from the same kind**: `{1 cup - 2 tbsp}` works, `{1 cup - 20 g}` doesn't, and what is taken away must leave something (`{1 tbsp - 1 cup}` is refused). -- **No range after `-`**: `{1 cup - 1-2 tbsp}` would swap its bounds; write the range on a term that is added. +- **Every term needs a unit**: `{1 + 1 cup}` is rejected. +- **Plain quantities only**: no percentages (`{100 g + 10%}`) or multiplications (`{2 x 100 g}`). +- **Subtract within the same kind**: `{1 cup - 2 tbsp}` works, `{1 cup - 20 g}` does not, and the result must remain positive (`{1 tbsp - 1 cup}` is rejected). +- **No range after `-`**: put ranges on added terms (`{1 cup + 1-2 tbsp}`), never subtracted ones. -Each kind of amount adds up and takes away **on its own**, because a volume and a weight can't be compared without a density. In `{1 cup - 2 tbsp + 30 g}`, the 2 tbsp come off the cup and the 30 g are added beside them: the sum is 14 tbsp of volume plus 30 g of weight. In `{1 cup - 20 g}`, there is no weight to take the 20 g from, so Gram refuses it rather than guess. Hover a sum in the editor to see what each kind comes to. +An invalid sum still compiles with an `INVALID_QUANTITY` warning explaining why, and is excluded from shopping list and nutrition totals. See [Scaling sums of quantities](/docs/explanation/scaling/#scaling-sums-of-quantities) for details. -A refused sum compiles with an `INVALID_QUANTITY` warning that says why, and counts for nothing in the shopping list and the nutrition. Two quantities written side by side without an operator (`{1 cup 5 tbsp}`) raise `INVALID_UNIT`; the editor offers to insert the ` + `. - -:::caution[oz is a weight] -In `{1 cup + 2 oz}`, `oz` is an ounce of weight, not of volume: Gram reads it as written and adds a note (`OZ_AFTER_VOLUME`). Write `fl oz` for a fluid ounce. +:::caution[`oz` means weight] +In `{1 cup + 2 oz}`, `oz` is parsed as weight (ounces), not fluid volume (`OZ_AFTER_VOLUME`). Write `fl oz` for fluid ounces. ::: ## 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. +Some syntax errors stop parsing before compilation: an unreadable quantity in braces (`@salt{1 g/l}`) or an unclosed brace. The error points to the exact spot to fix. -The compiler checks for semantic errors in your `@ingredient` declarations and will output specific warnings: +The compiler checks for semantic errors in your `@ingredient` declarations and emits structured warnings: - **Invalid Modifier**: If you combine incompatible modifiers (like `?*`), the compiler warns `INVALID_MODIFIER_COMBINATION` and ignores them. -- **Undefined Reference**: If you use a reference (`@&ingredient`) but that item hasn't been declared previously in the recipe, the compiler warns `UNDEFINED_REFERENCE`. +- **Undefined Reference**: If you use a reference (`@&ingredient`) before it has been declared in the recipe, the compiler warns `UNDEFINED_REFERENCE`. - **Database Missing**: If you compile with a database and the `@ingredient` is not found, it warns `MISSING_INGREDIENT`. - **Missing Macros**: If the database lacks nutritional information for the `@ingredient`, it warns `MISSING_MACROS`. - **Unknown Mass**: If it cannot convert a volume or count into grams to estimate nutrition, it warns `UNKNOWN_MASS`. -- **Invalid Quantity**: If a sum of quantities can't be read (a term without a unit, a percentage, an amount taken away from another kind…), it warns `INVALID_QUANTITY` and gives the reason. -- **Ambiguous Number**: If a comma is followed by exactly three digits (`{1,000 g}`), it reads a decimal and warns `AMBIGUOUS_NUMBER`, in case a thousand was meant. +- **Invalid Quantity**: If a sum of quantities breaks one of the rules above, it warns `INVALID_QUANTITY` with the reason. +- **Ambiguous Number**: If a comma is followed by three digits (`{1,000 g}`), it parses a decimal and warns `AMBIGUOUS_NUMBER`. ## Related resources diff --git a/packages/docs/src/content/docs/docs/reference/syntax/relative-quantities.mdx b/packages/docs/src/content/docs/docs/reference/syntax/relative-quantities.mdx index e4676ef7..6beff12f 100644 --- a/packages/docs/src/content/docs/docs/reference/syntax/relative-quantities.mdx +++ b/packages/docs/src/content/docs/docs/reference/syntax/relative-quantities.mdx @@ -49,12 +49,12 @@ When the compiler resolves a relative quantity, it follows four strict scoping a | **Section scoping** | Current section only | You cannot directly target a base `@ingredient` declared in a different section. To bridge sections, capture the result into a globally scoped `&variable`. | | **Accumulation** | Sums all occurrences | If the target `@ingredient` appears multiple times within the same section, the percentage applies to their **cumulative total**. | | **Mass-based** | Evaluated in grams | Calculations are always performed against **physical mass in grams**. For example, 50% of "2 eggs" (each standardized at 50g) produces **50g**, not 1 egg. | -| **Alternatives** | One option at a time | Each option of an alternative gets its own amount, never added to the others: `@butter{10% @&flour}\|@oil{8% @&flour}` reads "20 g of butter or 16 g of oil" for 200 g of flour. An option can also take a share of an earlier option of the same group: `@butter{100g}\|@oil{80% @&butter}`. | +| **Alternatives** | One option at a time | Each option in an alternative group computes independently (`@butter{10% @&flour}\|@oil{8% @&flour}` gives 20 g of butter or 16 g of oil for 200 g of flour). An option may also target an earlier option in the same group (`@butter{100g}\|@oil{80% @&butter}`). | ## Ratios with units -A percentage weighs grams against grams. A relates two amounts in any units, the way recipes state their rules: one egg per 100 g of flour, 15 g of salt per liter of water, 15 minutes per 500 g of roast. +While a percentage compares mass to mass, a relates two quantities in any compatible units—just as recipes state them: 1 egg per 100 g of flour, 15 g of salt per liter of water, or 15 minutes per 500 g of roast. ```gram Mix @flour{500 g} with @eggs{1 / 100 g @&flour}. // 5 eggs @@ -64,46 +64,31 @@ Pour @water{2 l} and @salt{15 g / 1 L @&water}. // 30 g of salt Crush @garlic{3 cloves} with @parsley{1 tsp / 2 cloves @&garlic}. // 1.5 tsp ``` -**Pattern:** `@name{ amount / target amount @&TargetIngredient }`, or `&TargetVariable` for an intermediate. The amount takes its unit (`15 g`) or none (`1` egg); the target amount is a number and a unit (`100 g`), a unit alone (`L`), or nothing for one piece (`{1 / @&cutlet}`). A range works as the amount (`{15-20 g / 100 g @&flour}`), never as the target amount. +**Pattern:** `@name{ amount / targetAmount @&TargetIngredient }` (or `&TargetVariable`). -Write a space on at least one side of the slash: `{1/100g @&flour}` reads as the fraction `1/100` and is refused with a message that shows the spaced form. Write the unit alone, too: in `{1 / 100 g of @&flour}` the unit is `g of`, which Gram refuses. +- `amount` takes its unit (`15 g`) or none for counts (`1` egg), and may be a range (`15-20 g`). +- `targetAmount` is a single number and unit (`100 g`), a unit alone (`L`), or omitted for one piece (`{1 / @&cutlet}`). +- **Always put a space around `/`** (at least on one side) and write the unit alone before the target: `{1/100g @&flour}` parses as the fraction `1/100`, and `{1 / 100 g of @&flour}` treats `g of` as the unit. -### The unit guardrail +### Unit compatibility -A ratio is computed only when its units can be compared, never guessed: +Gram only computes a ratio when its units can be compared safely—it never guesses: | Target amount | Target written in | Result | | :--- | :--- | :--- | -| A weight (`100 g`) | A weight (`1 kg`) | Computed by the compiler | -| A weight | A volume, or pieces | Computed with the density or the `unit_weight` of the ingredient database | -| Pieces (`2 cloves`, nothing) | The same pieces (`3 clove`, `4`) | Computed by the compiler: singular and plural match | -| Pieces | Other pieces (`2 slices` for garlic in cloves) | Refused | +| Weight (`100 g`) | Weight (`1 kg`) | Computed directly | +| Weight | Volume or count | Computed using density or `unit_weight` from the ingredient database | +| Count (`2 cloves`, or none) | Same count (`3 clove`, `4`) | Computed directly (singular/plural matched) | +| Count | Different count (`2 slices` for cloves) | Refused (`RELATIVE_QUANTITY_UNKNOWN_MASS`) | -A ratio that cannot be computed keeps its writing (`1 / 100 ml @&flour` in the views and the shopping list) and raises `RELATIVE_QUANTITY_UNKNOWN_MASS` with the reason. Unlike a percentage, a computed ratio keeps the unit of its amount: `5` eggs, `15 g` of salt, merged with the other uses of the ingredient in the shopping list. +If a ratio cannot be resolved, it remains as written in views and shopping lists and raises `RELATIVE_QUANTITY_UNKNOWN_MASS`. Unlike percentages, a resolved ratio keeps the unit of its own `amount` (e.g. `5` eggs, `15 g` of salt) and merges normally in the shopping list. -### Where the target is +### Scope, intermediates & scaling -The same rules as a percentage: an `@&ingredient` written earlier in the section with an amount (every amount in the section adds up), or an `&intermediate`. An option of an alternative may take an earlier option as its target. When the section uses an intermediate whole, with no amount (`Roll out the &dough`), the ratio counts from the mass of the section that makes it, an estimate of what went into the bowl, before cooking. Gram refuses when another section uses the intermediate too, since it cannot tell who takes what: - -```gram -## Dough ->&dough - -Mix @flour{500 g} and @water{60% @&flour}. - -## Bake - -Roll out the &dough, sprinkle @salt{2 g / 100 g &dough}. // 16 g of 800 g -``` - -This applies to a percentage as well (`@sugar{5% &dough}`), which used to give up there. - -### On references and composites - -A reference to a homemade preparation takes a ratio or a percentage too: `&stock{250 ml / 100 g @&rice}`, `&stock{250% @&rice}`. A composite parent does not yet (`<@box{1 / 100 g @&flour}>` is refused until composites are reworked). - -### Scaling - -Scaling a recipe computes its ratios again on the scaled amounts: twice the flour, twice the eggs. A ratio whose target is fixed (`@=pepper{2 g}`) stays as it is. `=` on a ratio itself is refused: a ratio always follows its target. +- **Same scope as percentages**: target an `@&ingredient` declared earlier in the section (repeated uses sum up), an earlier option in an alternative group, or an `&intermediate`. +- **Whole intermediates**: if a section consumes an intermediate without a quantity (`Roll out the &dough`), ratios and percentages (`@salt{2 g / 100 g &dough}`, `@sugar{5% &dough}`) resolve against the total mass of the section that produces it—provided only that section consumes it. +- **References & composites**: ratios and percentages work on homemade intermediate references (`&stock{250 ml / 100 g @&rice}`), but are not yet supported on composite parents (`@eggs{1}<@box{1 / 100 g @&flour}>`). +- **Scaling**: scaling a recipe recalculates ratios from the scaled targets (unless the target is fixed with `@=`). Marking a ratio itself with `=` is not allowed. ## Mass calculation rules diff --git a/packages/docs/src/content/docs/docs/reference/syntax/target-states.mdx b/packages/docs/src/content/docs/docs/reference/syntax/target-states.mdx index 89018379..d62702e6 100644 --- a/packages/docs/src/content/docs/docs/reference/syntax/target-states.mdx +++ b/packages/docs/src/content/docs/docs/reference/syntax/target-states.mdx @@ -9,7 +9,7 @@ import Term from '../../../../../components/Term.astro'; -A time says how long a step should take; it is rarely what tells the cook it is done. Custard is ready when it coats the spoon, egg yolks and sugar when they fall back in a ribbon, butter when it smells of hazelnut. A marks that cue with `={...}`: the state to reach, the one the cook has to recognize. +A timer tells you how long a step should take, not when it is truly done. Custard is ready when it coats the spoon, yolks when they fall in a ribbon, brown butter when it smells nutty. A marks that visual or sensory cue with `={...}`: ```gram Whisk @egg yolks{4} with @sugar{80 g} until ={ribbon stage}. @@ -19,50 +19,44 @@ As soon as the butter turns ={nutty brown}, take the #pan off the heat. The egg whites should be ={stiff} before you add the @sugar{50 g}. ``` -A target state goes wherever the sentence needs it. It is most often at the end of the step, since it usually marks what ends it, but it can also open the step or sit in the middle, and no phrase is required: "until", "as soon as", "when", or nothing at all. Write only the state between the braces and leave the other words in the sentence: the step still reads naturally, and the state stands out on its own in every view. +Place a target state wherever the sentence flows best—at the end, start, or middle of a step—with no required connecting word ("until", "when", or none at all). Put only the state itself inside the braces and keep surrounding words in the prose so the step reads naturally while the cue stands out in every view. ## How to check it -A note in parentheses, right after the closing brace, says how to tell that the state is reached: the test, the cue a beginner can trust. +Add a parenthetical note directly after the closing brace to explain how to verify the state—the practical test a cook can rely on: ```gram Cook on ^{low heat}, stirring, until ={it coats the spoon}(a finger drawn across the back of the spoon leaves a clean line) ->&custard{} ``` -The state and its note are always shown, on screen and on paper, and `gram cook` repeats them under the step. They are words for the cook, in the recipe's language: Gram keeps them as written and never reads them. +Both the state and its note are always displayed, on screen and in print, and `gram cook` highlights them beneath the step. Gram preserves them as written in your recipe's language without interpreting them. -As with ingredients, cookware, and temperatures, keep the opening `(` glued to the `}` on the same line: with a space (`={stiff peaks} (about 5 min)`), the parenthesis stays ordinary text in the sentence. +Just like ingredients, cookware, and temperatures, keep the opening `(` attached to `}` on the same line: with a space (`={stiff peaks} (about 5 min)`), the parentheses remain ordinary step text. ## With a time and a temperature -A step can carry a target state next to a timer and a temperature. The timer is the estimate, for the schedule; the state is what ends the step at the stove. +A step can combine a target state with a timer and a temperature. The timer estimates duration for the schedule; the state tells the cook when to stop at the stove. ```gram Cook at ^{82°C}(internal) for ~{8 min}, until ={it coats the spoon}. ``` :::tip[What does not go inside] -A target state is a state, never a measure: -- a temperature to reach is a [temperature](/docs/reference/syntax/temperatures/) with its note: `^{63°C}(internal)`; -- a time is a [timer](/docs/reference/syntax/times/): `~{5 min}`; -- a target state is never scaled: `={doubled in volume}` stays as written, whatever the number of servings. +A target state describes a sensory cue, never a measurement: +- use a [temperature](/docs/reference/syntax/temperatures/) with a note for target temperatures (`^{63°C}(internal)`); +- use a [timer](/docs/reference/syntax/times/) for durations (`~{5 min}`); +- target states never scale (`={doubled in volume}` stays unchanged regardless of servings). ::: ## Several in one step -A step can hold more than one. Each shows where it was written, `gram cook` lists them one under the other and, when a timer of the step rings, asks to check them all. +A step can contain multiple target states. Each renders inline in the prose, and `gram cook` lists them together—reminding you to check them when a step's timer finishes. ```gram Knead until the dough is ={smooth} and ={elastic}(it springs back slowly when stretched). ``` -As with timers and temperatures, a short step is easier to follow. When each state ends a different action, make two steps, each with its own state. Rather than: - -```gram -Melt the @butter{50 g} until ={nutty brown}, then let it cool until ={lukewarm} and stir in the @eggs{2}. -``` - -write: +As with timers and temperatures, shorter steps are easier to follow. If two states mark distinct actions, split them into separate steps rather than chaining them: ```gram Melt the @butter{50 g} until ={nutty brown}. @@ -72,13 +66,9 @@ Let it cool until ={lukewarm}, then stir in the @eggs{2}. ## Errors -A target state needs words between its braces, closed on the same line. `={}` and `={ribbon stage` (with no `}`) are syntax errors, shown in the editor where they start. +A target state must be non-empty and closed on the same line. `={}` or an unclosed `={ribbon stage` raises a syntax error pointing to the opening marker. -An `=` that does not touch a brace is ordinary text, and the fixed-quantity modifier `@=salt{1 tsp}` is unchanged. - -## In the compiled recipe - -Each target state is a `checkpoint` token in the step's `content`, where it was written: `{ "type": "checkpoint", "state": "ribbon stage", "note": "…" }`, `note` only when there is one. See [Data formats](/docs/reference/api/data-formats/). +A standalone `=` not followed by `{` stays ordinary text, and fixed ingredient modifiers (`@=salt{1 tsp}`) are unaffected. ## Related resources @@ -98,4 +88,9 @@ Each target state is a `checkpoint` token in the step's `content`, where it was description="Quick visual reference for every marker." href="/docs/reference/syntax/cheatsheet/" /> + 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 efc63211..d2241a6b 100644 --- a/packages/docs/src/content/docs/docs/reference/syntax/temperatures.mdx +++ b/packages/docs/src/content/docs/docs/reference/syntax/temperatures.mdx @@ -50,7 +50,7 @@ When the Gram compiler inspects a `^temperature` token: ## 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. +Add a parenthetical note right after the closing brace to specify the oven mode, measurement point, or cooking condition. This works on both exact and semantic temperatures, named or unnamed, just like ingredient preparation notes: ```gram Preheat the #oven to ^{160°C}(fan). @@ -60,9 +60,9 @@ 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. +The note is always shown next to the temperature on screen and in print, and is preserved as written in your recipe's language without being parsed. -As with ingredients and cookware, keep the opening `(` glued to the `}` on the same line: with a space (`^{180°C} (preheated)`), the parenthesis stays ordinary text in the sentence. +As with ingredients and cookware, keep the opening `(` attached to `}` on the same line: with a space (`^{180°C} (preheated)`), the parentheses remain ordinary step text. ## Error handling diff --git a/packages/docs/src/content/docs/docs/reference/syntax/times.mdx b/packages/docs/src/content/docs/docs/reference/syntax/times.mdx index 90a67e86..7e06b417 100644 --- a/packages/docs/src/content/docs/docs/reference/syntax/times.mdx +++ b/packages/docs/src/content/docs/docs/reference/syntax/times.mdx @@ -13,7 +13,7 @@ You can define `~timer` declarations and durations in your recipes using the `~` ## Basic declaration -A `~timer` **must** state its unit inside the braces. Words are not durations: `~{about 10 minutes}` or `~{half an hour}` are not read, and the compiler warns about them. +A `~timer` **must** state its unit inside the braces. Free-text durations like `~{about 10 minutes}` or `~{half an hour}` are not supported and trigger a compiler warning. ```gram Bake for ~{25min}. @@ -29,14 +29,14 @@ Bake for ~{25min}. Shorthand `m` or the word `minutes` are automatically normalized to `min` by the compiler. ::: -These units are resolved through Gram's multi-language time dictionary: localized aliases below are recognized natively regardless of the recipe language (e.g. in a French recipe, `~{2j}` resolves identically to `~{2d}`, and `~{1 hr}` reads in any recipe). +These units resolve through Gram's multi-language time dictionary, so localized aliases work regardless of the recipe language (`~{2j}` equals `~{2d}`, and `~{1 hr}` works anywhere). ## Writing a duration -Write a duration the way a recipe does, in American or British English, in French or in international notation. Spaces carry no meaning: `~{1h30}`, `~{1 h 30}`, `~{1hr 30}` and `~{1 hr. 30 mins}` all read as 1 hour 30 minutes. +Write durations the way recipes naturally do—spaces don't matter (`~{1h30}`, `~{1 h 30}`, `~{1 hr 30 mins}` all mean 1 h 30 min), and every view formats them consistently in the reader's language. ```gram Simmer the @stock{2 l} for ~{1h30}. @@ -46,66 +46,24 @@ Let the @dough{} rise ~_{1 hr 30 mins}. Age the @ham{1} in the cellar ~_{2d 4h}. ``` -Whatever the writing, the views display every duration the same way, in the reader's language (`1 h 30 min`), and hovering a timer in your editor shows how Gram read it. - -### Several units - -A duration can chain several units, optionally joined by `+`: `~{1h30min}`, `~{1 h 30 min}`, `~{2 d 4 h}`, `~{1h + 30min}`. - -- Units go **from the largest to the smallest**, each one once: `~{30min 1h}` and `~{1h 2h}` are not read. -- A **last number without a unit** is allowed right after hours (it counts minutes) or minutes (it counts seconds), when it is a whole number under 60: `~{1h30}`, `~{2min30}`. `~{1h75}` is not read: write `~{2h15}`. -- **Decimals and fractions** only work in a duration of a single unit: `~{1.5 h}`, `~{1½ h}`, `~{1 1/2 hours}`. `~{1.5h30}` is not read. - -### Clock notation - -A clock with three parts always reads: `~{1:30:00}` is 1 hour 30 minutes, `~{0:04:30}` is 4 minutes 30 seconds. With two parts, a unit says what the first part is: `~{1:30 h}` is 1 hour 30 minutes, `~{4:30 min}` is 4 minutes 30 seconds. - -```gram -Steam the @pudding{1} for ~_{1:30 h}. -``` - -`~{1:30}` alone is not read: it could be 1 hour 30 or 1 minute 30. Write `~{1h30}` or `~{1:30 min}`. After the first part, each part has two digits and stays under 60. - -### Prime notation - -Common in Italian and French recipes, `'` counts minutes and `"` seconds: `~{5'}`, `~{5'30"}`, `~{45"}`, `~{90'}`. A last number without a prime counts seconds (`~{5'30}`). Primes only count minutes and seconds, in whole numbers. - -```gram -Cook the @spaghetti{500g} for ~{9'}, then toss for ~{1'30"}. -``` - -The typographic variants read too: the curly apostrophe `’` that word processors put in place of `'`, the primes `′` and `″`, and two apostrophes `''` for seconds. - -### Decimal numbers - -A duration can be a decimal, with a point or a comma (`~{1.5 h}`, `~{1,5 h}`; see [decimal numbers](/docs/reference/syntax/ingredients/#decimal-numbers)). +- **Compound units** (`~{1h30min}`, `~{2 d 4 h}`, `~{1h + 30min}`): list units from largest to smallest, each once. A trailing number without a unit is allowed right after hours (minutes) or minutes (seconds) if it is a whole number under 60 (`~{1h30}`, `~{2min30}`, not `~{1h75}`). Decimals and fractions only apply to single-unit durations (`~{1.5 h}`, `~{1½ h}`, not `~{1.5h30}`). +- **Clock notation** (`~{1:30:00}`, `~{1:30 h}`, `~{4:30 min}`): three parts always work (`hh:mm:ss`); two parts require a leading unit so `1:30` isn't ambiguous between hours and minutes. +- **Prime notation** (`~{5'}`, `~{5'30"}`, `~{45"}`): `'` counts whole minutes and `"` counts whole seconds (typographic quotes `’`, `′`, `″`, and `''` also work). +- **Decimals** (`~{1.5 h}`, `~{1,5 h}`): periods and commas both work (see [decimal numbers](/docs/reference/syntax/ingredients/#decimal-numbers)). :::caution -A decimal is a fraction of the unit, not minutes: `~{1.30 h}` (or `~{1,30 h}`) is 1 hour 18 minutes, not 1 hour 30. Write `~{1h30}` or `~{1.5 h}` for an hour and a half. +A decimal is a fraction of the unit, not minutes: `~{1.30 h}` is 1 h 18 min, not 1 h 30 min. Write `~{1h30}` or `~{1.5 h}` for an hour and a half. ::: -### What Gram reads, at a glance - -| Written | Read as | -| :--- | :--- | -| `~{90min}`, `~{1.5 h}`, `~{1,5 h}`, `~{1½ h}`, `~{1 1/2 hours}` | 1 h 30 min | -| `~{1h30}`, `~{1 h 30}`, `~{1hr 30}`, `~{1 hr 30 mins}`, `~{1 hour 30 minutes}`, `~{1h30m}` | 1 h 30 min | -| `~{1 heure 30}`, `~{1h + 30min}`, `~{1:30 h}`, `~{1:30:00}` | 1 h 30 min | -| `~{4min30}`, `~{4:30 min}`, `~{4'30"}`, `~{0:04:30}` | 4 min 30 s | -| `~{2 d 4 h}`, `~{2 j 4 h}` | 2 days 4 hours | -| `~{45 min - 1 h}`, `~{1h30-2h}`, `~{5-7'}` | a range (see below) | - -| Not read | Why | Write instead | +| Accepted | Rejected | Use instead | | :--- | :--- | :--- | -| `~{1:30}` | hours or minutes? | `~{1h30}` or `~{1:30 min}` | -| `~{1h75}` | 60 minutes or more after the hours | `~{2h15}` | -| `~{30min 1h}` | units from the smallest to the largest | `~{1h30}` | -| `~{1.5h30}` | a decimal in a duration of several units | `~{1h30}` or `~{1.5 h}` | -| `~{half an hour}`, `~{2 to 3 hours}` | words | `~{30min}`, `~{2-3h}` | -| `~{2 * 2 min}` | a multiplication | the total, `~{4min}` | -| `~{PT1H30M}` | ISO 8601, a notation for machines | `~{1h30}` | +| `~{1h30}`, `~{1 hr 30}`, `~{1h + 30min}` | `~{1:30}` *(ambiguous)* | `~{1h30}` or `~{1:30 min}` | +| `~{1:30 h}`, `~{1:30:00}` | `~{1h75}` *(≥ 60 min)* | `~{2h15}` | +| `~{4'30"}`, `~{4min30}` | `~{30min 1h}` *(wrong order)* | `~{1h30}` | +| `~{1.5 h}`, `~{1,5 h}`, `~{1½ h}` | `~{1.5h30}` *(decimal in compound)* | `~{1h30}` or `~{1.5 h}` | +| `~{45 min - 1 h}`, `~{1h30-2h}` | `~{half an hour}` *(words)* | `~{30min}` | -A duration Gram does not read raises a [warning](#error-handling) with a suggestion, and is not counted in the total time: Gram never guesses. +Unrecognized durations raise an `INVALID_DURATION` warning with a suggested fix and are excluded from total times. ### Timer names You can assign an explicit name to a `~timer`. This is especially useful for passive background tasks: when multiple timers run concurrently (like a dough fermenting while a stock simmers), named timers allow user interfaces and production run sheets to track each process simultaneously without confusion. @@ -125,7 +83,7 @@ Let the dough rest in the fridge ~_{12-24h}. Roast the chicken for ~{40-50min}. ``` -Each side of a range follows the rules above, and the shorter duration comes first. The left side takes the unit of the right side only when it is a bare number and the right side has a single unit: `~{1-2 h}`, `~{5-7'}`, `~{1.5-2 h}` (and two clocks before a unit: `~{1:30-2:00 h}`). Otherwise, write both sides in full (since 1.5.0): +Each side of a range follows the rules above, with the shorter duration first. You can omit the unit on the left only when it is a bare number and the right side has a single unit (`~{1-2 h}`, `~{5-7'}`, `~{1:30-2:00 h}`). For compound or mixed-unit bounds, write both sides in full (): ```gram Braise the @beef cheeks{1 kg} ~_{2h30-3h}. @@ -133,7 +91,7 @@ Braise the @beef cheeks{1 kg} ~_{2h30-3h}. Poach the @pears{4} for ~{45 min - 1 h}. ``` -`~{1-2h30}` is not read (is the left side 1 hour or 1 hour 30?): write `~{1h-2h30}`. Neither is `~{2-1 h}`: write `~{1-2 h}`. +Ambiguous or reversed ranges like `~{1-2h30}` or `~{2-1 h}` are rejected—write `~{1h-2h30}` or `~{1-2 h}` instead. The interpretation of a range differs fundamentally based on timer type: @@ -148,7 +106,7 @@ Deprecated fields of the compiled recipe (`steps[].timings`, `steps[].background ### Proportional times -Some times follow a weight: 15 minutes per 500 g of roast, 4 minutes per cutlet. Write the duration, a slash, then the amount of an ingredient written earlier in the section, as in a [ratio with units](/docs/reference/syntax/relative-quantities/#ratios-with-units): +Some cooking times scale with weight or count—such as 15 minutes per 500 g of roast, or 4 minutes per cutlet. Write the duration, a slash, and the reference amount of an ingredient declared earlier in the section, following the same syntax as a [ratio with units](/docs/reference/syntax/relative-quantities/#ratios-with-units): ```gram Season the @roast{1.2 kg} and roast ~{15 min / 500 g @&roast}. // 36 min @@ -158,7 +116,10 @@ Braise the @shoulder{2 kg} ~_{1:30 h / 1 kg @&shoulder}. // 3 h Fry the @cutlets{4} ~{4 min / @&cutlets}. // 16 min ``` -The duration takes every form above (`1h30`, `1:30 h`, a range such as `15-20 min`), the target amount a single number. A time per piece counted from a weight (`~{4 min / @&cutlets}` with `@cutlets{800 g}`) uses the `unit_weight` of the ingredient database, and stays uncounted, with a warning, when there is none. Scaling the recipe computes the time again, and the schedule with it. A multiplier after a proportional time (`~{15 min / 500 g @&roast * 2}`) is not read yet, nor is a proportional section anchor. +- The duration accepts any standard format (`1h30`, `1:30 h`, or a range like `15-20 min`), while the target amount must be a single number. +- A time per piece applied to a weight (`~{4 min / @&cutlets}` with `@cutlets{800 g}`) relies on `unit_weight` in your ingredient database; if missing, the timer stays uncomputed with a warning. +- Scaling the recipe recalculates proportional times and updates the schedule automatically. +- Multipliers (`~{15 min / 500 g @&roast * 2}`) and proportional section anchors are not supported yet. ## Active vs passive @@ -284,8 +245,8 @@ Working days are designed to fit within a 24-hour span: if a long passive durati Section header retro-planning annotations require a **strictly negative** duration: - A **required** leading `-` sign. -- A non-zero duration, written like a timer (see [Writing a duration](#writing-a-duration)) in days, hours and minutes (compound and clock forms since 1.5.0). -- A single duration: an anchor is never a range, and never counts seconds. +- A non-zero duration in days, hours, or minutes (including compound and clock forms since 1.5.0; see [Writing a duration](#writing-a-duration)). +- A single duration—anchors cannot be ranges or include seconds. ```gram ## Puff pastry ~{-2d} @@ -299,15 +260,9 @@ Knead the @flour{500g}. ## Ganache ~{-1h30} Pour the @cream{200ml} over the @chocolate{200g}. - -## Custard ~{-1:30 h} - -Whisk the @yolks{4} with the @sugar{80g}. ``` -An anchor written with days stays in days (`~{-1d 12h}` is a day and a half, and opens a working day); otherwise it counts in its smallest unit (`~{-1h30}` is 90 minutes, `~{-1:30 h}` too). - -Free prose (`~{the day before}`), positive values (`~{2h}`), and zero values (`~{0h}`) are invalid. Existing recipes using legacy formats still compile for backward compatibility, but produce compiler warnings. +Free prose (`~{the day before}`), positive values (`~{2h}`), and zero values (`~{0h}`) are invalid and trigger compiler warnings. Units resolve through the multi-language time dictionary used by `~timer`: `j`, `jour`, and `jours` are recognized aliases for `d`. @@ -321,8 +276,8 @@ The compiler validates `~timer` declarations and section retro-planning annotati - **Invalid Unit** (`~timer`): Unrecognized units (e.g. `~{30 lightyears}`) trigger `INVALID_UNIT`. - **Missing Unit** (section retro-planning): `~{-2}`, free text, positive (`~{2h}`), or zero values (`~{0h}`) trigger `MISSING_UNIT`. - **Invalid Unit** (section retro-planning): Unrecognized units trigger `INVALID_UNIT`. -- **Invalid Duration** *(Since 1.5.0)*: A duration in a shape Gram does not read (`~{1:30}`, `~{1h75}`, `~{30min 1h}`, `~{1-2h30}`, `~{half an hour}`, or a range or seconds in an anchor) triggers `INVALID_DURATION`. The message says why and how to write it; the timer is not counted in the total time, and the section is not anchored. See [Writing a duration](#writing-a-duration). -- **Ambiguous Number** *(Since 1.5.0)*: A comma followed by exactly three digits (`~{1,000 min}`, `~{-1,000h}`) is read as a decimal, one minute or one hour, and triggers `AMBIGUOUS_NUMBER` in case a thousand was meant. +- **Invalid Duration** *(Since 1.5.0)*: Unrecognized or ambiguous duration formats (`~{1:30}`, `~{1h75}`, `~{30min 1h}`, `~{1-2h30}`, `~{half an hour}`, or ranges/seconds in anchors) trigger `INVALID_DURATION` with a suggested fix; the timer is excluded from total time and the anchor is ignored. +- **Ambiguous Number** *(Since 1.5.0)*: A comma followed by three digits (`~{1,000 min}`, `~{-1,000h}`) is parsed as a decimal (`1`) and triggers `AMBIGUOUS_NUMBER`. - **Time Paradox**: Anchors conflicting with dependency order (e.g. an ingredient anchored at `-10 min` needed by a section anchored at `-1 h`) trigger `TIME_PARADOX`. - **Track Contention**: Concurrent passive timers delayed on the same named track trigger `TRACK_CONTENTION`. - **Day overflow** *(Since 1.4.0)*: Passive durations pushing working day tasks beyond the 24-hour window trigger `DAY_OVERFLOW`. diff --git a/packages/docs/src/content/docs/docs/reference/tooling/cli.mdx b/packages/docs/src/content/docs/docs/reference/tooling/cli.mdx index 19f39048..d3e7bbc0 100644 --- a/packages/docs/src/content/docs/docs/reference/tooling/cli.mdx +++ b/packages/docs/src/content/docs/docs/reference/tooling/cli.mdx @@ -112,7 +112,7 @@ gram view brioche.gram --scale flour=300g # Scaled to flour = 300g ``` - Supports automatic paging for long recipes. - Displays calculated nutrition, timings, and ingredient checklists. -- Timers and the durations of the header are written the same way as in every view (`~{1h5}` displays as `1 h 5 min`, `~{25min 5s}` as `25 min 5 s`); a timer Gram does not read is shown as written. +- Timers and header durations use the same formatting as every other view (`~{1h5}` renders as `1 h 5 min`, `~{25min 5s}` as `25 min 5 s`); unrecognized timers remain as written. - Steps are numbered in each section, as in every view of the recipe. Quantities are repeated in the text of the steps, next to each ingredient (`flour (200 g)`); `--step-quantities hide` leaves them out. - Passive waiting time appears in the recipe header, and common fractions such as `1/4 tsp` remain fractions in the shopping list. - Passing `--scale` adjusts all ingredient quantities (both in the shopping list and in-step references). @@ -176,12 +176,12 @@ gram shop "menus/*.gram" --scale 4 # Batch cooking × 4 - When a glob or multiple files are provided, files imported (via `@use`) by other recipes in the batch are excluded by default to avoid duplicate shopping list entries. Pass `--include-modules` to include them. - Options: `--format terminal|md|json`, `--output/-o `, `--scale `, `--db`, `--skip-db`, `--include-modules`, and the analyzer's [settings flags](#settings-flags). -With `--format json`, each item keeps `qty`, the amount as a reader sees it (`2 cup + 3 tbsp`, `3,9 kg`), and also gives it as numbers, for a script to read : -- `amount` is a plain number, in the unit `qty` shows (`3.9` with `"unit": "kg"`), never written with a decimal comma. `null` when the ingredient has no number, or when its units do not add up. -- `unit` is the canonical unit (`tbsp` for `tablespoons` or `c. à s.`), `null` for a count (`@eggs{4}`). Cups and spoons add up in the smallest unit written: `2 cup + 3 tbsp` gives `"amount": 35, "unit": "tbsp"`. -- `range` gives the bounds of a range (`{ "min": 13, "max": 14 }`); `amount` is then its middle. -- `parts` lists the amounts whose units do not add up, as `qty` writes them (`1 1/2 cups + 70 g` gives `[{ "amount": 1.5, "unit": "cup" }, { "amount": 70, "unit": "g" }]`). -- `unresolved` lists what could not be turned into a number (`(2% of dough ❓)`): it is never counted in `amount`. +With `--format json`, each item keeps the human-readable `qty` string (`2 cup + 3 tbsp`, `3,9 kg`) alongside structured numeric fields for scripts : +- `amount`: plain number in the unit shown by `qty` (`3.9` for `"unit": "kg"`), always using a dot decimal; `null` if the ingredient has no quantity or mixes incompatible units. +- `unit`: canonical unit (`tbsp` for `tablespoons` or `c. à s.`), or `null` for counts (`@eggs{4}`). Compatible scales add up in the smallest unit written (`2 cup + 3 tbsp` gives `"amount": 35, "unit": "tbsp"`). +- `range`: `{ min, max }` bounds when the item is a range (`amount` holds the midpoint). +- `parts`: array of `{ amount, unit }` entries when incompatible units cannot be summed (`1 1/2 cups + 70 g` gives `[{ "amount": 1.5, "unit": "cup" }, { "amount": 70, "unit": "g" }]`). +- `unresolved`: unresolvable portions such as `(2% of dough ❓)`, excluded from `amount`. ```json { "id": "salt", "name": "salt", "qty": "3 g + (2% of dough ❓)", "amount": 3, "unit": "g", "unresolved": ["(2% of dough ❓)"], "isEstimate": false, "category": "Spices", "recipes": ["brioche"] } diff --git a/packages/docs/src/content/docs/docs/reference/tooling/language-server.mdx b/packages/docs/src/content/docs/docs/reference/tooling/language-server.mdx index 7f8d9b65..347493f2 100644 --- a/packages/docs/src/content/docs/docs/reference/tooling/language-server.mdx +++ b/packages/docs/src/content/docs/docs/reference/tooling/language-server.mdx @@ -31,26 +31,24 @@ The Gram Language Server implements the following standard capabilities: | LSP Capability | Gram Implementation | |---|---| | **Diagnostics** | Real-time reporting of syntax errors, structural defects (circular dependencies), and scheduling warnings (`DAY_OVERFLOW`, `DURATION_OUT_OF_RANGE`, `TRACK_CONTENTION`). | -| **Semantic Tokens** | AST-driven highlighting for modifiers, units, temperatures, and composite ingredients. | -| **Completion** | Contextual autocomplete for database ingredients, canonical units, and intermediate variables. Inside a timer (`~{…}`), only time units are offered. In a sum of quantities, units are offered again after each `+ 2` or `- 2`. | -| **Hover** | Displays nutritional breakdowns and real-time volume-to-mass conversions on ingredient hover. On a timer, shows the duration as Gram reads it (`~{1h30}` → `1 h 30 min`); on a section anchor, how long ahead the section starts and whether it opens a working day. On a sum of quantities, shows its total and its mass. | -| **Go to Definition** | Direct navigation from an intermediate reference (`&ref`) to its original declaration (`->&ref`). | -| **Find References** | Locates every usage of a specific intermediate variable across the document. | -| **Rename** | Safely and atomically renames intermediate variables throughout the file. | -| **Code Actions** | Quick fixes (declaring missing intermediate variables, converting volume to mass, mending a sum of quantities). | -| **Document Formatting** | Normalizes syntax in-place applying the 13 canonical formatting rules via `@gram-lang/format`. | -| **Inlay Hints** | Displays the recipe's total time at the end of the `title:` line, following mise en place placement and passive timer resolution (the `gram.miseEnPlace` and `gram.rests` settings). | +| **Semantic Tokens** | AST-driven highlighting for modifiers, units, temperatures, ratio operators (`/`), and composite ingredients. | +| **Completion** | Contextual autocomplete for database ingredients, canonical units, and intermediate variables. Offers time units inside `~{…}`, resumes unit completion after `+` or `-` in sums, and suggests `@&` / `&` targets (plus weight units after `/`) in ratios. | +| **Hover** | Displays nutritional breakdowns and volume-to-mass conversions on ingredient hover. On timers, shows the parsed duration (`~{1h30}` → `1 h 30 min`); on section anchors, the lead time and whether it opens a working day; on sums and ratios, the resolved total, mass, or reason if unresolved. | +| **Go to Definition** | Direct navigation from an intermediate reference (`&ref`, including inside ratios) to its original declaration (`->&ref`). | +| **Find References** | Locates every usage of an intermediate variable across the document (including inside ratios). | +| **Rename** | Safely and atomically renames intermediate variables throughout the file (including inside ratios). | +| **Code Actions** | Quick fixes (declaring missing intermediate variables, converting volume to mass, fixing sums of quantities). | +| **Document Formatting** | Normalizes syntax in-place via `@gram-lang/format`. | +| **Inlay Hints** | Displays the recipe's total time on the `title:` line (following `gram.miseEnPlace` and `gram.rests`), and shows resolved values (`= 5`, `= 24 min`) inline after unit ratios and proportional times. | | **Code Lens** | Injects interactive action buttons above the document (such as nutrition calculation). | | **Document Symbol** | Populates the editor's Outline view for clean structural navigation across recipe sections. | | **Folding Range** | Enables folding of YAML frontmatter blocks and `##` section headings. | -### Sums of quantities +### Sums of quantities and ratios + - On a [sum of quantities](/docs/reference/syntax/ingredients/#sums-of-quantities), the editor helps in three ways: - -- **Hover** shows the total as Gram reads it (`{1 cup + 1 tbsp}` → `= 17 tbsp`; a sum of several kinds shows what each comes to, `{1 cup - 2 tbsp + 30 g}` → `= 14 tbsp (volume) + 30 g (weight), counted apart`) and, when the ingredient database can weigh every term, its mass. A sum Gram refuses shows nothing more than its warning. -- **Quick Fixes** read the warning's `data`, passed on as the diagnostic's `data`: insert the ` + ` between two quantities written side by side (`{1 cup 5 tbsp}`, `INVALID_UNIT`), write the result Gram suggests (`{100 g + 10%}` → `{110 g}`, `INVALID_QUANTITY`), or turn `oz` after a volume into `fl oz` (`OZ_AFTER_VOLUME`). -- **Completion** offers units for each term: after `{1 cup + 2`, the units come back. +- **Sums of quantities**: hover previews the combined total (`{1 cup + 1 tbsp}` → `= 17 tbsp`) or per-family breakdown plus standardized mass; quick fixes insert missing ` + ` operators (`{1 cup 5 tbsp}`), apply suggested totals (`{100 g + 10%}`), or change `oz` after a volume to `fl oz`; unit completion resumes after `+` or `-`. +- **Unit ratios & proportional times**: inlay hints display resolved values inline (`= 5`, `= 16 g`, `= 24 min`); hover explains unresolved ratios; completion offers `@&`/`&` targets (and weight units after `/` in proportional timers); Go to Definition, Find References, and Rename include targets inside ratios. ## Settings diff --git a/packages/docs/src/content/docs/docs/reference/tooling/vscode-extension.mdx b/packages/docs/src/content/docs/docs/reference/tooling/vscode-extension.mdx index c42476d2..395cd5d7 100644 --- a/packages/docs/src/content/docs/docs/reference/tooling/vscode-extension.mdx +++ b/packages/docs/src/content/docs/docs/reference/tooling/vscode-extension.mdx @@ -85,18 +85,19 @@ A working day pushed beyond 24 hours by a prolonged passive phase triggers an ex ### 4. Smart ingredient management - **Silent plural management**: The extension automatically maps common plural nouns in your recipe (e.g. `@carrots`) to singular entries in your YAML database (`carrot`), maintaining natural language without raising false errors. - **Fuzzy matching**: If you misspell an ingredient, a Levenshtein distance algorithm suggests the closest known match via Code Actions (Quick Fixes). -- **Hover insights**: Hover over any ingredient to inspect its full nutritional profile. If the database specifies a density, the hover display instantly converts volume measurements to physical mass (e.g. `1 tbsp → 15g`). Hover a timer to see how Gram reads it (`~{1:30 h}` → `1 h 30 min`), or a section anchor to see how long ahead the section starts. +- **Hover insights**: Hover over any ingredient to inspect its nutritional profile and automatic volume-to-mass conversions (`1 tbsp → 15g`). Hover over a timer to see the parsed duration (`~{1:30 h}` → `1 h 30 min`), over a section anchor to see its lead time, or over a sum/ratio to inspect its resolved value. :::tip[Automatic database discovery] The extension automatically detects the `.gram/ingredients.yaml` file located at the workspace root. For custom folder layouts, specify `gram.ingredientDatabase.path` in your VS Code settings. ::: ### 5. Editing assistance & navigation -- **Semantic tokens**: Highlighting is driven directly by the compiler AST rather than regular expressions. Modifiers, nested units, and composite ingredients (`<@`) are colored accurately according to their syntactic role. +- **Semantic tokens**: Highlighting is driven directly by the compiler AST rather than regular expressions. Modifiers, nested units, ratio operators, and composite ingredients (`<@`) are colored accurately according to their syntactic role. +- **Inlay hints**: Shows total recipe duration next to `title:` and resolved values inline after unit ratios and proportional times (`= 5`, `= 24 min`). - **Intelligent autocomplete**: - `@` suggests ingredients declared in your database, automatically enclosing multi-word names in `{}` brackets. - `&` suggests available intermediate declarations (e.g. `->&dough`). - - `{}` contextually suggests canonical units (mass, volume) and their aliases as soon as a digit is typed; inside a timer (`~{}`), only time units. + - `{}` contextually suggests canonical units (mass, volume) and their aliases as soon as a digit is typed; inside a timer (`~{}`), only time units are offered. #### Navigation shortcuts diff --git a/packages/docs/src/content/docs/fr/docs/explanation/mass-and-yield.mdx b/packages/docs/src/content/docs/fr/docs/explanation/mass-and-yield.mdx index 0ea9d489..9f47ec08 100644 --- a/packages/docs/src/content/docs/fr/docs/explanation/mass-and-yield.mdx +++ b/packages/docs/src/content/docs/fr/docs/explanation/mass-and-yield.mdx @@ -42,9 +42,9 @@ Lorsque l'Analyseur rencontre un ingrédient, il le passe par un algorithme de p ### Peser une somme de quantités -Une [somme de quantités](/fr/docs/reference/syntax/ingredients/#sommes-de-quantités) se pèse nature par nature. Les termes d'une même nature sont d'abord additionnés, puis convertis selon l'algorithme ci-dessus : `@sucre{1 tasse - 2 càs}` pèse exactement le poids de la quantité totale, et `@beurre{1 tasse + 30 g}` ajoute le poids d'une tasse (via la densité) à 30 g. Le rendement s'applique lui aussi nature par nature, puisqu'un poids unitaire est une masse brute alors que les grammes écrits dans la recette sont nets. +Une [somme de quantités](/fr/docs/reference/syntax/ingredients/#sommes-de-quantités) se pèse par famille d'unités. Les termes d'une même famille sont d'abord additionnés, puis convertis selon l'ordre de priorité ci-dessus : `@sucre{1 tasse - 2 càs}` pèse le même poids que `@sucre{14 càs}`, tandis que `@beurre{1 tasse + 30 g}` additionne la masse convertie de la tasse et les 30 g. Le rendement s'applique lui aussi par famille, car un `unit_weight` représente une masse brute tandis que les grammes de la recette sont nets. -Si une des natures ne peut pas être pesée (`@riz{1 tasse + 20 g}` sans densité pour le riz), la somme entière n'a **aucune** masse plutôt qu'une masse partielle : la liste de courses fusionne les entrées par la masse, et une masse partielle vous ferait acheter 20 g de riz en oubliant la tasse. Les grammes comptent quand même là où ils s'achètent, dans leur propre entrée de la liste de courses. Une somme refusée par Gram (`INVALID_QUANTITY`) ne compte pas dans la nutrition, comme une quantité absente. +Si l'une des familles ne peut pas être pesée (`@riz{1 tasse + 20 g}` sans densité connue pour le riz), la somme ne reçoit **aucune** masse plutôt qu'une masse partielle — sans quoi la fusion de la liste de courses risquerait de ne retenir que les 20 g en oubliant la tasse. Le terme en grammes reste néanmoins comptabilisé dans sa propre entrée de liste de courses, tandis qu'une somme invalide (`INVALID_QUANTITY`) est exclue de la nutrition. ## Calcul du rendement (le facteur de déchet) diff --git a/packages/docs/src/content/docs/fr/docs/explanation/scaling.mdx b/packages/docs/src/content/docs/fr/docs/explanation/scaling.mdx index bacf6d6e..ed7fa358 100644 --- a/packages/docs/src/content/docs/fr/docs/explanation/scaling.mdx +++ b/packages/docs/src/content/docs/fr/docs/explanation/scaling.mdx @@ -58,7 +58,7 @@ function resolveScaleFactor( ## Mettre à l'échelle une somme de quantités -Une [somme de quantités](/fr/docs/reference/syntax/ingredients/#sommes-de-quantités) se met à l'échelle terme par terme : `applyScale` multiplie chacun de ses `parts`, puis recalcule le total. L'affichage revient au renderer, qui suit une règle simple : une recette à l'échelle d'origine montre chaque somme telle qu'écrite ; une fois mise à l'échelle, une quantité s'écrit comme on la mesure en cuisine. +Une [somme de quantités](/fr/docs/reference/syntax/ingredients/#sommes-de-quantités) se met à l'échelle terme par terme : `applyScale` multiplie chacun de ses `parts`, puis recalcule le total. Le moteur de rendu conserve les sommes telles qu'écrites sans mise à l'échelle, puis les reformule en mesures pratiques une fois ajustées : | Écrit | Échelle | Affiché | | :--- | :--- | :--- | @@ -71,19 +71,19 @@ Une [somme de quantités](/fr/docs/reference/syntax/ingredients/#sommes-de-quant | `{1 lb + 4 oz}` | × 1,5 | `1 1/2 lb + 6 oz` | | `{1 cup + 50 ml}` | × 2 | `2 cup + 100 ml` | -- **Les unités métriques restent dans la plus grande unité écrite**, en décimal : on pèse en grammes, donc `{800 g + 200 g}` se lit `1000 g`. Seule la liste de courses passe à l'unité dans laquelle on achète (`1500 g` → `1,5 kg`). -- **Les unités américaines et impériales sont recomposées** seulement au besoin, en fractions que possèdent vraiment les tasses et cuillères doseuses (¼, ⅓, ½, ⅔, ¾ de tasse ; ½ tbsp ; ⅛, ¼, ½ tsp…), jamais au-dessus de la plus grande unité écrite, cuillères (`cup → tbsp → tsp`) et mesures liquides (`gal → qt → pt → fl oz`) chacune de leur côté. Des termes déjà mesurables tels quels restent comme ils sont. -- **Une fourchette** garde la partie commune à ses deux bornes, et l'écart porte sur le dernier terme. -- **Deux systèmes** (`cup` et `ml`) restent terme par terme. +- **Unités métriques** : elles restent exprimées en décimales dans la plus grande unité écrite (`{800 g + 200 g}` donne `1000 g`, pas `1 kg`) ; seule la liste de courses convertit vers l'unité d'achat (`1500 g` → `1,5 kg`). +- **Unités américaines et impériales** : elles ne sont recomposées qu'au besoin en fractions usuelles de tasses et cuillères doseuses (`¼`, `⅓`, `½`, `⅔`, `¾` de tasse ; `½` tbsp ; `⅛`, `¼`, `½` tsp…), sans dépasser la plus grande unité écrite et en gardant cuillères (`cup → tbsp → tsp`) et mesures liquides (`gal → qt → pt → fl oz`) séparées. +- **Fourchettes** : la partie commune aux deux bornes est factorisée et l'écart reste sur le dernier terme. +- **Systèmes mixtes** (`cup` et `ml`) : chaque terme reste à sa place. -**Le scaling inversé sur une somme** (`--scale farine=500g`) s'appuie sur son total quand tous les termes sont de même nature ; un volume à côté d'une masse laisse deux entrées dans la liste de courses, ce qui déclenche `AMBIGUOUS_MULTI_UNIT`, comme deux mentions séparées. +**L'ajustement par ingrédient repère sur une somme** (`--scale farine=500g`) s'appuie sur le total lorsque tous les termes appartiennent à une même famille ; un volume mêlé à une masse produit deux entrées dans la liste de courses et lève `AMBIGUOUS_MULTI_UNIT`. ## Mettre à l'échelle les proportions et les temps proportionnels -Une [proportion avec unités](/fr/docs/reference/syntax/relative-quantities/#proportions-avec-unités) n'est jamais multipliée par le facteur : `applyScale` met les cibles à l'échelle, puis recalcule chaque proportion depuis ce qui est écrit (`resolveRatios`, la même passe que `compile`). `@oeufs{1 / 100 g @&farine}` suit donc la farine, et une proportion dont la cible est fixe (`@=poivre{2 g}`) ne bouge pas. La liste de courses est ensuite reconstruite depuis les sections mises à l'échelle : un usage fixe et un usage en proportion d'un même ingrédient s'y fusionnent comme à la compilation. +Une [proportion avec unités](/fr/docs/reference/syntax/relative-quantities/#proportions-avec-unités) n'est jamais multipliée directement par le facteur : `applyScale` ajuste d'abord les cibles, puis relance `resolveRatios` sur la formule d'origine. Ainsi, `@œufs{1 / 100 g @&farine}` suit la farine ajustée tandis qu'une cible figée (`@=poivre{2 g}`) reste immobile. La liste de courses est ensuite reconstruite depuis les sections ajustées afin de fusionner normalement usages fixes et proportionnels. -Quand un [temps proportionnel](/fr/docs/reference/syntax/times/#temps-proportionnels) change (`~{15 min / 500 g @&roti}` pour un rôti deux fois plus gros), le planning est recalculé par les mêmes fonctions que `compile` : `schedule`, le graphe de tâches, `metrics` et les `timings` dépréciés décrivent la recette mise à l'échelle exactement comme la compilerait la source réécrite. Une recette sans proportion se met à l'échelle comme avant. Les avertissements, eux, décrivent toujours la recette telle qu'elle est écrite. +Lorsqu'un [temps proportionnel](/fr/docs/reference/syntax/times/#temps-proportionnels) évolue (`~{15 min / 500 g @&rôti}` pour un rôti doublé), l'ordonnancement, le graphe de tâches, `metrics` et les `timings` dépréciés sont recalculés par les mêmes fonctions que `compile()`, comme si la source avait été réécrite. Les avertissements continuent de refléter la recette d'origine telle qu'écrite. ## Immuabilité diff --git a/packages/docs/src/content/docs/fr/docs/explanation/shopping-list-aggregation.mdx b/packages/docs/src/content/docs/fr/docs/explanation/shopping-list-aggregation.mdx index f9562c79..ff191b72 100644 --- a/packages/docs/src/content/docs/fr/docs/explanation/shopping-list-aggregation.mdx +++ b/packages/docs/src/content/docs/fr/docs/explanation/shopping-list-aggregation.mdx @@ -38,13 +38,13 @@ import Term from '../../../../../components/Term.astro'; La résolution des alias intervient une couche au-dessus, dans `@gram-lang/analyzer`, qui lui accède à la base de données. Si `beurre` y est défini comme alias de `butter`, l'Analyseur va regrouper les entrées brutes sous cet identifiant canonique, fusionnant `@butter` et `@beurre` en une seule ligne `butter`. **Cette étape requiert impérativement une base de données** ; sans elle (compilation avec `@gram-lang/kitchen` seul, ou CLI lancé à nu), les alias sont ignorés et le doublon subsiste. 2. ### Fusion des unités - `@gram-lang/kitchen` fusionne, sans base de données, tout ce qu'il peut additionner exactement, à trois niveaux : + `@gram-lang/kitchen` fusionne sans base de données tout ce qui s'additionne exactement, à trois niveaux : - - **Même unité** : `100 g` et `50 g` s'additionnent (`150 g`). Les graphies d'une même unité n'en font qu'une (`cup` et `cups`, `càs` et `c.à.s`). - - **Même échelle** : des unités qui se convertissent par un rapport entier s'additionnent dans la plus petite unité écrite. Cuillères et tasses américaines (`tsp`, `tbsp`, `fl oz`, `cup`, `pt`, `qt`, `gal`), onces et livres, grammes et kilos, millilitres et litres forment chacun une échelle : `1 kg` et `200 g` donnent `1200 g` (affiché `1,2 kg`), `1 cup` et `2 tbsp` donnent `18 tbsp` (affiché `1 cup + 2 tbsp`). - - **Systèmes ou natures différents** (`cup` et `ml`, un volume et une masse) : des entrées séparées, marquées `multiUnit: true`. `pincée` reste hors de toute échelle : ce n'est pas une mesure exacte. + - **Même unité** : `100 g` et `50 g` s'additionnent (`150 g`), et les variantes graphiques d'une unité sont regroupées (`cup` et `cups`, `càs` et `c.à.s`). + - **Même échelle** : les unités liées par un rapport entier exact s'additionnent dans la plus petite unité écrite. Cuillères et tasses américaines (`tsp`, `tbsp`, `fl oz`, `cup`, `pt`, `qt`, `gal`), onces et livres (`oz`, `lb`), masses métriques (`mg`, `g`, `kg`) et volumes métriques (`ml`, `cl`, `dl`, `l`) forment chacun une échelle : `1 kg` et `200 g` donnent `1200 g` (affiché `1,2 kg`), `1 cup` et `2 tbsp` donnent `18 tbsp` (affiché `1 cup + 2 tbsp`). + - **Systèmes ou natures différents** (`cup` et `ml`, ou volume et masse) : conservés en entrées séparées marquées `multiUnit: true`. Les mesures imprécises comme `pincée` restent hors échelle. - Une [somme de quantités](/fr/docs/reference/syntax/ingredients/#sommes-de-quantités) compte comme plusieurs mentions : `@lait{1 cup + 50 ml}` s'achète en `1 cup` et `50 ml`, exactement comme `@lait{1 cup}` puis `@&lait{50 ml}`. La liste de courses ne dépend donc jamais de la façon dont l'auteur a regroupé ses quantités. Les fourchettes s'additionnent borne par borne (`2-3 g` et `200 g` donnent `202-203 g`, et non plus le milieu, `202,5 g`). Une unité que Gram ne connaît pas reste telle qu'écrite : `gousse` et `gousses` font deux entrées. + Une [somme de quantités](/fr/docs/reference/syntax/ingredients/#sommes-de-quantités) compte comme des mentions distinctes (`@lait{1 cup + 50 ml}` équivaut à `@lait{1 cup}` puis `@&lait{50 ml}`), de sorte que la liste de courses ne dépend jamais du regroupement choisi dans la recette. Les fourchettes s'additionnent borne par borne (`2-3 g` et `200 g` donnent `202-203 g`), tandis que les unités inconnues restent telles qu'écrites (`gousse` et `gousses` restent séparés). Des entrées d'unités de natures différentes (ex : `100 g` et `1 tasse`) ne s'additionnent qu'avec une conversion via la masse, ce qui, tout comme la résolution des alias, dépend de la base de données d'ingrédients et se produit donc dans `@gram-lang/analyzer`. Si chaque quantité contributrice se résout en une masse (densité connue, depuis la BDD ou une surcharge au niveau de la recette), l'analyseur les convertit toutes en grammes et les fusionne en une seule entrée. diff --git a/packages/docs/src/content/docs/fr/docs/how-to/manage-database.mdx b/packages/docs/src/content/docs/fr/docs/how-to/manage-database.mdx index 927fd2d1..0f6c839b 100644 --- a/packages/docs/src/content/docs/fr/docs/how-to/manage-database.mdx +++ b/packages/docs/src/content/docs/fr/docs/how-to/manage-database.mdx @@ -10,10 +10,8 @@ Ce guide détaille le *workflow* standard pour entretenir votre base de données import { Steps, LinkCard, CardGrid } from '@astrojs/starlight/components'; import Since from '../../../../../components/Since.astro'; - - :::tip[La voir dans le playground] -Le [playground](/fr/play) montre la base qu'utilisent ses exemples, dans son onglet `ingredients.yaml`, à côté des fichiers de recette. Elle a le même format que votre propre fichier et s'y lit sans s'y modifier : un ingrédient ajouté là-bas à une recette reste sans masse ni nutrition tant qu'il ne figure pas dans une telle base. + Le [playground](/fr/play) affiche la base `ingredients.yaml` utilisée par ses exemples dans un onglet en lecture seule, aux côtés des fichiers de recette. Tout ingrédient que vous ajoutez dans une recette y reste sans masse ni nutrition tant qu'il ne figure pas dans cette base. ::: ## Le *workflow* recommandé diff --git a/packages/docs/src/content/docs/fr/docs/how-to/scale-recipes.mdx b/packages/docs/src/content/docs/fr/docs/how-to/scale-recipes.mdx index 82fd6359..c1d02e11 100644 --- a/packages/docs/src/content/docs/fr/docs/how-to/scale-recipes.mdx +++ b/packages/docs/src/content/docs/fr/docs/how-to/scale-recipes.mdx @@ -71,7 +71,7 @@ gram view pain.gram --scale farine=400g Gram va résoudre le facteur global (400/500 = 0.8), ajuster l'ancre `farine` à 400 g, et tous les ingrédients relatifs s'évalueront en cascade sur cette nouvelle base (Eau : 70 % de 400 g = 280 g). -Les proportions avec unités suivent de la même façon (depuis la 1.5.0) : `@oeufs{1 / 100 g @&farine}` donne 4 œufs pour 400 g de farine, et un temps proportionnel comme `~{15 min / 500 g @&roti}` suit le rôti, et le planning avec lui. +Les proportions avec unités fonctionnent de la même façon (depuis la 1.5.0) : `@œufs{1 / 100 g @&farine}` s'ajuste à 4 œufs pour 400 g de farine, et un temps proportionnel comme `~{15 min / 500 g @&rôti}` met automatiquement à jour la durée et le planning. ### Les limites de l'ajustement par ingrédient repère diff --git a/packages/docs/src/content/docs/fr/docs/how-to/weekly-shopping-list.mdx b/packages/docs/src/content/docs/fr/docs/how-to/weekly-shopping-list.mdx index ddb12407..9e87b5ac 100644 --- a/packages/docs/src/content/docs/fr/docs/how-to/weekly-shopping-list.mdx +++ b/packages/docs/src/content/docs/fr/docs/how-to/weekly-shopping-list.mdx @@ -53,7 +53,7 @@ gram shop "menus/*.gram" --format md --output liste-de-courses.md gram shop "menus/*.gram" --format json --output liste-de-courses.json ``` -En plus de la quantité lisible (`qty`), le JSON donne celle de chaque ingrédient en nombres (`amount`, `unit`) : un script ou une appli peut ainsi les trier, les additionner ou les comparer sans avoir à décortiquer le texte. Chaque champ est détaillé dans la [référence de la CLI](/fr/docs/reference/tooling/cli/#gram-shop-motif). +En plus du texte formaté (`qty`), `--format json` expose des champs numériques (`amount`, `unit`, `range`, `parts`) pour qu'un script ou une application puisse trier, additionner ou comparer les quantités sans analyser de texte. Consultez la [référence de la CLI](/fr/docs/reference/tooling/cli/#gram-shop-motif) pour le schéma complet. ## Ressources associées diff --git a/packages/docs/src/content/docs/fr/docs/reference/api/data-formats.mdx b/packages/docs/src/content/docs/fr/docs/reference/api/data-formats.mdx index 5b02fb51..72f4c329 100644 --- a/packages/docs/src/content/docs/fr/docs/reference/api/data-formats.mdx +++ b/packages/docs/src/content/docs/fr/docs/reference/api/data-formats.mdx @@ -287,7 +287,7 @@ Mélanger @farine{200g} et @lait{200ml}. Remarquez le vocabulaire `StepToken` généré par le compilateur au sein de `content` : le texte narratif pur est une simple `string` ; les ingrédients, le matériel et les références partagent la forme `Usage` (sans champ `type`, identifiés par la présence d'un `id`) ; les minuteurs, températures, états attendus (`checkpoint`, depuis la 1.5.0 : `{ type, state, note? }`), commentaires et déclarations portent chacun un discriminant `type` explicite en minuscules. Cette distinction avec l'énumération `ASTNodeType` (en PascalCase) du parseur est délibérée : elle caractérise la charge utile *compilée*, non la syntaxe d'entrée. Consultez le guide [Créer une UI personnalisée](/fr/docs/how-to/build-custom-ui) pour un exemple d'intégration dans un framework front-end. - Un minuteur porte `raw`, la durée telle qu'écrite entre les accolades, et `minutes`, la durée que retient le planning (le milieu d'une fourchette). `quantity` et `unit` restent, dans la plus petite unité écrite (`1h20` donne `80` `min`), pour que les programmes qui les lisent restent justes ; une durée écrite comme avant la 1.5 (`1.5h`) les garde inchangés. Un minuteur que Gram ne lit pas ne garde que `raw` (et `name`, `isPassive`) : il s'affiche tel qu'écrit. + Un jeton minuteur comporte `raw` (la durée telle qu'écrite entre accolades) et `minutes` (la durée retenue pour l'ordonnancement, ou le milieu d'une fourchette). `quantity` et `unit` restent renseignés dans la plus petite unité écrite (`1h20` donne `80` `min`) pour la compatibilité ascendante, tandis que les formats antérieurs à la 1.5 (`1.5h`) restent inchangés. Un minuteur non reconnu ne conserve que `raw` (ainsi que `name` et `isPassive`) afin de pouvoir s'afficher tel qu'écrit. ```json { "type": "timer", "raw": "1h30", "quantity": { "type": "single", "value": 90 }, "unit": "min", "minutes": 90 } @@ -295,11 +295,11 @@ Remarquez le vocabulaire `StepToken` généré par le compilateur au sein de `co { "type": "timer", "raw": "1:30" } ``` - Une [somme de quantités](/fr/docs/reference/syntax/ingredients/#sommes-de-quantités) (`@farine{1 cup + 1 tbsp}`) ajoute `parts` à son `Usage` : chaque terme tel qu'écrit, avec son `qty` (un nombre ou une `QuantityValue`) et son `unit`, et `minus: true` sur un terme retiré. **`parts` est la seule source de vérité** ; `qty` et `unit` gardent un total pour qu'un programme qui les lit reste juste : + Une [somme de quantités](/fr/docs/reference/syntax/ingredients/#sommes-de-quantités) (`@farine{1 cup + 1 tbsp}`) ajoute `parts` à son `Usage` : chaque terme écrit avec `qty` (nombre ou `QuantityValue`), `unit`, et `minus: true` pour les termes soustraits. **`parts` fait foi** ; `qty` et `unit` fournissent un résumé de compatibilité : -- **Une seule nature d'unité** : `qty` / `unit` portent le total, dans la plus petite unité écrite quand les unités partagent une échelle (`{1 cup + 1 tbsp}` donne `17` `tbsp`), sinon en `ml` ou en `g`. Une fourchette dans un terme fait du total une fourchette. -- **Plusieurs natures** (un volume et une masse, ou des unités que Gram ne connaît pas) : pas de `qty`, et `unit` contient la somme écrite en toutes lettres (`"1 cup + 20 g"`), comme une quantité en mots (`{une pincée}`). Lisez `parts` plutôt que de décortiquer ce texte. -- **Refusée** (avertissement `INVALID_QUANTITY`) : `parts` seul, ni `qty` ni `unit`. +- **Une seule nature d'unité** : `qty` et `unit` contiennent le total, dans la plus petite unité écrite quand les termes partagent une échelle (`{1 cup + 1 tbsp}` donne `17` `tbsp`), ou sinon en `ml` / `g`. Une fourchette dans un terme rend le total sous forme de fourchette. +- **Plusieurs natures** (un volume et une masse, ou des unités inconnues) : `qty` est omis et `unit` contient l'expression écrite (`"1 cup + 20 g"`), à la manière d'une quantité textuelle (`{une pincée}`). Lisez `parts` plutôt que d'analyser cette chaîne. +- **Invalide** (`INVALID_QUANTITY`) : `parts` seul, sans `qty` ni `unit`. ```json { "id": "farine", "_usageId": "1", "qty": 17, "unit": "tbsp", "parts": [ { "qty": 1, "unit": "cup" }, { "qty": 1, "unit": "tbsp" } ] } diff --git a/packages/docs/src/content/docs/fr/docs/reference/api/i18n.mdx b/packages/docs/src/content/docs/fr/docs/reference/api/i18n.mdx index 03f0a8d1..0f46cf2b 100644 --- a/packages/docs/src/content/docs/fr/docs/reference/api/i18n.mdx +++ b/packages/docs/src/content/docs/fr/docs/reference/api/i18n.mdx @@ -48,11 +48,11 @@ resolveTimeUnit('minutes'); // "m" resolveTimeUnit('heures', 'fr'); // "h" ``` -### Lire une durée +### Analyser une durée -`parseDuration` lit une durée telle qu'on l'écrit dans un minuteur (`1h30`, `1 hr 30 mins`, `1:30 h`, `5'30"`, `45 min - 1 h`), dans n'importe quelle langue de `TIME_DICTIONARIES`, et la convertit en minutes. Elle ne devine jamais : un texte qu'elle ne sait pas lire revient avec sa raison, que kitchen transforme en `MISSING_UNIT`, `INVALID_UNIT` ou `INVALID_DURATION`. Chaque côté garde ses termes (`parts`, dans l'unité écrite) et sa forme (`units`, `clock` ou `prime`). Elle n'impose ni plafond ni signe : c'est à l'appelant de les vérifier. +`parseDuration` convertit en minutes les durées de minuteurs (`1h30`, `1 hr 30 mins`, `1:30 h`, `5'30"`, `45 min - 1 h`) dans toutes les langues de `TIME_DICTIONARIES`. Toute saisie invalide retourne un motif d'échec — traduit par `@gram-lang/kitchen` en `MISSING_UNIT`, `INVALID_UNIT` ou `INVALID_DURATION` — sans jamais deviner. Chaque borne conserve ses termes (`parts`) et sa forme (`units`, `clock` ou `prime`), les contrôles de signe et de plafond revenant à l'appelant. ```typescript function parseDuration(text: string): DurationResult diff --git a/packages/docs/src/content/docs/fr/docs/reference/api/warnings.mdx b/packages/docs/src/content/docs/fr/docs/reference/api/warnings.mdx index ef9e0ba1..5e3fb8d8 100644 --- a/packages/docs/src/content/docs/fr/docs/reference/api/warnings.mdx +++ b/packages/docs/src/content/docs/fr/docs/reference/api/warnings.mdx @@ -25,7 +25,7 @@ interface Warning { `compile()` les retourne dans le tableau `CompilationResult.warnings`. De son côté, `analyze()` les propage (et en ajoute potentiellement de nouveaux) dans `AnalyzedCompilationResult.warnings`. Ce ne sont jamais de simples chaînes de caractères : le champ `.message` est toujours garanti. - Quelques codes portent aussi `data`, ce dont un outil a besoin pour agir sans décortiquer `.message` : le serveur de langage le transmet dans le `data` du diagnostic, et ses Quick Fix s'en servent. Seuls `INVALID_QUANTITY` (`{ reason, suggestion? }`), `OZ_AFTER_VOLUME` (`{ suggestion }`) et le `INVALID_UNIT` d'un ingrédient (`{ reason, suggestion? }`) le remplissent ; ailleurs, il est absent. + Certains codes fournissent aussi un champ `data` structuré permettant aux outils et aux correctifs rapides du serveur de langage d'agir sans analyser `.message`. Seuls `INVALID_QUANTITY` (`{ reason, suggestion? }`), `OZ_AFTER_VOLUME` (`{ suggestion }`) et `INVALID_UNIT` sur un ingrédient (`{ reason, suggestion? }`) renseignent `data`. ## Sévérité & `--strict` @@ -50,7 +50,13 @@ Une quantité relative cible un ingrédient (`50% of @nom`) qui n'est pas apparu ### `RELATIVE_QUANTITY_UNKNOWN_MASS` Émis pendant l'analyse : la cible d'une quantité relative a bien été trouvée, mais sa propre masse est incalculable (unité/densité introuvable). Le pourcentage ne peut donc pas s'appliquer. **Correction** : attribuez à l'ingrédient cible une unité standardisable, ou renseignez sa densité / son `unit_weight` dans la base de données. -Pour une proportion avec unités (`1 / 100 g @&farine`, `~{15 min / 500 g @&roti}`, depuis la 1.5.0), il porte une `reason` et pointe sur la proportion : `noTargetQuantity` (la cible n'a pas de quantité), `incompatibleUnits` (`2 tranches` face à de l'ail compté en gousses, un poids face à une pièce nommée, ou une unité suivie d'un mot, `100 g de`), `missingDensity` (un poids face à un volume, sans densité), `missingUnitWeight` (des pièces face à un poids, sans `unit_weight`), et pour une préparation utilisée en entier (`Étaler la &pate`) `wholeUseAmbiguous` (une autre section s'en sert aussi) ou `producerMassUnknown` (la masse de la section qui la fabrique est incomplète). Gram ne devine jamais une proportion qu'il ne sait pas calculer : la quantité reste non résolue. **Correction** : écrivez la proportion dans l'unité de la cible, ajoutez la densité ou le `unit_weight` à la base d'ingrédients, ou indiquez la quantité de préparation utilisée (`&pate{500 g}`). +Pour une [proportion avec unités](/fr/docs/reference/syntax/relative-quantities/#proportions-avec-unités) (`1 / 100 g @&farine`, `~{15 min / 500 g @&rôti}`, ), il inclut une `reason` pointant sur la proportion et laisse la quantité non résolue : +- `noTargetQuantity` : la cible n'a pas de quantité. +- `incompatibleUnits` : pièces incompatibles (`2 tranches` face à des gousses), poids face à une pièce nommée, ou mot après l'unité (`100 g de`). +- `missingDensity` / `missingUnitWeight` : la conversion entre poids et volume ou pièces requiert `density` ou `unit_weight` dans la base d'ingrédients. +- `wholeUseAmbiguous` / `producerMassUnknown` : pour une préparation utilisée en entier (`&pâte`), une autre section la consomme aussi ou la masse de sa section productrice est incomplète. + +**Correction** : écrivez la proportion dans l'unité de la cible, renseignez `density` ou `unit_weight` dans la base, ou indiquez la quantité utilisée (`&pâte{500 g}`). ### `CIRCULAR_REFERENCE` La quantité relative d'un ingrédient se cible elle-même (`@farine{50% of @farine}`). **Correction** : supprimez l'auto-référence (une quantité relative doit pointer vers un ingrédient ou une variable *différente*). @@ -62,37 +68,35 @@ Une référence pure (`&nom`) ou un ingrédient référençable (`@&nom`) pointe Un `Timer` (minuteur) ou une `Temperature` a été écrit sans unité explicite (ex. `~{10}` au lieu de `~{10 min}`). **Correction** : ajoutez l'unité manquante. ### `INVALID_UNIT` -Soit le mot qui suit un nombre dans un `Timer` (ou dans l'ancre d'une section) n'est pas une unité de temps, comme dans `~{3 bananes}`, soit une `Temperature` a reçu une unité autre que Celsius ou Fahrenheit. **Correction** : utilisez une unité de temps reconnue pour les minuteurs (`h`, `min`, `heures`, `hr`…), et limitez-vous à `°C` ou `°F` pour les températures. +Soit le mot qui suit un nombre dans un `Timer` ou une ancre de section n'est pas une unité de temps reconnue (`~{3 bananes}`), soit une `Temperature` utilise une unité autre que Celsius ou Fahrenheit. **Correction** : utilisez une unité de temps reconnue (`h`, `min`, `heures`, `hr`…), et `°C` ou `°F` pour les températures. - L'avertissement signale aussi un ingrédient dont l'unité se lit comme deux quantités : une unité connue, un nombre puis une autre unité connue, comme dans `@farine{1 cup 5 tbsp}` ou `@farine{1 kg 200 g}`. Tout `cup 5 tbsp` passe alors pour une seule unité inconnue, sans masse, et une recette doublée affiche `2 cup 5 tbsp`. **Correction** : écrivez les deux quantités sous forme de [somme](/fr/docs/reference/syntax/ingredients/#sommes-de-quantités), `@farine{1 kg + 200 g}` ; l'éditeur propose la correction, et `data.suggestion` contient l'unité à écrire (`kg + 200 g`). Un nombre qui ne fait que décrire l'unité, comme dans `@tomates{1 boîte de 400 g}`, ne déclenche rien : doubler le nombre de boîtes reste juste. + Signale aussi un ingrédient dont l'unité juxtapose deux quantités sans opérateur (`@farine{1 cup 5 tbsp}` ou `@farine{1 kg 200 g}`), sans quoi `cup 5 tbsp` passerait pour une seule unité inconnue sans masse. **Correction** : écrivez une [somme de quantités](/fr/docs/reference/syntax/ingredients/#sommes-de-quantités) (`@farine{1 kg + 200 g}`) ; `data.suggestion` fournit la forme corrigée pour les actions rapides de l'éditeur. Les mentions descriptives comme `@tomates{1 boîte de 400 g}` restent valides. -Il signale enfin une unité qui cache une quantité, comme dans `@farine{environ 200g}` : une quantité commence par son nombre, donc avec des mots devant, tout le texte était lu comme une unité, sans masse, et la quantité disparaissait d'une recette mise à l'échelle. **Correction** : écrivez la quantité seule (`@farine{200g}`), et le « environ » dans l'étape s'il compte. Des mots sans nombre, comme `{une pincée}` ou `{à votre goût}`, ne déclenchent rien. +Signale enfin une unité précédée de mots cachant la quantité (`@farine{environ 200g}`), toute quantité devant commencer par son nombre. **Correction** : écrivez `@farine{200g}` et laissez « environ » dans la phrase. Les quantités textuelles sans nombre (`{une pincée}`, `{au goût}`) sont acceptées. ### `INVALID_QUANTITY` -Une [somme de quantités](/fr/docs/reference/syntax/ingredients/#sommes-de-quantités) que Gram refuse d'additionner. La recette compile quand même et la somme s'affiche telle qu'écrite, mais elle ne compte ni dans la liste de courses ni dans la nutrition. Le message et `data.reason` disent ce qui coince : +Émis lorsqu'une [somme de quantités](/fr/docs/reference/syntax/ingredients/#sommes-de-quantités) ou une expression numérique ne peut pas être évaluée. La recette compile et s'affiche telle qu'écrite, mais la valeur est exclue de la liste de courses et de la nutrition. `data.reason` en précise la cause : | `reason` | Exemple | Correction | | :--- | :--- | :--- | -| `unitlessTerm` | `{1 + 1 tasse}` | Donnez son unité à chaque terme : `{1 tasse + 1 càs}`. | -| `percentTerm` | `{100 g + 10%}` | Écrivez le résultat (`{110 g}`, fourni dans `data.suggestion` et proposé par l'éditeur), ou une quantité relative comme `{10% &farine}`. | -| `expressionTerm` | `{2 x 100 g + 50 g}` | Une somme ne fait qu'ajouter ou retirer : écrivez `{250 g}`. | -| `quantityInUnit` | `{1 boîte de 400 g + 50 g}` | Écrivez la quantité dans une seule unité : `{450 g}`. | -| `nonPositiveTotal` | `{1 càs - 1 tasse}` | On retire autant ou plus qu'on n'ajoute : vérifiez les termes. | -| `rangeAfterMinus` | `{1 tasse - 1-2 càs}` | Une fourchette retirée inverserait ses bornes : mettez-la sur un terme ajouté, ou écrivez le total en fourchette. | -| `minusAcrossFamilies` | `{1 tasse - 20 g}` | On ne retire une quantité que d'une quantité de même nature (un volume d'un volume, une masse d'une masse). | +| `unitlessTerm` | `{1 + 1 tasse}` | Donnez son unité à chaque terme (`{1 tasse + 1 càs}`). | +| `percentTerm` | `{100 g + 10%}` | Écrivez le résultat (`{110 g}`, fourni dans `data.suggestion`) ou une quantité relative (`{10% &farine}`). | +| `expressionTerm` | `{2 x 100 g + 50 g}` | Les sommes n'acceptent que `+` et `-` ; écrivez `{250 g}`. | +| `quantityInUnit` | `{1 boîte de 400 g + 50 g}` | Exprimez la quantité dans une seule unité (`{450 g}`). | +| `nonPositiveTotal` | `{1 càs - 1 tasse}` | La quantité retirée atteint ou dépasse ce qui est ajouté. | +| `rangeAfterMinus` | `{1 tasse - 1-2 càs}` | Placez les fourchettes sur un terme ajouté, ou écrivez le total en fourchette. | +| `minusAcrossFamilies` | `{1 tasse - 20 g}` | Soustrayez uniquement au sein d'une même famille d'unités (volume d'un volume, masse d'une masse). | +| `zeroDenominator` | `{1/0 tasse}`, `{1/0% &pâte}`, `#poêle{1/0}`, `^{1/0 °C}` | Une division par zéro est ignorée ; écrivez une fraction valide (`1/2`). | +| `relativeNotSupported` | `@œufs{3}<@boîte{50% @&farine}`, `@œufs{1}<@boîte{1 / 100 g @&farine}` | Pourcentages et proportions ne sont pas encore pris en charge sur un parent composite ; indiquez sa quantité (`@œufs{3}<@boîte{1}`). | -La soustraction se vérifie nature par nature : chaque nature s'additionne et se soustrait de son côté. `{1 tasse - 2 càs + 30 g}` passe donc (les 2 càs se retirent de la tasse), alors que `{1 tasse - 20 g}` n'a aucune masse dont retirer les 20 g. Le survol d'une somme dans l'éditeur montre ce que donne chaque nature. - -Il signale aussi, avec `reason: "zeroDenominator"`, une fraction dont le dénominateur vaut zéro, partout où s'écrit un nombre (`@farine{1/0 tasse}`, `{1 1/0 tasse}`, un terme de somme, `{1/0% &pâte}`, `#poêle{1/0}`, `^{1/0 °C}`). Un tel nombre n'a pas de valeur : Gram l'écarte, comme si aucun nombre n'avait été écrit (`tasse` seule, une somme privée de ce terme, un ingrédient sans quantité pour un pourcentage). Avant, il disparaissait sans un mot. **Correction** : écrivez la fraction voulue (`1/2`). Pour un minuteur, c'est `INVALID_DURATION` qui le signale. - -Avec `reason: "relativeNotSupported"`, il signale un pourcentage posé sur un parent composite (`@oeufs{3}<@boite{50% @&farine}>`), que Gram ne sait pas encore lire : le parent est pris sans quantité, là où le pourcentage disparaissait jusqu'ici sans un mot. **Correction** : écrivez la quantité du parent (`<@boite{1}>`). Une proportion sur un parent (`<@boite{1 / 100 g @&farine}>`) est refusée de la même façon, et une proportion sur zéro (`{1 / 0 g @&farine}`) lève `zeroDenominator` : l'ingrédient est lu sans quantité. +La soustraction est vérifiée par famille d'unités : `{1 tasse - 2 càs + 30 g}` est valide (2 càs retirées de 1 tasse), tandis que `{1 tasse - 20 g}` n'a aucune masse dont soustraire les 20 g. ### `OZ_AFTER_VOLUME` -Information : une somme place `oz` après un volume, comme dans `@eau{1 cup + 2 oz}`. `oz` est une once de poids, et Gram la lit comme telle : la somme est un volume plus une masse. **Correction** : écrivez `fl oz` si vous pensiez à une once liquide (`data.suggestion`, proposé par l'éditeur) ; sinon, rien à faire. +Notice informative lorsqu'`oz` suit un volume dans une somme (`@eau{1 cup + 2 oz}`). Comme `oz` désigne une masse, Gram le garde séparé du volume. **Correction** : écrivez `fl oz` s'il s'agit d'onces liquides (`data.suggestion` propose cette correction rapide). ### `DURATION_OUT_OF_RANGE` @@ -102,12 +106,17 @@ Un minuteur, ou le décalage du rétroplanning d'une section, dure plus de 1000 ### `AMBIGUOUS_NUMBER` -Une virgule suivie d'exactement trois chiffres, après une partie entière d'un à trois chiffres, comme dans `@farine{1,000 g}` ou `@farine{12,500 g}`. Gram lit une virgule entre deux chiffres comme une décimale et n'a pas de séparateur de milliers : c'est donc 1 g (et 12,5 g). L'avertissement dit comment le nombre a été lu, parce qu'un lecteur anglophone y verrait mille. Dans tous les cas, la quantité reste utilisable. **Correction** : écrivez `{1000 g}` si vous vouliez mille, `{1 g}` sinon. Un nombre qui ne peut pas être un séparateur de milliers, comme `{0,125 kg}` ou `{1,25 kg}`, ne déclenche rien, pas plus que le point : `{1.000 kg}` a toujours voulu dire 1 kg. Tous les nombres d'une recette sont vérifiés : quantités, minuteurs et températures, mais aussi un pourcentage (`{1,000% &pâte}`) et l'ancre d'une section (`~{-1,000h}`, lue comme une heure), y compris celle posée sur un `@use`. Une ancre écartée de toute façon, positive ou sans unité valide, ne déclenche que `MISSING_UNIT`, `INVALID_UNIT` ou `INVALID_DURATION`. +Une virgule suivie de trois chiffres après un à trois chiffres entiers (`@farine{1,000 g}`, `@farine{12,500 g}`). Gram prenant en charge la virgule décimale sans séparateur de milliers, `{1,000 g}` est interprété comme `1 g` (et `{12,500 g}` comme `12,5 g`). Vérifié sur les quantités, minuteurs, températures, pourcentages et ancres de section (`@use` inclus). **Correction** : écrivez `{1000 g}` pour mille, ou `{1 g}` sinon. Un point (`{1.000 kg}`) reste toujours une décimale sans avertissement. ### `INVALID_DURATION` -Un minuteur ou l'ancre d'une section est écrit avec des nombres et des unités que Gram connaît, mais d'une façon qu'il refuse de deviner : `~{1:30}` (des heures ou des minutes ?), `~{30min 1h}` (unités dans le désordre), `~{1h75}` (75 minutes après une heure), `~{1-2h30}` (le côté gauche vaut-il `1 h` ou `1 h 30` ?), `~{2-1 h}` (une fourchette commence par la durée la plus courte), `~{2 * 2 min}` ou `~{1 heure et demie}`. Le message donne la raison et un exemple à écrire à la place. Le minuteur ne compte pas dans le temps total (le JSON compilé n'en garde que le texte écrit, dans `raw`) et l'ancre est ignorée. Une ancre est aussi refusée si c'est une fourchette (`~{-1-2j}`) ou si elle compte des secondes (`~{-1min30}`, `~{-5'}`). Un temps proportionnel est refusé avec un multiplicateur (`~{15 min / 500 g @&roti * 2}`, `reason: "ratioMultiplication"`) ou une fourchette comme quantité de la cible (`~{15 min / 1-2 kg @&roti}`, `"ratioShape"`), et une ancre ne peut jamais en être un (`"anchorRatio"`). **Correction** : écrivez la durée comme le propose le message, par exemple `~{1h30}`, `~{1:30 min}` ou `~{1h30-2h}`. Un mot juste après un nombre reste une unité inconnue (`INVALID_UNIT`), et un nombre seul un `MISSING_UNIT`. +Un minuteur ou une ancre de section emploie des nombres et unités connus de Gram, mais sous une forme ambiguë ou non prise en charge : +- **Minuteurs ambigus ou invalides** : `~{1:30}` (heures ou minutes ?), `~{30min 1h}` (ordre inversé), `~{1h75}` (`≥ 60` après les heures), `~{1-2h30}` (borne ambiguë), `~{2-1 h}` (fourchette inversée), `~{2 * 2 min}` ou texte libre (`~{une demi-heure}`). Le minuteur est exclu du temps total tout en conservant son texte dans `raw`. +- **Ancres non prises en charge** : fourchettes (`~{-1-2j}`), secondes (`~{-1min30}`, `~{-5'}`) ou ancres proportionnelles (`reason: "anchorRatio"`). +- **Limites des temps proportionnels** : multiplicateurs (`~{15 min / 500 g @&rôti * 2}`, `reason: "ratioMultiplication"`) ou cibles en fourchette (`~{15 min / 1-2 kg @&rôti}`, `reason: "ratioShape"`). + +**Correction** : suivez l'écriture suggérée dans `.message` (`~{1h30}`, `~{1:30 min}`, `~{1h30-2h}`). Un mot inconnu après un nombre lève toujours `INVALID_UNIT`, et un nombre seul `MISSING_UNIT`. ### `SCOPE_CONFLICT` Deux sections déclarent un même nom de variable (`>> nom`). Les noms de variables doivent être uniques à l'échelle de toute la recette, pas juste de la section. **Correction** : renommez l'une des deux variables. 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 c5332efb..1a64dbf6 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 @@ -77,7 +77,7 @@ Les quantités et les minuteurs ont besoin d'un vrai nombre (ou d'accolades vide ```gram ❌ @farine{1 kg 200 g} → ✅ @farine{1 kg + 200 g} ``` -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}`). +Écrivez les mesures composées en [somme](/fr/docs/reference/syntax/ingredients/#sommes-de-quantités) (`{1 cup + 1 tbsp}`, `{1 tasse - 2 càs}`, `{1 tasse + 20 g}`) plutôt que de les convertir en un seul nombre décimal (`{1.0625 cup}`). Chaque terme doit porter son unité, et seules les quantités simples sont autorisées (pas de `%`, pas de `×`, et pas de fourchette après `-`). ### Le mode du four laissé dans la phrase @@ -86,7 +86,7 @@ Une quantité que la recette donne en plusieurs mesures s'écrit en [somme](/fr/ ❌ 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. +Placez le mode du four ou la condition de cuisson (« chaleur tournante », « à cœur », « à couvert ») dans une [précision entre parenthèses](/fr/docs/reference/syntax/temperatures/#mode-de-cuisson-et-précisions) collée à `}`, dans la langue de la recette. Un espace devant `(` la laisse en texte ordinaire. ### L'état attendu laissé dans la phrase @@ -95,17 +95,17 @@ Ce qui accompagne une température (le mode du four, « à cœur », « à couve ❌ Fouetter jusqu'au ruban. → ✅ Fouetter jusqu'au ={ruban}. ❌ Cuire jusqu'à ={82°C} ou ={5 min}. → ✅ Cuire à ^{82°C}(à cœur) pendant ~{5 min}, jusqu'à ={la nappe}. ``` -Quand la source dit quel état atteindre (une texture, une couleur, une odeur), notez-le en [état attendu](/fr/docs/reference/syntax/target-states/), où qu'il se trouve dans l'étape : l'état seul entre les accolades, les mots de liaison (« jusqu'à », « dès que », « quand ») laissés dans la phrase, et un test en précision collée si la source en donne un. Jamais de température, de durée ni de quantité à l'intérieur, et jamais de repère que la source ne donne pas. +Balisez les repères visuels ou sensoriels donnés par la source en [états attendus](/fr/docs/reference/syntax/target-states/) (`={...}`), en laissant les mots de liaison (« jusqu'à », « dès que », « quand ») hors des accolades et en plaçant tout test de contrôle dans une précision collée `(...)`. N'y mettez jamais de température, de durée ni de quantité, et n'inventez aucun repère absent de la source. ### Une règle proportionnelle calculée à la main ```gram -❌ Ajouter @oeufs{5} (1 œuf pour 100 g de farine). → ✅ Ajouter @oeufs{1 / 100 g @&farine}. -❌ Rôtir ~{36 min} (15 min par 500 g). → ✅ Rôtir ~{15 min / 500 g @&roti}. -❌ Ajouter @oeufs{1/100g @&farine}. → ✅ Ajouter @oeufs{1 / 100 g @&farine}. +❌ Ajouter @œufs{5} (1 œuf pour 100 g de farine). → ✅ Ajouter @œufs{1 / 100 g @&farine}. +❌ Rôtir ~{36 min} (15 min par 500 g). → ✅ Rôtir ~{15 min / 500 g @&rôti}. +❌ Ajouter @œufs{1/100g @&farine}. → ✅ Ajouter @œufs{1 / 100 g @&farine}. ``` -Quand la source énonce une règle proportionnelle (« pour 100 g », « par litre », « par pièce »), écrivez-la en [proportion avec unités](/fr/docs/reference/syntax/relative-quantities/#proportions-avec-unités) : elle suit sa cible quand la recette change d'échelle. Seulement dans ce cas : une quantité que la source donne telle quelle reste une quantité. Toujours une espace autour de la barre, l'unité seule avant la cible (jamais `100 g de @&farine`), et aucun multiplicateur après un temps proportionnel. +Lorsque la source formule une règle proportionnelle (« pour 100 g », « par litre », « par pièce »), écrivez-la en [proportion avec unités](/fr/docs/reference/syntax/relative-quantities/#proportions-avec-unités) pour qu'elle suive la mise à l'échelle. Espacez toujours `/`, écrivez l'unité seule devant la cible (jamais `100 g de @&farine`), et n'ajoutez pas de multiplicateur après un temps proportionnel. ### Utiliser `@&` dès la première occurrence 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 ef7280d6..a81f28ff 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 @@ -15,9 +15,9 @@ Les marqueurs essentiels utilisés directement au fil des étapes : | :--- | :--- | :--- | :--- | :--- | | **Ingrédient** | `@` | `@nom[{quantité}]` | `@farine{200g}` | Déclare un ingrédient. Omettre `{}` indique une absence de quantité explicite (ex. `@sel`). | | **Matériel** | `#` | `#nom[{quantité}]` | `#poêle{2}`, `#fouet` | Indique un ustensile ou équipement requis. Omettre `{}` équivaut à `1`. | -| **Minuteur** | `~` | `~{temps}` | `~{30min}`, `~{1h30}` | Définit la durée d'une action active en cuisine, écrite comme dans une recette (`1 heure 30`, `1:30 h`, `5'30"`). | +| **Minuteur** | `~` | `~{temps}` | `~{30min}`, `~{1h30}` | Durée d'une action active en cuisine (`1 heure 30`, `1:30 h`, `5'30"`). | | **Température** | `^` | `^{température}` | `^{180°C}`, `^{350°F}` | Indique une consigne thermique précise (`C` ou `F`, insensible à la casse). | -| **État attendu** | `=` | `={état}` | `={ruban}`, `={doré}` | L'état à atteindre, avec les mots du cuisinier, n'importe où dans l'étape. Depuis la 1.5.0. | +| **État attendu** | `=` | `={état}` | `={ruban}`, `={doré}` | Repère sensoriel à atteindre, n'importe où dans l'étape. | ## Modificateurs @@ -42,18 +42,18 @@ Formulations complémentaires pour enrichir la description des étapes : | **Préparation courte** | `(...)` | `@beurre{10g}(pommade)` | Précise l'état ou la découpe sans surcharger l'identifiant. | | **Alias de composant** | `:identifiant` | `@vin blanc sec:vin{10ml}` | Affiche un libellé clair tout en reliant l'ingrédient à un identifiant canonique. | | **Quantité relative** | `% @&cible` | `@eau{70% @&farine}` | Calcule la quantité par rapport à la masse d'un ingrédient pivot. | -| **Proportion avec unités** | `a / b @&cible` | `@oeufs{1 / 100 g @&farine}`, `@sel{15 g / L @&eau}` | Une quantité par quantité d'un autre ingrédient, dans n'importe quelles unités ; une espace autour de la barre. Depuis la 1.5.0. | +| **Proportion avec unités** | `a / b @&cible` | `@œufs{1 / 100 g @&farine}`, `@sel{15 g / L @&eau}` | Quantité par référence d'un autre ingrédient, dans n'importe quelles unités compatibles (espace autour de `/`). | | **Ingrédient composite** | `<@parent` | `@zeste de citron{1}<@citron` | Rapproche des éléments (zeste, jus) sous un même article d'achat parent. | | **Minuteur passif** | `~_` | `~_{1h}` | Modélise un repos ou une pousse sans monopoliser le cuisinier. | -| **Temps proportionnel** | `~{temps / b @&cible}` | `~{15 min / 500 g @&roti}`, `~{4 min / @&cotelette}` | Un temps qui suit un poids ou un nombre de pièces, recalculé à la mise à l'échelle. Depuis la 1.5.0. | +| **Temps proportionnel** | `~{temps / b @&cible}` | `~{15 min / 500 g @&rôti}`, `~{4 min / @&côtelette}` | Durée recalculée selon le poids ou le nombre d'un ingrédient. | | **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. Depuis la 1.5.0. | -| **Précision d'un état attendu** | `={...}(précision)` | `={la nappe}(un doigt laisse une trace nette)` | Comment vérifier l'état, toujours affichée. Depuis la 1.5.0. | +| **Précision de température** | `^{...}(précision)` | `^{160°C}(chaleur tournante)`, `^{63°C}(à cœur)` | Mode du four ou condition de cuisson, toujours affichée. | +| **Précision d'état attendu** | `={...}(précision)` | `={la nappe}(un doigt laisse une trace nette)` | Comment vérifier l'état attendu, toujours affichée. | | **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. | +| **Somme de quantités** | `a + b`, `a - b` | `@farine{1 kg + 200 g}`, `@sucre{1 tasse - 2 càs}`, `@riz{1 tasse + 20 g}` | Conservée telle qu'écrite et additionnée ; un volume et une masse restent côte à côte. | -Toute précision entre parenthèses `(...)` — sur un ingrédient, un ustensile, une température ou un état attendu — doit être collée à l'élément qui la précède, sur la même ligne : avec un espace, elle reste du texte ordinaire. +Toute précision entre parenthèses `(...)` — sur un ingrédient, un ustensile, une température ou un état attendu — doit être collée à l'élément qui la précède, sur la même ligne ; avec un espace, elle reste du texte ordinaire. ## Variables intermédiaires diff --git a/packages/docs/src/content/docs/fr/docs/reference/syntax/ingredients.mdx b/packages/docs/src/content/docs/fr/docs/reference/syntax/ingredients.mdx index 00bf71b1..c400ef43 100644 --- a/packages/docs/src/content/docs/fr/docs/reference/syntax/ingredients.mdx +++ b/packages/docs/src/content/docs/fr/docs/reference/syntax/ingredients.mdx @@ -201,7 +201,7 @@ Ajouter le @beurre{1½ plaquette}. ### Nombres décimaux -Un nombre décimal s'écrit avec une virgule ou un point, selon votre habitude : `{1,5 kg}` et `{1.5 kg}` désignent la même quantité. C'est valable pour tous les nombres entre accolades : ingrédients, fourchettes (`{0,5-0,75 l}`), quantités relatives (`{12,5% &pâte}`), ustensiles, températures (`^{37,5°C}`), minuteurs et ancres de section. +Les nombres décimaux acceptent indifféremment la virgule ou le point : `{1,5 kg}` et `{1.5 kg}` désignent la même quantité. Cela vaut pour tous les nombres entre accolades : ingrédients, fourchettes (`{0,5-0,75 l}`), quantités relatives (`{12,5% &pâte}`), ustensiles, températures (`^{37,5°C}`), minuteurs et ancres de section. ```gram Ajouter la @farine{1,5 kg} et le @sel{0.125 kg}. @@ -209,53 +209,51 @@ Ajouter la @farine{1,5 kg} et le @sel{0.125 kg}. Verser le @lait{0,5-0,75 l}. ``` -Gram n'a pas de séparateur de milliers : écrivez `{1500 g}`, jamais `{1,500 g}`. Une virgule suivie d'exactement trois chiffres se lit comme une décimale, comme les autres (`{1,000 g}` fait 1 g). Mais comme un lecteur anglophone y verrait mille, le compilateur émet `AMBIGUOUS_NUMBER` et précise comment il a lu le nombre. Le point garde le sens qu'il a toujours eu : `{1.000 kg}` fait 1 kg, sans avertissement. +Gram n'a pas de séparateur de milliers : écrivez `{1500 g}`, jamais `{1,500 g}`. Une virgule suivie de trois chiffres comme `{1,000 g}` est interprétée comme une décimale (`1 g`) et déclenche un avertissement `AMBIGUOUS_NUMBER` ; le point (`{1.000 kg}`) garde toujours son sens décimal sans avertissement. ### Sommes de quantités -Quand une mesure ne tient pas dans une seule unité, on l'écrit comme le dirait la recette : des termes reliés par `+`, ou par `-` pour une quantité qu'on retire. +Quand une mesure associe plusieurs unités, écrivez-la en somme avec `+`, ou `-` pour une quantité retirée : ```gram -Ajouter la @farine{1 kg + 200 g} et le @lait{1 l - 10 cl}. +Ajouter la @farine{1 kg + 200 g} et le @sucre{1 tasse - 2 càs}. Verser la @crème{20 cl + 1-2 càs}. Incorporer le @beurre{2 1/2 càs + ½ càc} et le @riz{1 tasse + 20 g}. ``` -Chaque terme est un nombre (ou une fourchette, ou une fraction) suivi de son unité. Gram garde les termes tels qu'écrits et en calcule le total : `{1 kg + 200 g}` fait 1200 g, `{1 l - 10 cl}` fait 90 cl. La recette affiche la somme comme vous l'avez écrite ; une fois mise à l'échelle, elle est recalculée en quantités qu'on peut mesurer (`{1 kg + 200 g}` doublé donne `2,4 kg`, et `{1 cup + 1 tbsp}` doublé donne `2 cup + 2 tbsp`, pas `2 1/8 cup`). Le modificateur `=` fige une somme comme n'importe quelle quantité (`@=sel{1,5 g + 1 pincée}`). +Chaque terme est une quantité (nombre, fourchette ou fraction) suivie de son unité. Gram conserve la somme telle qu'écrite dans la recette d'origine et la recalcule en mesures pratiques lors de la mise à l'échelle (par exemple, `{1 cup + 1 tbsp}` doublé devient `2 cup + 2 tbsp`). Le modificateur `=` fige la somme entière (`@=sel{1,5 g + 1 pincée}`). -Une somme vaut **plusieurs mentions** de l'ingrédient : `@riz{1 tasse + 20 g}` arrive dans la liste de courses exactement comme `@riz{1 tasse}` suivi de `@&riz{20 g}`. Les termes de même nature s'additionnent (tasses et cuillères, kilos et grammes) ; un volume à côté d'une masse, ou deux unités que Gram ne connaît pas (`{1 tête + 2 gousses}`), restent côte à côte. +Dans la liste de courses, une somme équivaut à des mentions distinctes de l'ingrédient : les unités compatibles s'additionnent (tasses et cuillères, grammes et kilos), tandis qu'un volume et une masse (`{1 tasse + 20 g}`) ou des unités inconnues restent côte à côte. -Quelques règles gardent une somme lisible : +Quelques règles garantissent la cohérence d'une somme : -- **Chaque terme a son unité** : `{1 + 1 tasse}` est refusé. -- **Rien que des quantités** : pas de pourcentage (`{100 g + 10%}` ; écrivez `{110 g}`, ou une [quantité relative](/fr/docs/reference/syntax/relative-quantities/)), pas de multiplication (`{2 x 100 g + 50 g}`). -- **On retire d'une quantité de même nature** : `{1 tasse - 2 càs}` passe, `{1 tasse - 20 g}` non, et il doit rester quelque chose (`{1 càs - 1 tasse}` est refusé). -- **Pas de fourchette après un `-`** : `{1 tasse - 1-2 càs}` inverserait ses bornes ; mettez la fourchette sur un terme ajouté. +- **Chaque terme porte son unité** : `{1 + 1 tasse}` est refusé. +- **Uniquement des quantités simples** : pas de pourcentage (`{100 g + 10%}`) ni de multiplication (`{2 x 100 g}`). +- **Soustraction au sein d'une même nature** : `{1 tasse - 2 càs}` est accepté, `{1 tasse - 20 g}` ne l'est pas, et le résultat doit rester positif (`{1 càs - 1 tasse}` est refusé). +- **Pas de fourchette après `-`** : placez les fourchettes sur un terme ajouté (`{1 tasse + 1-2 càs}`), jamais sur un terme soustrait. -Chaque nature de quantité s'additionne et se soustrait **de son côté**, car on ne compare pas un volume et une masse sans densité. Dans `{1 tasse - 2 càs + 30 g}`, les 2 càs se retirent de la tasse et les 30 g s'ajoutent à côté : la somme fait une tasse moins deux cuillères de volume, plus 30 g de masse. Dans `{1 tasse - 20 g}`, il n'y a aucune masse dont retirer les 20 g : Gram refuse plutôt que de deviner. Survolez une somme dans l'éditeur pour voir ce que donne chaque nature. +Une somme invalide compile quand même avec un avertissement `INVALID_QUANTITY` indiquant le motif, et est exclue de la liste de courses et de la nutrition. Consultez [Mettre à l'échelle une somme de quantités](/fr/docs/explanation/scaling/#mettre-à-léchelle-une-somme-de-quantités) pour en savoir plus. -Une somme refusée compile quand même, avec un avertissement `INVALID_QUANTITY` qui en donne la raison, et ne compte ni dans la liste de courses ni dans la nutrition. Deux quantités écrites côte à côte sans opérateur (`{1 kg 200 g}`) déclenchent `INVALID_UNIT` ; l'éditeur propose d'insérer le ` + `. - -:::caution[oz est une masse] -Dans `{1 cup + 2 oz}`, `oz` désigne une once de poids, pas de volume : Gram le lit tel quel et ajoute une note (`OZ_AFTER_VOLUME`). Écrivez `fl oz` pour une once liquide. +:::caution[`oz` désigne une masse] +Dans `{1 cup + 2 oz}`, `oz` est interprété comme une once de poids, et non de volume (`OZ_AFTER_VOLUME`). Écrivez `fl oz` pour une once liquide. ::: ## Gestion des erreurs -Certaines erreurs de syntaxe arrêtent la lecture de la recette avant même la compilation : une quantité entre accolades illisible (`@sel{1 g/l}`), une accolade jamais refermée. Le message indique l'endroit exact à corriger, et l'éditeur le souligne. +Certaines erreurs de syntaxe arrêtent l'analyse avant même la compilation : une quantité illisible entre accolades (`@sel{1 g/l}`) ou une accolade non refermée. Le message pointe l'endroit exact à corriger. -Le compilateur vérifie les erreurs sémantiques dans vos déclarations d'`@ingrédient` et produira des avertissements spécifiques : +Le compilateur vérifie également la cohérence sémantique de vos déclarations d'`@ingrédient` : -- **Modificateur Invalide** : Si vous combinez des modificateurs incompatibles (comme `?*`), le compilateur avertit `INVALID_MODIFIER_COMBINATION` et les ignore. -- **Référence Non Définie** : Si vous utilisez une référence (`@&ingrédient`) mais que cet élément n'a pas été déclaré précédemment dans la recette, le compilateur avertit `UNDEFINED_REFERENCE`. -- **Base de Données Manquante** : Si vous compilez avec une base de données et que l'`@ingrédient` est introuvable, il avertit `MISSING_INGREDIENT`. -- **Macros Manquants** : Si la base de données ne contient pas d'informations nutritionnelles pour l'`@ingrédient`, il avertit `MISSING_MACROS`. -- **Masse Inconnue** : S'il ne peut pas convertir un volume ou une unité en grammes pour estimer la nutrition, il avertit `UNKNOWN_MASS`. -- **Quantité invalide** : si une somme de quantités ne peut pas être lue (un terme sans unité, un pourcentage, une quantité retirée d'une autre nature…), il avertit `INVALID_QUANTITY` et en donne la raison. -- **Nombre ambigu** : si une virgule est suivie d'exactement trois chiffres (`{1,000 g}`), il lit une décimale et avertit `AMBIGUOUS_NUMBER`, au cas où mille était voulu. +- **Modificateur invalide** : Si vous combinez des modificateurs incompatibles (comme `?*`), le compilateur avertit `INVALID_MODIFIER_COMBINATION` et les ignore. +- **Référence non définie** : Si vous utilisez une référence (`@&ingrédient`) avant sa déclaration initiale dans la recette, le compilateur avertit `UNDEFINED_REFERENCE`. +- **Base de données manquante** : Si vous compilez avec une base de données et que l'`@ingrédient` est introuvable, il avertit `MISSING_INGREDIENT`. +- **Macros manquants** : Si la base de données ne contient pas d'informations nutritionnelles pour l'`@ingrédient`, il avertit `MISSING_MACROS`. +- **Masse inconnue** : S'il ne peut pas convertir un volume ou une pièce en grammes pour estimer la nutrition, il avertit `UNKNOWN_MASS`. +- **Quantité invalide** : Si une somme de quantités enfreint l'une des règles ci-dessus, il avertit `INVALID_QUANTITY` en précisant le motif. +- **Nombre ambigu** : Si une virgule est suivie de trois chiffres (`{1,000 g}`), il interprète une décimale et avertit `AMBIGUOUS_NUMBER`. ## Ressources associées diff --git a/packages/docs/src/content/docs/fr/docs/reference/syntax/relative-quantities.mdx b/packages/docs/src/content/docs/fr/docs/reference/syntax/relative-quantities.mdx index 64263d60..db7acd12 100644 --- a/packages/docs/src/content/docs/fr/docs/reference/syntax/relative-quantities.mdx +++ b/packages/docs/src/content/docs/fr/docs/reference/syntax/relative-quantities.mdx @@ -49,61 +49,46 @@ Lors de l'évaluation d'une quantité relative, le compilateur observe quatre r | **Portée de section** | Section courante uniquement | Il n'est pas possible de cibler directement un ingrédient brut déclaré dans une autre section. Pour traverser les sections, capturez le résultat dans une `&variable` intermédiaire globale. | | **Accumulation** | Somme des occurrences | Si le même `@ingrédient` cible apparaît plusieurs fois dans la section, le pourcentage est appliqué sur la **somme totale cumulée** de ces quantités. | | **Calcul en masse** | Évalué en grammes | Les calculs reposent invariablement sur la **masse physique en grammes**. Par exemple, 50% de « 2 œufs » (calibrés à 50g l'unité) produira **50g**, et non 1 œuf. | -| **Alternatives** | Une option à la fois | Chaque option d'une alternative reçoit sa propre quantité, sans jamais s'additionner aux autres : pour 200 g de farine, `@beurre{10% @&farine}\|@huile{8% @&farine}` se lit « 20 g de beurre ou 16 g d'huile ». Une option peut aussi se calculer sur une option qui la précède dans le même groupe : `@beurre{100g}\|@huile{80% @&beurre}`. | +| **Alternatives** | Une option à la fois | Chaque option d'un groupe d'alternatives est calculée indépendamment (`@beurre{10% @&farine}\|@huile{8% @&farine}` donne 20 g de beurre ou 16 g d'huile pour 200 g de farine). Une option peut aussi cibler une option précédente du même groupe (`@beurre{100g}\|@huile{80% @&beurre}`). | ## Proportions avec unités -Un pourcentage compare des grammes à des grammes. Une relie deux quantités dans n'importe quelles unités, comme les recettes énoncent leurs règles : un œuf pour 100 g de farine, 15 g de sel par litre d'eau, 15 minutes par 500 g de rôti. +Alors qu'un pourcentage compare des grammes à des grammes, une relie deux quantités dans n'importe quelles unités compatibles, comme les recettes énoncent leurs règles : 1 œuf pour 100 g de farine, 15 g de sel par litre d'eau, ou 15 minutes par 500 g de rôti. ```gram -Mélanger @farine{500 g} avec @oeufs{1 / 100 g @&farine}. // 5 œufs +Mélanger @farine{500 g} avec @œufs{1 / 100 g @&farine}. // 5 œufs Verser @eau{2 l} et @sel{15 g / 1 L @&eau}. // 30 g de sel Écraser @ail{3 gousses} avec @persil{1 càc / 2 gousses @&ail}. // 1,5 càc ``` -**Forme :** `@nom{ quantité / quantité de la cible @&IngrédientCible }`, ou `&VariableCible` pour une préparation intermédiaire. La quantité prend son unité (`15 g`) ou aucune (`1` œuf) ; la quantité de la cible est un nombre et une unité (`100 g`), une unité seule (`L`), ou rien pour une pièce (`{1 / @&côtelette}`). Une fourchette marche pour la quantité (`{15-20 g / 100 g @&farine}`), jamais pour celle de la cible. +**Schéma :** `@nom{ quantité / quantitéCible @&IngrédientCible }` (ou `&VariableCible`). -Mettez une espace d'au moins un côté de la barre : `{1/100g @&farine}` se lit comme la fraction `1/100`, et Gram la refuse avec un message qui montre la forme espacée. Écrivez aussi l'unité seule : dans `{1 / 100 g de @&farine}`, l'unité serait `g de`, que Gram refuse. +- `quantité` porte son unité (`15 g`) ou aucune pour des pièces (`1` œuf), et accepte une fourchette (`15-20 g`). +- `quantitéCible` est un nombre simple et son unité (`100 g`), une unité seule (`L`), ou rien pour une pièce (`{1 / @&côtelette}`). +- **Espacez toujours `/`** (au moins d'un côté) et écrivez l'unité seule devant la cible : `{1/100g @&farine}` serait interprété comme la fraction `1/100`, et `{1 / 100 g de @&farine}` prendrait `g de` pour l'unité. -### Le garde-fou des unités +### Garde-fou des unités -Une proportion n'est calculée que si ses unités se comparent, jamais devinée : +Gram ne calcule une proportion que lorsque ses unités sont comparables ; il ne devine jamais : -| Quantité de la cible | Cible écrite en | Résultat | +| Quantité cible | Cible écrite en | Résultat | | :--- | :--- | :--- | -| Un poids (`100 g`) | Un poids (`1 kg`) | Calculée par le compilateur | -| Un poids | Un volume, ou des pièces | Calculée avec la densité ou le `unit_weight` de la base d'ingrédients | -| Des pièces (`2 gousses`, rien) | Les mêmes pièces (`3 gousse`, `4`) | Calculée par le compilateur : singulier et pluriel se valent | -| Des pièces | D'autres pièces (`2 tranches` pour de l'ail en gousses) | Refusée | +| Poids (`100 g`) | Poids (`1 kg`) | Calcul direct | +| Poids | Volume ou pièces | Calculé via la densité ou le `unit_weight` de la base d'ingrédients | +| Pièces (`2 gousses`, ou rien) | Mêmes pièces (`3 gousse`, `4`) | Calcul direct (singulier/pluriel reconnus) | +| Pièces | Autres pièces (`2 tranches` pour des gousses) | Refusé (`RELATIVE_QUANTITY_UNKNOWN_MASS`) | -Une proportion impossible à calculer garde son écriture (`1 / 100 ml @&farine` dans les vues et la liste de courses) et lève `RELATIVE_QUANTITY_UNKNOWN_MASS` avec la raison. Contrairement au pourcentage, une proportion calculée garde l'unité de sa quantité : `5` œufs, `15 g` de sel, fusionnés avec les autres usages de l'ingrédient dans la liste de courses. +Si une proportion ne peut pas être résolue, elle conserve son écriture dans les vues et la liste de courses, et déclenche `RELATIVE_QUANTITY_UNKNOWN_MASS`. Contrairement aux pourcentages, une proportion résolue conserve l'unité de sa propre quantité (`5` œufs, `15 g` de sel) et fusionne normalement dans la liste de courses. -### Où se trouve la cible +### Portée, préparations intermédiaires et mise à l'échelle -Les mêmes règles que pour un pourcentage : un `@&ingrédient` écrit plus tôt dans la section avec une quantité (toutes les quantités de la section s'additionnent), ou une `&préparation`. Une option d'une alternative peut viser une option qui la précède. Quand la section utilise une préparation en entier, sans quantité (`Étaler la &pate`), la proportion se calcule sur la masse de la section qui la fabrique : une estimation de ce qui est entré dans le bol, avant cuisson. Gram refuse si une autre section se sert aussi de la préparation, faute de savoir qui en prend quoi : - -```gram -## Pâte ->&pate - -Mélanger @farine{500 g} et @eau{60% @&farine}. - -## Cuisson - -Étaler la &pate, saupoudrer de @sel{2 g / 100 g &pate}. // 16 g pour 800 g -``` - -Le pourcentage en profite aussi (`@sucre{5% &pate}`), lui qui abandonnait jusqu'ici dans ce cas. - -### Sur les références et les composites - -Une référence à une préparation maison accepte elle aussi une proportion ou un pourcentage : `&bouillon{250 ml / 100 g @&riz}`, `&bouillon{250% @&riz}`. Un parent composite, pas encore (`<@boite{1 / 100 g @&farine}>` reste refusé en attendant la refonte des composites). - -### Mise à l'échelle - -Mettre une recette à l'échelle recalcule ses proportions sur les quantités mises à l'échelle : deux fois plus de farine, deux fois plus d'œufs. Une proportion dont la cible est fixe (`@=poivre{2 g}`) ne bouge pas. Le `=` sur la proportion elle-même est refusé : une proportion suit toujours sa cible. +- **Même portée que les pourcentages** : ciblez un `@&ingrédient` déclaré plus tôt dans la section (les mentions s'additionnent), une option précédente d'une alternative ou une `&préparation`. +- **Préparations utilisées en entier** : si une section utilise une préparation intermédiaire sans quantité (`Étaler la &pâte`), proportions et pourcentages (`@sel{2 g / 100 g &pâte}`, `@sucre{5% &pâte}`) se calculent sur la masse totale de la section qui la produit, à condition qu'elle seule la consomme. +- **Références et composites** : proportions et pourcentages fonctionnent sur les références à une préparation maison (`&bouillon{250 ml / 100 g @&riz}`), mais pas encore sur un parent composite (`@œufs{1}<@boîte{1 / 100 g @&farine}`). +- **Mise à l'échelle** : changer l'échelle d'une recette recalcule les proportions à partir des cibles mises à l'échelle (sauf si la cible est figée avec `@=`). Le modificateur `=` sur la proportion elle-même est refusé. ## Règles de calcul des masses diff --git a/packages/docs/src/content/docs/fr/docs/reference/syntax/target-states.mdx b/packages/docs/src/content/docs/fr/docs/reference/syntax/target-states.mdx index ef68df61..9e24b8b5 100644 --- a/packages/docs/src/content/docs/fr/docs/reference/syntax/target-states.mdx +++ b/packages/docs/src/content/docs/fr/docs/reference/syntax/target-states.mdx @@ -9,7 +9,7 @@ import Term from '../../../../../../components/Term.astro'; -Une durée donne un ordre d'idée ; c'est rarement elle qui dit au cuisinier que c'est prêt. Une crème anglaise est cuite quand elle nappe la cuillère, des jaunes blanchis quand ils retombent en ruban, un beurre quand il sent la noisette. Un note ce repère avec `={...}` : l'état à atteindre, celui que le cuisinier doit savoir reconnaître. +Un minuteur donne un ordre d'idée ; c'est rarement lui qui dit au cuisinier que la préparation est prête. Une crème anglaise est cuite quand elle nappe la cuillère, des jaunes blanchis quand ils retombent en ruban, un beurre quand il sent la noisette. Un note ce repère visuel ou sensoriel avec `={...}` : ```gram Fouetter @jaunes{4} avec @sucre{80 g} jusqu'au ={ruban}. @@ -19,50 +19,44 @@ Dès que le beurre est ={noisette}, retirer la #poêle du feu. Les blancs doivent être ={fermes} avant d'y verser le @sucre{50 g}. ``` -Un état attendu se place là où la phrase le demande. On le trouve le plus souvent en fin d'étape, puisqu'il marque en général ce qui la termine, mais il peut aussi ouvrir l'étape ou se glisser au milieu, et aucune formule n'est imposée : « jusqu'à », « dès que », « quand », ou rien du tout. On n'écrit entre les accolades que l'état lui-même et on laisse les autres mots dans la phrase : l'étape se lit toujours aussi naturellement, et l'état ressort tout seul dans chaque vue. +Placez l'état attendu là où la phrase le demande — en fin, début ou milieu d'étape — sans formule imposée (« jusqu'à », « dès que », « quand », ou rien du tout). Ne placez entre les accolades que l'état lui-même, en laissant les mots de liaison dans la phrase : l'étape reste fluide tout en mettant le repère en valeur dans chaque vue. ## Comment le vérifier -Une précision entre parenthèses, collée à l'accolade fermante, dit comment reconnaître que l'état est atteint : le test, l'indice auquel un débutant peut se fier. +Une précision entre parenthèses, collée à l'accolade fermante, indique comment contrôler que l'état est atteint — le test concret auquel se fier : ```gram Cuire sur ^{feu doux} en remuant jusqu'à ={la nappe}(un doigt passé sur le dos de la cuillère laisse une trace nette) ->&crème anglaise{} ``` -L'état et sa précision s'affichent toujours, à l'écran comme sur papier, et `gram cook` les rappelle sous l'étape. Ce sont des mots pour le cuisinier, dans la langue de la recette : Gram les garde tels quels et ne les interprète jamais. +L'état et sa précision sont toujours affichés, à l'écran comme sur papier, et `gram cook` les met en avant sous l'étape. Gram les conserve tels quels dans la langue de la recette, sans chercher à les interpréter. -Comme pour les ingrédients, le matériel et les températures, la parenthèse ouvrante reste collée à la `}` sur la même ligne : avec un espace (`={bec d'oiseau} (environ 5 min)`), elle reste du texte ordinaire dans la phrase. +Comme pour les ingrédients, le matériel et les températures, la parenthèse ouvrante reste collée à `}` sur la même ligne : avec un espace (`={bec d'oiseau} (environ 5 min)`), elle redevient du texte ordinaire. ## Avec une durée et une température -Une étape peut porter un état attendu à côté d'un minuteur et d'une température. Le minuteur donne l'estimation qui sert au planning ; l'état, lui, dit quand s'arrêter devant le fourneau. +Une étape peut associer un état attendu à un minuteur et une température. Le minuteur donne l'estimation pour le planning ; l'état dit quand arrêter la cuisson. ```gram Cuire à ^{82°C}(à cœur) pendant ~{8 min}, jusqu'à ={la nappe}. ``` :::tip[Ce qui n'a pas sa place entre les accolades] -Un état attendu décrit un état, jamais une mesure : -- une température à atteindre est une [température](/fr/docs/reference/syntax/temperatures/) avec sa précision : `^{63°C}(à cœur)` ; -- une durée est un [minuteur](/fr/docs/reference/syntax/times/) : `~{5 min}` ; -- un état attendu ne change jamais d'échelle : `={doublé de volume}` reste tel quel, quel que soit le nombre de portions. +Un état attendu décrit un état sensoriel, jamais une mesure : +- une température cible est une [température](/fr/docs/reference/syntax/temperatures/) avec sa précision (`^{63°C}(à cœur)`) ; +- une durée est un [minuteur](/fr/docs/reference/syntax/times/) (`~{5 min}`) ; +- un état attendu ne change jamais d'échelle (`={doublé de volume}` reste tel quel quel que soit le nombre de portions). ::: ## Plusieurs états dans une étape -Une étape peut en contenir plusieurs. Chacun s'affiche à sa place dans la phrase, `gram cook` les rappelle l'un sous l'autre et, quand un minuteur de l'étape sonne, invite à les vérifier tous. +Une étape peut contenir plusieurs états attendus. Chacun s'affiche à sa place dans le texte, et `gram cook` les regroupe pour vous rappeler de les vérifier quand le minuteur de l'étape sonne. ```gram Pétrir jusqu'à ce que la pâte soit ={lisse} et ={élastique}(elle se rétracte doucement quand on l'étire). ``` -Comme pour les minuteurs et les températures, une étape courte se suit plus facilement. Si chaque état conclut un geste différent, mieux vaut en faire deux étapes, chacune avec son état. Plutôt que : - -```gram -Faire fondre le @beurre{50 g} jusqu'à ={noisette}, puis le laisser refroidir jusqu'à ce qu'il soit ={tiède} et y incorporer les @œufs{2}. -``` - -écrivez : +Comme pour les minuteurs et les températures, les étapes courtes sont plus faciles à suivre. Si deux états concluent des actions distinctes, séparez-les en deux étapes plutôt que de les enchaîner : ```gram Faire fondre le @beurre{50 g} jusqu'à ={noisette}. @@ -72,13 +66,9 @@ Le laisser refroidir jusqu'à ce qu'il soit ={tiède}, puis y incorporer les @œ ## Erreurs -Un état attendu doit contenir des mots entre ses accolades, fermées sur la même ligne. `={}` et `={ruban` (sans `}`) sont des erreurs de syntaxe, signalées dans l'éditeur à l'endroit où elles commencent. +Un état attendu ne peut pas être vide et doit se refermer sur la même ligne. `={}` ou `={ruban` (sans `}`) provoquent une erreur de syntaxe pointant sur l'ouverture. -Un `=` qui ne touche pas une accolade reste du texte, et le modificateur de quantité fixe `@=sel{1 c.à.c}` ne change pas. - -## Dans la recette compilée - -Chaque état attendu devient un jeton `checkpoint` dans le `content` de l'étape, à l'endroit où il est écrit : `{ "type": "checkpoint", "state": "ruban", "note": "…" }`, avec `note` seulement s'il y en a une. Voir [Formats de données](/fr/docs/reference/api/data-formats/). +Un `=` qui ne précède pas `{` reste du texte ordinaire, et le modificateur de quantité fixe `@=sel{1 c.à.c}` reste inchangé. ## Pour aller plus loin @@ -98,4 +88,9 @@ Chaque état attendu devient un jeton `checkpoint` dans le `content` de l'étape description="Un aide-mémoire visuel de tous les marqueurs." href="/fr/docs/reference/syntax/cheatsheet/" /> + 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 93320f8c..5f96b24d 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 @@ -50,7 +50,7 @@ Lorsque le compilateur Gram traite un élément `^température` : ## 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. +Ajoutez une précision entre parenthèses juste après l'accolade fermante pour indiquer le mode du four, le point de mesure ou une condition de cuisson. Cela fonctionne sur les températures exactes comme sémantiques, nommées ou non, à la manière d'une préparation d'ingrédient : ```gram Préchauffer le #four à ^{160°C}(chaleur tournante). @@ -60,9 +60,9 @@ 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. +La précision s'affiche toujours à côté de la température, à l'écran comme sur papier, et reste telle qu'écrite dans la langue de la recette, sans être interprétée par Gram. -Comme pour les ingrédients et le matériel, la parenthèse ouvrante reste collée à la `}` sur la même ligne : avec un espace (`^{180°C} (four bien chaud)`), elle reste du texte ordinaire dans la phrase. +Comme pour les ingrédients et le matériel, gardez la parenthèse ouvrante collée à `}` sur la même ligne : avec un espace (`^{180°C} (four bien chaud)`), elle redevient du texte ordinaire. ## Gestion des erreurs diff --git a/packages/docs/src/content/docs/fr/docs/reference/syntax/times.mdx b/packages/docs/src/content/docs/fr/docs/reference/syntax/times.mdx index e1e84561..62843977 100644 --- a/packages/docs/src/content/docs/fr/docs/reference/syntax/times.mdx +++ b/packages/docs/src/content/docs/fr/docs/reference/syntax/times.mdx @@ -13,7 +13,7 @@ Les minuteurs (`~minuteur`) et les durées se déclarent à l'aide du symbole `~ ## Déclaration de base -Un `~minuteur` **doit** préciser son unité entre les accolades. Les mots ne sont pas des durées : `~{environ 10 minutes}` ou `~{une demi-heure}` ne sont pas lus, et le compilateur le signale. +Un `~minuteur` **doit** préciser son unité entre les accolades. Les durées en texte libre (`~{environ 10 minutes}`, `~{une demi-heure}`) ne sont pas prises en charge et déclenchent un avertissement du compilateur. ```gram Cuire pendant ~{25 min}. @@ -29,14 +29,14 @@ Cuire pendant ~{25 min}. La notation abrégée `m` ou le terme `minutes` sont automatiquement normalisés en `min` par le compilateur. ::: -La résolution des unités s'appuie sur le dictionnaire temporel multilingue de Gram. Les alias localisés ci-dessous sont donc reconnus quelle que soit la langue de la recette : `~{2j}` équivaut à `~{2d}`, et `~{1 hr}` se lit partout. +Ces unités s'appuient sur le dictionnaire temporel multilingue de Gram, ce qui permet d'utiliser des alias localisés quelle que soit la langue de la recette (`~{2j}` équivaut à `~{2d}`, et `~{1 hr}` fonctionne partout). ## Écrire une durée -Une durée s'écrit comme dans un livre de cuisine, en français, en anglais (américain ou britannique) ou en notation internationale. Les espaces ne comptent pas : `~{1h30}`, `~{1 h 30}`, `~{1 heure 30}` et `~{1 hr. 30 mins}` valent tous 1 heure 30. +Écrivez les durées comme dans une recette : les espaces importent peu (`~{1h30}`, `~{1 h 30}`, `~{1 heure 30}` valent tous 1 h 30 min), et toutes les vues les affichent de façon uniforme dans la langue du lecteur. ```gram Laisser frémir le @bouillon{2 l} pendant ~{1h30}. @@ -46,66 +46,24 @@ Laisser lever la @pâte{} ~_{1 heure 30}. Affiner le @jambon{1} à la cave ~_{2 j 4 h}. ``` -Quelle que soit l'écriture, les vues affichent toutes les durées de la même façon, dans la langue du lecteur (`1 h 30 min`). Dans l'éditeur, survoler un minuteur montre comment Gram l'a lu. - -### Plusieurs unités - -Une durée peut enchaîner plusieurs unités, reliées au besoin par un `+` : `~{1h30min}`, `~{1 h 30 min}`, `~{2 j 4 h}`, `~{1h + 30min}`. - -- Les unités vont **de la plus grande à la plus petite**, chacune une seule fois : `~{30min 1h}` et `~{1h 2h}` ne sont pas lus. -- Le **dernier nombre peut se passer d'unité** juste après les heures (il compte alors des minutes) ou les minutes (des secondes), s'il est entier et inférieur à 60 : `~{1h30}`, `~{2min30}`. `~{1h75}` n'est pas lu : écrivez `~{2h15}`. -- **Décimales et fractions** ne valent que pour une durée d'une seule unité : `~{1,5 h}`, `~{1½ h}`, `~{1 1/2 heure}`. `~{1,5h30}` n'est pas lu. - -### Notation horaire - -Une horloge en trois parties se lit toujours : `~{1:30:00}` fait 1 heure 30, `~{0:04:30}` 4 minutes 30. En deux parties, une unité indique ce que compte la première : `~{1:30 h}` fait 1 heure 30, `~{4:30 min}` 4 minutes 30 secondes. - -```gram -Cuire le @pudding{1} à la vapeur ~_{1:30 h}. -``` - -`~{1:30}` seul n'est pas lu : est-ce 1 heure 30 ou 1 minute 30 ? Écrivez `~{1h30}` ou `~{1:30 min}`. Après la première, chaque partie a deux chiffres et reste sous 60. - -### Notation en primes - -Courante dans les recettes italiennes et françaises, `'` compte les minutes et `"` les secondes : `~{5'}`, `~{5'30"}`, `~{45"}`, `~{90'}`. Un dernier nombre sans prime compte des secondes (`~{5'30}`). Les primes ne comptent que des minutes et des secondes, en nombres entiers. - -```gram -Cuire les @spaghetti{500 g} ~{9'}, puis les faire sauter ~{1'30"}. -``` - -Les variantes typographiques se lisent aussi : l'apostrophe courbe `’` que les traitements de texte substituent à `'`, les primes `′` et `″`, et deux apostrophes `''` pour les secondes. - -### Nombres décimaux - -Une durée peut être décimale, avec une virgule ou un point (`~{1,5 h}`, `~{1.5 h}` ; voir les [nombres décimaux](/fr/docs/reference/syntax/ingredients/#nombres-décimaux)). +- **Plusieurs unités** (`~{1h30min}`, `~{2 j 4 h}`, `~{1h + 30min}`) : rangez les unités de la plus grande à la plus petite, chacune une seule fois. Un dernier nombre sans unité est accepté juste après les heures (minutes) ou les minutes (secondes), s'il est entier et inférieur à 60 (`~{1h30}`, `~{2min30}`, mais pas `~{1h75}`). Décimales et fractions ne s'emploient que sur une durée d'une seule unité (`~{1,5 h}`, `~{1½ h}`, pas `~{1,5h30}`). +- **Notation horaire** (`~{1:30:00}`, `~{1:30 h}`, `~{4:30 min}`) : trois parties sont toujours comprises (`hh:mm:ss`) ; deux parties exigent une unité pour lever l'ambiguïté entre heures et minutes. +- **Notation en primes** (`~{5'}`, `~{5'30"}`, `~{45"}`) : `'` compte des minutes entières et `"` des secondes entières (les variantes typographiques `’`, `′`, `″` et `''` sont aussi acceptées). +- **Nombres décimaux** (`~{1,5 h}`, `~{1.5 h}`) : virgule et point sont acceptés (voir les [nombres décimaux](/fr/docs/reference/syntax/ingredients/#nombres-décimaux)). :::caution -Une décimale est une fraction de l'unité, pas des minutes : `~{1,30 h}` (ou `~{1.30 h}`) fait 1 heure 18, et non 1 h 30. Pour une heure et demie, écrivez `~{1h30}` ou `~{1,5 h}`. +Une décimale représente une fraction de l'unité, pas des minutes : `~{1,30 h}` vaut 1 h 18 min, et non 1 h 30 min. Écrivez `~{1h30}` ou `~{1,5 h}` pour une heure et demie. ::: -### Ce que Gram lit, en un coup d'œil - -| Écriture | Lecture | -| :--- | :--- | -| `~{90min}`, `~{1,5 h}`, `~{1.5 h}`, `~{1½ h}`, `~{1 1/2 heure}` | 1 h 30 min | -| `~{1h30}`, `~{1 h 30}`, `~{1 heure 30}`, `~{1 h 30 min}`, `~{1h + 30min}` | 1 h 30 min | -| `~{1 hr 30 mins}`, `~{1 hour 30 minutes}`, `~{1h30m}`, `~{1:30 h}`, `~{1:30:00}` | 1 h 30 min | -| `~{4min30}`, `~{4:30 min}`, `~{4'30"}`, `~{0:04:30}` | 4 min 30 s | -| `~{2 j 4 h}`, `~{2 d 4 h}` | 2 jours 4 heures | -| `~{45 min - 1 h}`, `~{1h30-2h}`, `~{5-7'}` | une fourchette (voir plus bas) | - -| Non lu | Pourquoi | À écrire plutôt | +| Accepté | Refusé | À écrire plutôt | | :--- | :--- | :--- | -| `~{1:30}` | des heures ou des minutes ? | `~{1h30}` ou `~{1:30 min}` | -| `~{1h75}` | 60 minutes ou plus après les heures | `~{2h15}` | -| `~{30min 1h}` | unités de la plus petite à la plus grande | `~{1h30}` | -| `~{1,5h30}` | une décimale dans une durée à plusieurs unités | `~{1h30}` ou `~{1,5 h}` | -| `~{une demi-heure}`, `~{2 à 3 heures}` | des mots | `~{30min}`, `~{2-3h}` | -| `~{2 * 2 min}` | une multiplication | le total, `~{4min}` | -| `~{PT1H30M}` | ISO 8601, une notation pour les machines | `~{1h30}` | +| `~{1h30}`, `~{1 heure 30}`, `~{1h + 30min}` | `~{1:30}` *(ambigu)* | `~{1h30}` ou `~{1:30 min}` | +| `~{1:30 h}`, `~{1:30:00}` | `~{1h75}` *(≥ 60 min)* | `~{2h15}` | +| `~{4'30"}`, `~{4min30}` | `~{30min 1h}` *(mauvais ordre)* | `~{1h30}` | +| `~{1,5 h}`, `~{1.5 h}`, `~{1½ h}` | `~{1,5h30}` *(décimale composée)* | `~{1h30}` ou `~{1,5 h}` | +| `~{45 min - 1 h}`, `~{1h30-2h}` | `~{une demi-heure}` *(en lettres)* | `~{30min}` | -Une durée que Gram ne lit pas déclenche un [avertissement](#gestion-des-erreurs) assorti d'une proposition, et ne compte pas dans le temps total : Gram ne devine jamais. +Une durée non reconnue déclenche un avertissement `INVALID_DURATION` avec une suggestion de correction et n'est pas comptabilisée dans le temps total. ### Noms de minuteur Vous pouvez assigner un identifiant textuel à un `~minuteur`. Cette fonctionnalité est particulièrement précieuse pour les tâches de fond : lorsque plusieurs minuteurs tournent en parallèle (une pâte en fermentation pendant qu'un bouillon mijote), leur attribuer un nom permet aux interfaces et aux fiches de production de suivre leur progression simultanée sans ambiguïté. @@ -125,7 +83,7 @@ Laisser la pâte reposer au frais ~_{12-24h}. Rôtir le poulet pendant ~{40-50 min}. ``` -Chaque côté d'une fourchette suit les règles précédentes, et la durée la plus courte vient en premier. Le côté gauche ne reprend l'unité du côté droit que s'il se réduit à un nombre et que le côté droit n'a qu'une unité : `~{1-2 h}`, `~{5-7'}`, `~{1,5-2 h}` (ou deux horloges suivies d'une unité : `~{1:30-2:00 h}`). Sinon, écrivez les deux côtés en entier (depuis la 1.5.0) : +Chaque côté d'une fourchette suit les règles précédentes, la durée la plus courte en premier. On ne peut omettre l'unité à gauche que s'il s'agit d'un simple nombre et que le côté droit ne comporte qu'une seule unité (`~{1-2 h}`, `~{5-7'}`, `~{1:30-2:00 h}`). Pour des bornes composées, écrivez les deux côtés en entier () : ```gram Braiser les @joues de bœuf{1 kg} ~_{2h30-3h}. @@ -133,7 +91,7 @@ Braiser les @joues de bœuf{1 kg} ~_{2h30-3h}. Pocher les @poires{4} ~{45 min - 1 h}. ``` -`~{1-2h30}` n'est pas lu (le côté gauche vaut-il 1 heure ou 1 heure 30 ?) : écrivez `~{1h-2h30}`. `~{2-1 h}` non plus : écrivez `~{1-2 h}`. +Les fourchettes ambiguës ou inversées comme `~{1-2h30}` ou `~{2-1 h}` sont refusées : écrivez `~{1h-2h30}` ou `~{1-2 h}`. L'interprétation d'une fourchette diffère fondamentalement selon la nature du minuteur : @@ -148,17 +106,20 @@ Les champs dépréciés de la recette compilée (`steps[].timings`, `steps[].bac ### Temps proportionnels -Certains temps suivent un poids : 15 minutes par 500 g de rôti, 4 minutes par côtelette. Écrivez la durée, une barre, puis la quantité d'un ingrédient écrit plus tôt dans la section, comme dans une [proportion avec unités](/fr/docs/reference/syntax/relative-quantities/#proportions-avec-unités) : +Certains temps suivent un poids ou un nombre de pièces : 15 minutes par 500 g de rôti, 4 minutes par côtelette. Écrivez la durée, une barre oblique, puis la quantité de référence d'un ingrédient déclaré plus tôt dans la section, sur le modèle d'une [proportion avec unités](/fr/docs/reference/syntax/relative-quantities/#proportions-avec-unités) : ```gram -Assaisonner le @roti{1,2 kg} et le rôtir ~{15 min / 500 g @&roti}. // 36 min +Assaisonner le @rôti{1,2 kg} et le rôtir ~{15 min / 500 g @&rôti}. // 36 min -Braiser l'@epaule{2 kg} ~_{1:30 h / 1 kg @&epaule}. // 3 h +Braiser l'@épaule{2 kg} ~_{1:30 h / 1 kg @&épaule}. // 3 h -Poêler les @cotelettes{4} ~{4 min / @&cotelettes}. // 16 min +Poêler les @côtelettes{4} ~{4 min / @&côtelettes}. // 16 min ``` -La durée prend toutes les formes vues plus haut (`1h30`, `1:30 h`, une fourchette comme `15-20 min`), la quantité de la cible un seul nombre. Un temps par pièce compté sur un poids (`~{4 min / @&cotelettes}` avec `@cotelettes{800 g}`) passe par le `unit_weight` de la base d'ingrédients, et reste hors du compte, avec un avertissement, s'il manque. Mettre la recette à l'échelle recalcule le temps, et le planning avec. Un multiplicateur après un temps proportionnel (`~{15 min / 500 g @&roti * 2}`) n'est pas encore lu, pas plus qu'une ancre de section proportionnelle. +- La durée accepte toutes les écritures ci-dessus (`1h30`, `1:30 h`, une fourchette comme `15-20 min`), mais la quantité cible doit être un nombre simple. +- Un temps par pièce appliqué à un poids (`~{4 min / @&côtelettes}` avec `@côtelettes{800 g}`) utilise le `unit_weight` de votre base d'ingrédients ; s'il manque, le minuteur reste non calculé avec un avertissement. +- La mise à l'échelle recalcule automatiquement ces durées et met le planning à jour. +- Les multiplicateurs (`~{15 min / 500 g @&rôti * 2}`) et les ancres de section proportionnelles ne sont pas encore pris en charge. ## Actif vs passif @@ -281,11 +242,11 @@ Chaque journée de travail est conçue pour s'inscrire dans une amplitude de 24 ### Syntaxe stricte -L'annotation `~{...}` d'un titre de section exige une durée **strictement négative**. Puisqu'il s'agit d'une anticipation, une valeur positive ou nulle n'a pas de sens : +L'annotation `~{...}` d'un titre de section exige une durée **strictement négative** : - Un signe moins `-` **obligatoire** en préfixe. -- Une durée non nulle, écrite comme un minuteur (voir [Écrire une durée](#écrire-une-durée)), en jours, heures et minutes (plusieurs unités et notation horaire depuis la 1.5.0). -- Une seule durée : une ancre n'est jamais une fourchette et ne compte jamais de secondes. +- Une durée non nulle en jours, heures ou minutes (formes composées et horaires prises en charge depuis la 1.5.0 ; voir [Écrire une durée](#écrire-une-durée)). +- Une durée simple : une ancre n'accepte ni fourchette ni secondes. ```gram ## Pâte feuilletée ~{-2j} @@ -299,15 +260,9 @@ Pétrir la @farine{500 g}. ## Ganache ~{-1h30} Verser la @crème{200 ml} sur le @chocolat{200 g}. - -## Crème ~{-1:30 h} - -Fouetter les @jaunes{4} avec le @sucre{80 g}. ``` -Une ancre écrite avec des jours reste en jours (`~{-1j 12h}` fait un jour et demi et ouvre une journée de travail) ; sinon, elle compte dans sa plus petite unité (`~{-1h30}` fait 90 minutes, `~{-1:30 h}` aussi). - -Les mentions en texte libre (`~{la veille}`), les valeurs positives (`~{2h}`) ou nulles (`~{0h}`) ne sont pas permises. Pour préserver la compatibilité ascendante, les recettes existantes comportant ces formes compilent toujours, mais font l'objet d'un avertissement. +Les mentions en texte libre (`~{la veille}`), les valeurs positives (`~{2h}`) ou nulles (`~{0h}`) sont invalides et génèrent des avertissements du compilateur. L'unité est résolue via le même dictionnaire multilingue que `~minuteur` : `j`, `jour` et `jours` sont pleinement reconnus comme alias de l'unité canonique `d` (jour). @@ -321,8 +276,8 @@ Pour garantir un ordonnancement déterministe, le compilateur valide minutieusem - **Unité invalide (*Invalid Unit*)** (`~minuteur`) : Si l'unité ne figure pas dans le dictionnaire temporel (ex. : `~{30 années-lumière}`), il émet `INVALID_UNIT`. - **Unité manquante (*Missing Unit*)** (rétroplanning de section) : Les mentions telles que `~{-2}`, `~{la veille}`, `~{2h}` ou `~{0h}` déclenchent `MISSING_UNIT`. - **Unité invalide (*Invalid Unit*)** (rétroplanning de section) : Une unité non reconnue déclenche `INVALID_UNIT`. -- **Durée illisible (*Invalid Duration*)** *(Depuis la 1.5.0)* : Une durée d'une forme que Gram ne lit pas (`~{1:30}`, `~{1h75}`, `~{30min 1h}`, `~{1-2h30}`, `~{une demi-heure}`, ou une fourchette ou des secondes dans une ancre), déclenche `INVALID_DURATION`. Le message explique pourquoi et propose une écriture ; le minuteur ne compte pas dans le temps total, et la section n'est pas ancrée. Voir [Écrire une durée](#écrire-une-durée). -- **Nombre ambigu (*Ambiguous Number*)** *(Depuis la 1.5.0)* : Une virgule suivie d'exactement trois chiffres (`~{1,000 min}`, `~{-1,000h}`) se lit comme une décimale, soit une minute ou une heure, et déclenche `AMBIGUOUS_NUMBER` au cas où mille était voulu. +- **Durée invalide (*Invalid Duration*)** *(Depuis la 1.5.0)* : Une écriture non reconnue ou ambiguë (`~{1:30}`, `~{1h75}`, `~{30min 1h}`, `~{1-2h30}`, `~{une demi-heure}`, ou une fourchette/des secondes dans une ancre) déclenche `INVALID_DURATION` avec une suggestion de correction ; le minuteur est exclu du temps total et l'ancre est ignorée. +- **Nombre ambigu (*Ambiguous Number*)** *(Depuis la 1.5.0)* : Une virgule suivie de trois chiffres (`~{1,000 min}`, `~{-1,000h}`) est interprétée comme une décimale (`1`) et déclenche `AMBIGUOUS_NUMBER`. - **Paradoxe temporel (*Time Paradox*)** : Si une ancre de rétroplanning entre en contradiction avec l'ordre logique d'une dépendance (ex. : une section ancrée à `-10 min` requise par une section ancrée à `-1 h`), le compilateur émet `TIME_PARADOX`. - **Embouteillage (*Track Contention*)** : Si des minuteurs passifs concurrents sur une même piste nommée ne peuvent être ordonnancés sans décalage temporel, le compilateur prévient de ce réaménagement via `TRACK_CONTENTION`. - **Journée qui déborde (*Day overflow*)** *(Depuis la 1.4.0)* : Si un long temps passif repousse le travail d'une journée au-delà de sa fenêtre maximale de 24 heures, le compilateur signale un `DAY_OVERFLOW` (suggérant d'ancrer la section un jour plus tôt ou d'ajuster la durée). diff --git a/packages/docs/src/content/docs/fr/docs/reference/tooling/cli.mdx b/packages/docs/src/content/docs/fr/docs/reference/tooling/cli.mdx index 7c9282be..006757db 100644 --- a/packages/docs/src/content/docs/fr/docs/reference/tooling/cli.mdx +++ b/packages/docs/src/content/docs/fr/docs/reference/tooling/cli.mdx @@ -112,7 +112,7 @@ gram view brioche.gram --scale farine=300g # Proportions ajustées pour farine ``` - Prend en charge la pagination automatique pour les recettes longues. - Affiche la synthèse nutritionnelle, les durées et la liste d'ingrédients à cocher. -- Les minuteurs et les durées de l'en-tête s'écrivent comme dans toutes les vues (`~{1h5}` s'affiche `1 h 5 min`, `~{25min 5s}` s'affiche `25 min 5 s`) ; un minuteur que Gram ne lit pas reste tel qu'écrit. +- Les minuteurs et les durées de l'en-tête utilisent le même formatage que dans toutes les vues (`~{1h5}` s'affiche `1 h 5 min`, `~{25min 5s}` s'affiche `25 min 5 s`) ; les minuteurs non reconnus restent tels qu'écrits. - Les étapes sont numérotées dans chaque section, comme dans toutes les vues de la recette. Les quantités sont reprises dans le texte des étapes, à côté de chaque ingrédient (`farine (200 g)`) ; `--step-quantities hide` les retire. - Le temps d'attente passif apparaît dans l'en-tête de la recette, et les fractions courantes telles que `1/4 tsp` restent sous forme fractionnaire dans la liste de courses. - Le drapeau `--scale` ajuste l'intégralité des quantités d'ingrédients (liste de courses et rappels au sein des étapes). @@ -176,12 +176,12 @@ gram shop "menus/*.gram" --scale 4 # Préparation par lots × 4 - Lorsqu'un motif de recherche ou plusieurs fichiers sont fournis, les recettes importées (via `@use`) par d'autres fichiers du lot sont exclues par défaut pour éviter les doublons sur la liste de courses consolidée. Spécifiez `--include-modules` pour les inclure malgré tout. - Options : `--format terminal|md|json`, `--output/-o `, `--scale `, `--db`, `--skip-db`, `--include-modules`, ainsi que les [réglages](#les-réglages-en-ligne-de-commande) de l'analyseur. -Avec `--format json`, chaque article garde `qty`, la quantité telle qu'on la lit (`2 cup + 3 tbsp`, `3,9 kg`), et la donne aussi en nombres, pour qu'un script s'en serve directement : -- `amount` est un nombre brut, dans l'unité qu'affiche `qty` (`3.9` avec `"unit": "kg"`), jamais écrit avec une virgule. Il vaut `null` si l'ingrédient n'a pas de quantité chiffrée, ou si ses unités ne s'additionnent pas. -- `unit` est l'unité canonique (`tbsp` pour `tablespoons` comme pour `c. à s.`), `null` pour un nombre de pièces (`@oeufs{4}`). Tasses et cuillères s'additionnent dans la plus petite unité écrite : `2 cup + 3 tbsp` donne `"amount": 35, "unit": "tbsp"`. -- `range` donne les bornes d'une fourchette (`{ "min": 13, "max": 14 }`) ; `amount` en est alors le milieu. -- `parts` liste les quantités dont les unités ne s'additionnent pas, comme `qty` les écrit (`1 1/2 cups + 70 g` donne `[{ "amount": 1.5, "unit": "cup" }, { "amount": 70, "unit": "g" }]`). -- `unresolved` liste ce qui n'a pas pu être chiffré (`(2% of pâte ❓)`) : ce n'est jamais compté dans `amount`. +Avec `--format json`, chaque article conserve le texte lisible `qty` (`2 cup + 3 tbsp`, `3,9 kg`) ainsi que des champs numériques structurés pour les scripts : +- `amount` : nombre brut dans l'unité de `qty` (`3.9` avec `"unit": "kg"`), toujours avec un point décimal ; vaut `null` si l'ingrédient n'a pas de quantité ou mêle des unités incompatibles. +- `unit` : unité canonique (`tbsp` pour `tablespoons` comme pour `c. à s.`), ou `null` pour un comptage (`@œufs{4}`). Les échelles compatibles s'additionnent dans la plus petite unité écrite (`2 cup + 3 tbsp` donne `"amount": 35, "unit": "tbsp"`). +- `range` : bornes `{ min, max }` pour une fourchette (`amount` porte alors le milieu). +- `parts` : tableau `{ amount, unit }` lorsque des unités incompatibles ne peuvent pas s'additionner (`1 1/2 cups + 70 g` donne `[{ "amount": 1.5, "unit": "cup" }, { "amount": 70, "unit": "g" }]`). +- `unresolved` : fragments non chiffrables (`(2% de pâte ❓)`), exclus de `amount`. ```json { "id": "sel", "name": "sel", "qty": "3 g + (2% of pâte ❓)", "amount": 3, "unit": "g", "unresolved": ["(2% of pâte ❓)"], "isEstimate": false, "category": "Épices", "recipes": ["brioche"] } diff --git a/packages/docs/src/content/docs/fr/docs/reference/tooling/language-server.mdx b/packages/docs/src/content/docs/fr/docs/reference/tooling/language-server.mdx index 9b4b27dc..5c90f787 100644 --- a/packages/docs/src/content/docs/fr/docs/reference/tooling/language-server.mdx +++ b/packages/docs/src/content/docs/fr/docs/reference/tooling/language-server.mdx @@ -31,26 +31,24 @@ Le Serveur de Langage Gram implémente les capacités standardisées suivantes : | Capacité LSP | Implémentation Gram | |---|---| | **Diagnostics** | Remontée en temps réel des erreurs de syntaxe, des incohérences structurelles (dépendances circulaires) et des avertissements d'ordonnancement (`DAY_OVERFLOW`, `DURATION_OUT_OF_RANGE`, `TRACK_CONTENTION`). | -| **Semantic Tokens** | Coloration sémantique pilotée par l'AST, permettant de distinguer avec précision les modificateurs, unités, températures et ingrédients composites. | -| **Completion** | Autocomplétion contextuelle pour les ingrédients de la base de données, les unités canoniques et les variables intermédiaires. Dans un minuteur (`~{…}`), seules les unités de temps sont proposées. Dans une somme de quantités, les unités reviennent après chaque `+ 2` ou `- 2`. | -| **Hover** | Affiche la composition nutritionnelle et les conversions automatiques volume-masse au survol des ingrédients. Sur un minuteur, montre la durée telle que Gram la lit (`~{1h30}` → `1 h 30 min`) ; sur une ancre de section, l'avance prise par la section et si elle ouvre une journée de travail. Sur une somme de quantités, montre son total et sa masse. | -| **Go to Definition** | Navigation directe depuis une référence intermédiaire (`&ref`) vers sa déclaration source (`->&ref`). | -| **Find References** | Inventaire exhaustif de toutes les utilisations d'une variable intermédiaire donnée à travers la recette. | -| **Rename** | Renommage atomique et sécurisé d'une variable intermédiaire sur l'ensemble du document. | -| **Code Actions** | Suggestions de corrections rapides (*quick fixes* : déclaration d'une variable manquante, conversion d'un volume en masse, réparation d'une somme de quantités). | -| **Document Formatting** | Normalisation syntaxique complète en appliquant les 13 règles canoniques via `@gram-lang/format`. | -| **Inlay Hints** | Affiche la durée totale de la recette en fin de ligne `title:`, calculée selon le planning de mise en place et la résolution des temps passifs (réglages `gram.miseEnPlace` et `gram.rests`). | -| **Code Lens** | Injecte des actions interactives contextuelles au-dessus du document (affichage du panneau nutritionnel). | -| **Document Symbol** | Alimente la vue Plan (*Outline*) de l'éditeur pour une navigation fluide au sein des sections de la recette. | -| **Folding Range** | Permet de replier proprement le frontmatter YAML et les blocs de sections `##`. | +| **Semantic Tokens** | Coloration sémantique pilotée par l'AST pour les modificateurs, unités, températures, opérateurs de proportion (`/`) et ingrédients composites. | +| **Completion** | Autocomplétion contextuelle des ingrédients de la base, unités canoniques et variables intermédiaires. Propose uniquement les unités de temps dans `~{…}`, relance la complétion d'unités après `+` ou `-` dans les sommes, et suggère les cibles `@&` / `&` (et unités de poids après `/`) dans les proportions. | +| **Hover** | Affiche le profil nutritionnel et les conversions volume-masse au survol des ingrédients. Sur un minuteur, indique la durée interprétée (`~{1h30}` → `1 h 30 min`) ; sur une ancre de section, l'anticipation et l'ouverture d'une journée ; sur une somme ou une proportion, le total, la masse ou la raison d'un éventuel refus. | +| **Go to Definition** | Navigation directe depuis une référence intermédiaire (`&ref`, y compris dans une proportion) vers sa déclaration source (`->&ref`). | +| **Find References** | Recherche toutes les utilisations d'une variable intermédiaire à travers le document (proportions comprises). | +| **Rename** | Renommage atomique d'une variable intermédiaire dans tout le fichier (proportions comprises). | +| **Code Actions** | Corrections rapides (*quick fixes* : déclaration d'une variable manquante, conversion volume-masse, correction d'une somme de quantités). | +| **Document Formatting** | Normalisation syntaxique via `@gram-lang/format`. | +| **Inlay Hints** | Affiche la durée totale sur la ligne `title:` (selon `gram.miseEnPlace` et `gram.rests`), ainsi que les valeurs résolues (`= 5`, `= 24 min`) après chaque proportion avec unités ou temps proportionnel. | +| **Code Lens** | Injecte des actions interactives au-dessus du document (affichage du panneau nutritionnel). | +| **Document Symbol** | Alimente la vue Plan (*Outline*) pour naviguer entre les sections. | +| **Folding Range** | Permet de replier le frontmatter YAML et les sections `##`. | -### Sommes de quantités +### Sommes de quantités et proportions + - Sur une [somme de quantités](/fr/docs/reference/syntax/ingredients/#sommes-de-quantités), l'éditeur aide de trois façons : - -- **Le survol** montre le total tel que Gram le lit (`{1 cup + 1 tbsp}` → `= 17 tbsp` ; une somme de plusieurs natures montre ce que donne chacune, `{1 cup - 2 tbsp + 30 g}` → `= 14 tbsp (volume) + 30 g (weight), counted apart`) et, quand la base d'ingrédients sait peser chaque terme, sa masse. Une somme refusée par Gram n'affiche rien de plus que son avertissement. -- **Les Quick Fix** lisent le `data` de l'avertissement, transmis dans celui du diagnostic : insérer le ` + ` entre deux quantités écrites côte à côte (`{1 kg 200 g}`, `INVALID_UNIT`), écrire le résultat que Gram suggère (`{100 g + 10%}` → `{110 g}`, `INVALID_QUANTITY`), ou changer un `oz` placé après un volume en `fl oz` (`OZ_AFTER_VOLUME`). -- **La complétion** propose les unités de chaque terme : après `{1 kg + 2`, les unités reviennent. +- **Sommes de quantités** : le survol affiche le total combiné (`{1 cup + 1 tbsp}` → `= 17 tbsp`) ou le détail par famille d'unités et la masse ; les corrections rapides insèrent le ` + ` manquant (`{1 kg 200 g}`), appliquent le résultat suggéré (`{100 g + 10%}`) ou remplacent `oz` après un volume par `fl oz` ; la complétion d'unités reprend après `+` ou `-`. +- **Proportions avec unités et temps proportionnels** : les *inlay hints* affichent la valeur calculée en ligne (`= 5`, `= 16 g`, `= 24 min`) ; le survol explique les proportions non résolues ; la complétion suggère les cibles `@&`/`&` (et les unités de poids après `/` dans les minuteurs proportionnels) ; la navigation, la recherche de références et le renommage prennent en charge les cibles dans les proportions. ## Réglages diff --git a/packages/docs/src/content/docs/fr/docs/reference/tooling/vscode-extension.mdx b/packages/docs/src/content/docs/fr/docs/reference/tooling/vscode-extension.mdx index 3f7f0623..0b3b5e9b 100644 --- a/packages/docs/src/content/docs/fr/docs/reference/tooling/vscode-extension.mdx +++ b/packages/docs/src/content/docs/fr/docs/reference/tooling/vscode-extension.mdx @@ -85,18 +85,19 @@ Une journée de travail qu'une phase passive prolongée repousse au-delà du cyc ### 4. Gestion intelligente des ingrédients - **Gestion transparente des pluriels** : L'extension associe automatiquement les formes plurielles courantes de votre recette (ex. `@carottes`) aux entrées singulières correspondantes de votre référentiel YAML (`carotte`). Vous conservez ainsi une rédaction naturelle sans générer de faux avertissements. - **Appariement flou (*Fuzzy Matching*)** : En cas de faute de frappe sur un ingrédient, un algorithme basé sur la distance de Levenshtein suggère la correspondance la plus probable via les actions de code (*Quick Fixes*). -- **Informations au survol** : Survolez n'importe quel ingrédient pour inspecter ses valeurs nutritionnelles. Si la base lui associe une masse volumique, le survol convertit instantanément les volumes en masse physique (ex. `1 c.à.s → 15 g`). Survolez un minuteur pour voir comment Gram le lit (`~{1:30 h}` → `1 h 30 min`), ou une ancre de section pour connaître l'avance prise par la section. +- **Informations au survol** : Survolez un ingrédient pour inspecter son profil nutritionnel et les conversions volume-masse (`1 c.à.s → 15 g`). Survolez un minuteur pour voir la durée interprétée (`~{1:30 h}` → `1 h 30 min`), une ancre de section pour connaître son anticipation, ou une somme/proportion pour consulter la valeur calculée. :::tip[Détection automatique de la base de données] L'extension détecte automatiquement le fichier `.gram/ingredients.yaml` présent à la racine de votre espace de travail. Pour les arborescences spécifiques, personnalisez le chemin via `gram.ingredientDatabase.path` dans vos paramètres VS Code. ::: ### 5. Assistance à l'édition & navigation -- **Jetons sémantiques (*Semantic Tokens*)** : La coloration syntaxique s'appuie directement sur l'AST produit par le compilateur plutôt que sur de simples expressions régulières. Les modificateurs, les unités imbriquées et les ingrédients composites (`<@`) sont colorés avec précision selon leur fonction syntaxique. +- **Jetons sémantiques (*Semantic Tokens*)** : La coloration syntaxique s'appuie directement sur l'AST du compilateur. Les modificateurs, unités imbriquées, opérateurs de proportion et ingrédients composites (`<@`) sont colorés selon leur rôle syntaxique. +- **Inlay hints** : Affiche la durée totale de la recette à côté de `title:`, ainsi que les valeurs résolues après les proportions avec unités et temps proportionnels (`= 5`, `= 24 min`). - **Autocomplétion intelligente** : - `@` suggère les ingrédients déclarés dans votre base, en encapsulant automatiquement les dénominations composées entre accolades `{}`. - `&` suggère les variables intermédiaires déclarées en amont (ex. `->&pâte`). - - `{}` suggère les unités canoniques (masse, volume) et leurs alias dès la saisie d'un chiffre ; dans un minuteur (`~{}`), seulement les unités de temps. + - `{}` suggère les unités canoniques (masse, volume) et leurs alias dès la saisie d'un chiffre ; dans un minuteur (`~{}`), seules les unités de temps sont proposées. #### Raccourcis de navigation -- 2.54.0 From b77fb9aeee5dabc7b23786b437a148745b38f56d Mon Sep 17 00:00:00 2001 From: abiwab Date: Wed, 18 Nov 2026 12:44:30 +0100 Subject: [PATCH 02/24] docs: reorganize sidebar into topics and add docs landing page --- packages/docs/astro.config.mjs | 210 ++--- packages/docs/public/llms-full.txt | 96 +-- packages/docs/src/components/DocsHome.astro | 719 ++++++++++++++++++ packages/docs/src/components/Header.astro | 12 +- packages/docs/src/components/Homepage.astro | 8 +- packages/docs/src/components/Sidebar.astro | 163 ++++ packages/docs/src/components/SiteFooter.astro | 4 +- packages/docs/src/components/SiteTitle.astro | 5 +- packages/docs/src/content/docs/docs/index.mdx | 9 + .../docs/docs/reference/syntax/times.mdx | 96 +-- .../docs/src/content/docs/fr/docs/index.mdx | 9 + .../docs/fr/docs/reference/syntax/times.mdx | 96 +-- packages/docs/src/pages/404.astro | 4 +- packages/docs/src/pages/docs/index.astro | 25 - packages/docs/src/pages/en/docs/index.astro | 8 +- packages/docs/src/pages/fr/docs/index.astro | 18 - 16 files changed, 1183 insertions(+), 299 deletions(-) create mode 100644 packages/docs/src/components/DocsHome.astro create mode 100644 packages/docs/src/components/Sidebar.astro create mode 100644 packages/docs/src/content/docs/docs/index.mdx create mode 100644 packages/docs/src/content/docs/fr/docs/index.mdx delete mode 100644 packages/docs/src/pages/docs/index.astro delete mode 100644 packages/docs/src/pages/fr/docs/index.astro diff --git a/packages/docs/astro.config.mjs b/packages/docs/astro.config.mjs index 642b928c..193a8ad2 100644 --- a/packages/docs/astro.config.mjs +++ b/packages/docs/astro.config.mjs @@ -60,7 +60,7 @@ export default defineConfig({ errorOnInconsistentLocale: true, exclude: [ '/play', '/play/', '/fr/play', '/fr/play/', - '/docs', '/docs/', '/fr/docs', '/fr/docs/', '/en/docs', '/en/docs/', + '/en/docs', '/en/docs/', '/blog', '/blog/', '/blog/**', '/fr/blog', '/fr/blog/', '/fr/blog/**' ] }) @@ -72,6 +72,7 @@ export default defineConfig({ ], components: { Footer: './src/components/Footer.astro', + Sidebar: './src/components/Sidebar.astro', SiteTitle: './src/components/SiteTitle.astro', ThemeSelect: './src/components/ThemeSelect.astro' }, @@ -81,104 +82,143 @@ export default defineConfig({ }, sidebar: [ { - label: 'Introduction', - collapsed: false, + label: 'Guides', + translations: { fr: 'Guides' }, items: [ - { label: 'What is Gram?', translations: { fr: "C'est quoi Gram ?" }, slug: 'docs/explanation/philosophy' }, - { label: 'Getting started', translations: { fr: 'Premiers pas' }, slug: 'docs/tutorials/getting-started' }, - { label: 'Your first recipe', translations: { fr: 'Votre première recette' }, slug: 'docs/tutorials/first-recipe' } + { + label: 'Introduction', + collapsed: false, + items: [ + { label: 'Overview', translations: { fr: "Vue d'ensemble" }, slug: 'docs' }, + { label: 'What is Gram?', translations: { fr: "C'est quoi Gram ?" }, slug: 'docs/explanation/philosophy' }, + { label: 'Getting started', translations: { fr: 'Premiers pas' }, slug: 'docs/tutorials/getting-started' }, + { label: 'Your first recipe', translations: { fr: 'Votre première recette' }, slug: 'docs/tutorials/first-recipe' } + ] + }, + { + label: 'How-to guides', + translations: { fr: 'Guides pratiques' }, + collapsed: false, + items: [ + { label: 'Organize modular recipes', translations: { fr: 'Organiser des recettes modulaires' }, slug: 'docs/how-to/organize-modular-recipes' }, + { label: 'Scale recipes dynamically', translations: { fr: 'Ajuster les proportions' }, slug: 'docs/how-to/scale-recipes' }, + { label: 'Plan a meal', translations: { fr: 'Planifier un repas' }, slug: 'docs/how-to/plan-a-meal' }, + { label: 'Generate shopping list', translations: { fr: 'Générer la liste de courses' }, slug: 'docs/how-to/weekly-shopping-list' }, + { label: 'Manage database', translations: { fr: 'Gérer la base de données' }, slug: 'docs/how-to/manage-database' }, + { label: 'Configure AI provider', translations: { fr: "Configurer l'IA" }, slug: 'docs/how-to/configure-ai' } + ] + } ] }, { - label: 'How-to guides', - translations: { fr: 'Guides pratiques' }, - collapsed: false, + label: 'Language', + translations: { fr: 'Syntaxe' }, items: [ - { label: 'Organize modular recipes', translations: { fr: 'Organiser des recettes modulaires' }, slug: 'docs/how-to/organize-modular-recipes', badge: { text: 'v1.2.0', variant: 'default' } }, - { label: 'Scale recipes dynamically', translations: { fr: 'Ajuster les proportions' }, slug: 'docs/how-to/scale-recipes' }, - { label: 'Plan a meal', translations: { fr: 'Planifier un repas' }, slug: 'docs/how-to/plan-a-meal', badge: { text: 'v1.4.0', variant: 'default' } }, - { label: 'Generate shopping list', translations: { fr: 'Générer la liste de courses' }, slug: 'docs/how-to/weekly-shopping-list' }, - { label: 'Configure AI provider', translations: { fr: "Configurer l'IA" }, slug: 'docs/how-to/configure-ai' }, - { label: 'Manage database', translations: { fr: 'Gérer la base de données' }, slug: 'docs/how-to/manage-database' }, - { label: 'How to build a custom UI', translations: { fr: 'Créer une UI personnalisée' }, slug: 'docs/how-to/build-custom-ui' }, - { label: 'Deprecated features', translations: { fr: 'Fonctionnalités dépréciées' }, slug: 'docs/how-to/deprecations' } + { + label: 'Basics', + translations: { fr: 'Bases' }, + collapsed: false, + items: [ + { label: 'Cheatsheet', translations: { fr: 'Antisèche' }, slug: 'docs/reference/syntax/cheatsheet' }, + { label: 'Document structure', translations: { fr: 'Structure du document' }, slug: 'docs/reference/syntax/document-structure' }, + { label: 'Ingredients', translations: { fr: 'Ingrédients' }, slug: 'docs/reference/syntax/ingredients' }, + { label: 'Cookware', translations: { fr: 'Matériel' }, slug: 'docs/reference/syntax/cookware' }, + { label: 'Times & scheduling', translations: { fr: 'Temps & planification' }, slug: 'docs/reference/syntax/times' }, + { label: 'Temperatures', translations: { fr: 'Températures' }, slug: 'docs/reference/syntax/temperatures' }, + { label: 'Target states', translations: { fr: 'États attendus' }, slug: 'docs/reference/syntax/target-states', badge: { text: 'v1.5.0', variant: 'default' } } + ] + }, + { + label: 'Advanced', + translations: { fr: 'Avancé' }, + collapsed: true, + items: [ + { label: 'Relative quantities & ratios', translations: { fr: 'Quantités relatives & proportions' }, slug: 'docs/reference/syntax/relative-quantities' }, + { label: 'Intermediate variables', translations: { fr: 'Variables intermédiaires' }, slug: 'docs/reference/syntax/intermediate-variables' }, + { label: 'Composite ingredients', translations: { fr: 'Ingrédients composites' }, slug: 'docs/reference/syntax/composite-ingredients' }, + { label: 'Module imports', translations: { fr: 'Imports de modules' }, slug: 'docs/reference/syntax/modules' } + ] + } ] }, { - label: 'Language reference', - translations: { fr: 'Référence du langage' }, - collapsed: false, + label: 'Tooling', + translations: { fr: 'Outils' }, items: [ - { label: 'Document structure', translations: { fr: 'Structure du document' }, slug: 'docs/reference/syntax/document-structure' }, - { label: 'Module imports', translations: { fr: 'Imports de modules' }, slug: 'docs/reference/syntax/modules', badge: { text: 'v1.2.0', variant: 'default' } }, - { label: 'Ingredients', translations: { fr: 'Ingrédients' }, slug: 'docs/reference/syntax/ingredients' }, - { label: 'Cookware', translations: { fr: 'Matériel' }, slug: 'docs/reference/syntax/cookware' }, - { label: 'Times', translations: { fr: 'Temps' }, slug: 'docs/reference/syntax/times' }, - { label: 'Temperatures', translations: { fr: 'Températures' }, slug: 'docs/reference/syntax/temperatures' }, - { label: 'Target states', translations: { fr: 'États attendus' }, slug: 'docs/reference/syntax/target-states', badge: { text: 'v1.5.0', variant: 'default' } }, - { label: 'Intermediate variables', translations: { fr: 'Variables intermédiaires' }, slug: 'docs/reference/syntax/intermediate-variables' }, - { label: 'Relative quantities', translations: { fr: 'Quantités relatives' }, slug: 'docs/reference/syntax/relative-quantities' }, - { label: 'Composite ingredients', translations: { fr: 'Ingrédients composites' }, slug: 'docs/reference/syntax/composite-ingredients' }, - { label: 'Cheatsheet', translations: { fr: 'Antisèche' }, slug: 'docs/reference/syntax/cheatsheet' }, - { label: 'Writing Gram programmatically', translations: { fr: 'Génération automatisée de Gram' }, slug: 'docs/reference/syntax/ai-generation-notes' } + { + label: 'CLI & editors', + translations: { fr: 'CLI & éditeurs' }, + collapsed: false, + items: [ + { label: 'CLI commands', translations: { fr: 'Commandes CLI' }, slug: 'docs/reference/tooling/cli' }, + { label: 'VS Code extension', translations: { fr: 'Extension VS Code' }, slug: 'docs/reference/tooling/vscode-extension' }, + { label: 'Language server', slug: 'docs/reference/tooling/language-server' } + ] + }, + { + label: 'Integration & AI', + translations: { fr: 'Intégration & IA' }, + collapsed: false, + items: [ + { label: 'Writing Gram programmatically', translations: { fr: 'Génération automatisée de Gram' }, slug: 'docs/reference/syntax/ai-generation-notes' }, + { label: 'How to build a custom UI', translations: { fr: 'Créer une UI personnalisée' }, slug: 'docs/how-to/build-custom-ui' } + ] + } ] }, { - label: 'Tooling reference', - translations: { fr: 'Référence des outils' }, - collapsed: false, + label: 'Engine & API', + translations: { fr: 'Moteur & API' }, items: [ - { label: 'CLI commands', translations: { fr: 'Commandes CLI' }, slug: 'docs/reference/tooling/cli' }, - { label: 'VS Code extension', translations: { fr: 'Extension VS Code' }, slug: 'docs/reference/tooling/vscode-extension' }, - { label: 'Language server', slug: 'docs/reference/tooling/language-server' } + { + label: 'API reference', + translations: { fr: 'Référence API' }, + collapsed: false, + items: [ + { label: 'Overview', translations: { fr: "Vue d'ensemble" }, slug: 'docs/reference/api' }, + { label: '@gram-lang/parser', slug: 'docs/reference/api/parser' }, + { label: '@gram-lang/modules', slug: 'docs/reference/api/modules' }, + { label: '@gram-lang/kitchen', slug: 'docs/reference/api/kitchen' }, + { label: '@gram-lang/scheduler', slug: 'docs/reference/api/scheduler' }, + { label: '@gram-lang/analyzer', slug: 'docs/reference/api/analyzer' }, + { label: '@gram-lang/renderer', slug: 'docs/reference/api/renderer' }, + { label: '@gram-lang/format', slug: 'docs/reference/api/format' }, + { label: '@gram-lang/i18n', slug: 'docs/reference/api/i18n' }, + { label: 'Data formats', translations: { fr: 'Formats de données' }, slug: 'docs/reference/api/data-formats' }, + { label: 'Warnings', translations: { fr: 'Avertissements' }, slug: 'docs/reference/api/warnings' }, + { label: 'Deprecated features', translations: { fr: 'Fonctionnalités dépréciées' }, slug: 'docs/how-to/deprecations' } + ] + }, + { + label: 'Gram engine', + translations: { fr: 'Moteur Gram' }, + collapsed: true, + items: [ + { label: 'The Gram lifecycle', translations: { fr: 'Cycle de vie' }, slug: 'docs/explanation/engine/lifecycle' }, + { label: 'Parsing & AST', slug: 'docs/explanation/engine/parser' }, + { label: 'Module resolution & composition', translations: { fr: 'Résolution & composition' }, slug: 'docs/explanation/engine/modules' }, + { label: 'Compilation & structure', translations: { fr: 'Compilation & structure' }, slug: 'docs/explanation/engine/kitchen' }, + { label: 'The scheduling engine', translations: { fr: "Le moteur d'ordonnancement" }, slug: 'docs/explanation/engine/scheduler' }, + { label: 'Semantic analysis', translations: { fr: 'Analyse sémantique' }, slug: 'docs/explanation/engine/analyzer' }, + { label: 'Rendering & output', translations: { fr: 'Rendu & sortie' }, slug: 'docs/explanation/engine/renderer' } + ] + }, + { + label: 'Deep dives', + translations: { fr: 'Analyses approfondies' }, + collapsed: true, + items: [ + { label: 'ALAP scheduling', translations: { fr: 'Ordonnancement ALAP' }, slug: 'docs/explanation/alap-scheduling' }, + { label: 'Mass & yield', translations: { fr: 'Masse & rendement' }, slug: 'docs/explanation/mass-and-yield' }, + { label: 'Nutrition', slug: 'docs/explanation/nutrition' }, + { label: 'Shopping lists', translations: { fr: 'Liste de courses' }, slug: 'docs/explanation/shopping-list-aggregation' }, + { label: 'Scaling', translations: { fr: "Ajustement des proportions" }, slug: 'docs/explanation/scaling' }, + { label: 'Planning & run sheet', translations: { fr: 'Planification & plan de marche' }, slug: 'docs/explanation/planning' } + ] + }, + { label: 'Changelog', translations: { fr: 'Changelog' }, slug: 'docs/changelog' } ] - }, - { - label: 'API reference', - translations: { fr: 'Référence API' }, - collapsed: true, - items: [ - { label: 'Overview', translations: { fr: "Vue d'ensemble" }, slug: 'docs/reference/api' }, - { label: '@gram-lang/parser', slug: 'docs/reference/api/parser' }, - { label: '@gram-lang/modules', slug: 'docs/reference/api/modules', badge: { text: 'v1.2.0', variant: 'default' } }, - { label: '@gram-lang/kitchen', slug: 'docs/reference/api/kitchen' }, - { label: '@gram-lang/scheduler', slug: 'docs/reference/api/scheduler', badge: { text: 'v1.4.0', variant: 'default' } }, - { label: '@gram-lang/analyzer', slug: 'docs/reference/api/analyzer' }, - { label: '@gram-lang/renderer', slug: 'docs/reference/api/renderer' }, - { label: '@gram-lang/format', slug: 'docs/reference/api/format' }, - { label: '@gram-lang/i18n', slug: 'docs/reference/api/i18n' }, - { label: 'Data formats', translations: { fr: 'Formats de données' }, slug: 'docs/reference/api/data-formats' }, - { label: 'Warnings', translations: { fr: 'Avertissements' }, slug: 'docs/reference/api/warnings' } - ] - }, - { - label: 'Gram engine', - translations: { fr: 'Moteur Gram' }, - collapsed: true, - items: [ - { label: 'The Gram lifecycle', translations: { fr: 'Cycle de vie' }, slug: 'docs/explanation/engine/lifecycle' }, - { label: 'Parsing & AST', slug: 'docs/explanation/engine/parser' }, - { label: 'Module resolution & composition', translations: { fr: 'Résolution & composition' }, slug: 'docs/explanation/engine/modules', badge: { text: 'v1.2.0', variant: 'default' } }, - { label: 'Compilation & structure', translations: { fr: 'Compilation & structure' }, slug: 'docs/explanation/engine/kitchen' }, - { label: 'The scheduling engine', translations: { fr: "Le moteur d'ordonnancement" }, slug: 'docs/explanation/engine/scheduler', badge: { text: 'v1.4.0', variant: 'default' } }, - { label: 'Semantic analysis', translations: { fr: 'Analyse sémantique' }, slug: 'docs/explanation/engine/analyzer' }, - { label: 'Rendering & output', translations: { fr: 'Rendu & sortie' }, slug: 'docs/explanation/engine/renderer' } - ] - }, - { - label: 'Deep dives', - translations: { fr: 'Analyses approfondies' }, - collapsed: true, - items: [ - { label: 'ALAP scheduling', translations: { fr: 'Ordonnancement ALAP' }, slug: 'docs/explanation/alap-scheduling' }, - { label: 'Mass & yield', translations: { fr: 'Masse & rendement' }, slug: 'docs/explanation/mass-and-yield' }, - { label: 'Nutrition', slug: 'docs/explanation/nutrition' }, - { label: 'Shopping lists', translations: { fr: 'Liste de courses' }, slug: 'docs/explanation/shopping-list-aggregation' }, - { label: 'Scaling', translations: { fr: "Ajustement des proportions" }, slug: 'docs/explanation/scaling' }, - { label: 'Planning & run sheet', translations: { fr: 'Planification & plan de marche' }, slug: 'docs/explanation/planning', badge: { text: 'v1.4.0', variant: 'default' } } - ] - }, - { label: 'Changelog', translations: { fr: 'Changelog' }, slug: 'docs/changelog' } + } ], head: [ { diff --git a/packages/docs/public/llms-full.txt b/packages/docs/public/llms-full.txt index 57333f93..57303a36 100644 --- a/packages/docs/public/llms-full.txt +++ b/packages/docs/public/llms-full.txt @@ -744,6 +744,54 @@ These units resolve through Gram's multi-language time dictionary, so localized | `m` | `min`, `mins`, `minute`, `minutes` | | `s` | `sec`, `secs`, `second`, `seconds` | +## Active vs passive + +The Gram compiler builds a complete execution timeline for each recipe. To achieve realistic scheduling, it distinguishes hands-on kitchen work from autonomous background tasks. + +:::tip[💡 The Golden Rule: Does this step block YOU from starting the next step?] + +| Cook Status | Timer Type | Syntax | Culinary Examples | +| :--- | :--- | :--- | :--- | +| **YES** (Exclusive manual attention required) | **Active** | `~` | *Whisking by hand, stirring risotto, plating* | +| **NO** (Equipment or time does the work) | **Passive** | `~_` | *Oven baking, fermentation, simmering, chilling* | + +::: + +### Active (default) +By default, a `~timer` is active. It requires direct hands-on involvement: the step is **blocking** and demands undivided attention before moving on to subsequent operations. + +```gram +Whisk the @heavy cream{} continuously for ~{5min}. +``` +> ⏱️ **Result:** Adds 5 minutes to **active time**. + +### Passive (`_`) +Add the `_` modifier to designate a passive `~timer`. This represents a **background task**. You initiate the timer (e.g. putting a dish into the oven) and can immediately proceed with subsequent steps. + +```gram +Bake in the #oven for ~_{45min}. + +Meanwhile, prepare the glaze... +``` +> ⏱️ **Result:** Adds 0 minutes to active time, but extends **idle / passive duration** to ensure these 45 minutes elapse before removing the dish. + +### Sequential passive timers (named tracks) +By default, passive timers run concurrently with the rest of the recipe. However, certain background operations sharing equipment cannot physically overlap (e.g. blind-baking a crust for 10 minutes, then lowering the heat and continuing baking for 30 minutes in the same oven). + +To enforce **sequential** execution of passive timers, assign them the **same track name**: + +```gram +Bake in the #oven at 240°C for ~_baking{10min}. + +Lower the heat to 180°C and bake for ~_baking{30min}. +``` + +> ⏱️ **Result:** Because both timers share the track name `baking`, Gram places them on the same background track. The 30-minute timer will only start *after* the 10-minute timer completes. Idle waiting time increases by 40 minutes, while active hands-on time remains zero. + +:::tip[Without a track, overlapping waits are flagged] +Two passive timers that overlap in steps citing the **same cookware** (`#oven` in both) with no track in common are reported by `PASSIVE_OVERLAP_SAME_COOKWARE`: the message suggests a named track. It is only informational, since two trays can share an oven. See [Warnings](/docs/reference/api/warnings/#passive_overlap_same_cookware). +::: + ## Writing a duration *(since v1.5.0)* @@ -832,54 +880,6 @@ Fry the @cutlets{4} ~{4 min / @&cutlets}. // 16 min - Scaling the recipe recalculates proportional times and updates the schedule automatically. - Multipliers (`~{15 min / 500 g @&roast * 2}`) and proportional section anchors are not supported yet. -## Active vs passive - -The Gram compiler builds a complete execution timeline for each recipe. To achieve realistic scheduling, it distinguishes hands-on kitchen work from autonomous background tasks. - -:::tip[💡 The Golden Rule: Does this step block YOU from starting the next step?] - -| Cook Status | Timer Type | Syntax | Culinary Examples | -| :--- | :--- | :--- | :--- | -| **YES** (Exclusive manual attention required) | **Active** | `~` | *Whisking by hand, stirring risotto, plating* | -| **NO** (Equipment or time does the work) | **Passive** | `~_` | *Oven baking, fermentation, simmering, chilling* | - -::: - -### Active (default) -By default, a `~timer` is active. It requires direct hands-on involvement: the step is **blocking** and demands undivided attention before moving on to subsequent operations. - -```gram -Whisk the @heavy cream{} continuously for ~{5min}. -``` -> ⏱️ **Result:** Adds 5 minutes to **active time**. - -### Passive (`_`) -Add the `_` modifier to designate a passive `~timer`. This represents a **background task**. You initiate the timer (e.g. putting a dish into the oven) and can immediately proceed with subsequent steps. - -```gram -Bake in the #oven for ~_{45min}. - -Meanwhile, prepare the glaze... -``` -> ⏱️ **Result:** Adds 0 minutes to active time, but extends **idle / passive duration** to ensure these 45 minutes elapse before removing the dish. - -### Sequential passive timers (named tracks) -By default, passive timers run concurrently with the rest of the recipe. However, certain background operations sharing equipment cannot physically overlap (e.g. blind-baking a crust for 10 minutes, then lowering the heat and continuing baking for 30 minutes in the same oven). - -To enforce **sequential** execution of passive timers, assign them the **same track name**: - -```gram -Bake in the #oven at 240°C for ~_baking{10min}. - -Lower the heat to 180°C and bake for ~_baking{30min}. -``` - -> ⏱️ **Result:** Because both timers share the track name `baking`, Gram places them on the same background track. The 30-minute timer will only start *after* the 10-minute timer completes. Idle waiting time increases by 40 minutes, while active hands-on time remains zero. - -:::tip[Without a track, overlapping waits are flagged] -Two passive timers that overlap in steps citing the **same cookware** (`#oven` in both) with no track in common are reported by `PASSIVE_OVERLAP_SAME_COOKWARE`: the message suggests a named track. It is only informational, since two trays can share an oven. See [Warnings](/docs/reference/api/warnings/#passive_overlap_same_cookware). -::: - ## How time is calculated Behind the scenes, Gram tracks four distinct time metrics to establish realistic schedules: diff --git a/packages/docs/src/components/DocsHome.astro b/packages/docs/src/components/DocsHome.astro new file mode 100644 index 00000000..c0a60dce --- /dev/null +++ b/packages/docs/src/components/DocsHome.astro @@ -0,0 +1,719 @@ +--- +import type { CodeLanguage } from "astro"; +import { Code } from "astro:components"; +import gramGrammar from "@gram-lang/parser/textmate"; +import Icon from "./Icon.astro"; +import { GRAM_VERSION } from "../lib/gram-version"; +import type { starlightIcons } from "../lib/starlight-icons"; + +const gramLang = { + ...gramGrammar, + name: "gram", +} as unknown as CodeLanguage; +const codeThemes = { + light: "github-light", + dark: "github-dark", +} as const; + +interface PillarLink { + label: string; + href: string; +} + +interface Pillar { + title: string; + description: string; + href: string; + icon: keyof typeof starlightIcons; + links: PillarLink[]; +} + +interface Highlight { + badge: string; + title: string; + description: string; + href: string; +} + +interface Props { + lang: "en" | "fr"; +} + +const { lang } = Astro.props; +const isFr = lang === "fr"; + +const copy = isFr + ? { + eyebrow: `Documentation · v${GRAM_VERSION}`, + lead: "Écrivez vos recettes en texte brut, avec mise à l'échelle, conversions de masse, nutrition, listes de courses et planification intégrées.", + primaryCta: "Premiers pas", + primaryHref: "/fr/docs/tutorials/getting-started/", + secondaryCta: "Ouvrir le Playground", + secondaryHref: "/fr/play", + snippetTitle: "cookies.gram", + snippetCode: [ + "---", + "title: Cookies au beurre noisette", + "portions: 12", + "---", + "", + "## Pâte ->&pâte", + "", + "Faire fondre @beurre{150 g} jusqu'à ={noisette}.", + "", + "Mélanger @farine{250 g}, @sucre{1 tasse + 2 càs} et @œufs{1 / 250 g @&farine}, puis réserver ~_{1h30}.", + "", + "Cuire à ^{180°C}(chaleur tournante) jusqu'à ={bords dorés}.", + ].join("\n"), + pillarsHeading: "Explorer par section", + newHeading: "Nouveautés de la v1.5", + newSub: + "Les points forts de cette version dans le langage et les outils.", + pillars: [ + { + title: "Guides", + description: + "Découvrez la philosophie du langage, rédigez votre première recette et suivez les guides pratiques.", + href: "/fr/docs/tutorials/getting-started/", + icon: "rocket", + links: [ + { + label: "C'est quoi Gram ?", + href: "/fr/docs/explanation/philosophy/", + }, + { + label: "Votre première recette", + href: "/fr/docs/tutorials/first-recipe/", + }, + { + label: "Planifier un repas", + href: "/fr/docs/how-to/plan-a-meal/", + }, + { + label: "Recettes modulaires", + href: "/fr/docs/how-to/organize-modular-recipes/", + }, + ], + }, + { + title: "Syntaxe du langage", + description: + "L'antisèche et la référence complète des marqueurs de base et des mécanismes avancés.", + href: "/fr/docs/reference/syntax/cheatsheet/", + icon: "document", + links: [ + { + label: "Antisèche", + href: "/fr/docs/reference/syntax/cheatsheet/", + }, + { + label: "Ingrédients", + href: "/fr/docs/reference/syntax/ingredients/", + }, + { + label: "Temps & planification", + href: "/fr/docs/reference/syntax/times/", + }, + { + label: "États attendus", + href: "/fr/docs/reference/syntax/target-states/", + }, + ], + }, + { + title: "Outils & intégration", + description: + "Utilisez la CLI, l'extension VS Code, le Language Server, l'import IA ou créez votre propre interface.", + href: "/fr/docs/reference/tooling/cli/", + icon: "laptop", + links: [ + { label: "Commandes CLI", href: "/fr/docs/reference/tooling/cli/" }, + { + label: "Extension VS Code", + href: "/fr/docs/reference/tooling/vscode-extension/", + }, + { + label: "Language Server (LSP)", + href: "/fr/docs/reference/tooling/language-server/", + }, + { + label: "Génération IA", + href: "/fr/docs/reference/syntax/ai-generation-notes/", + }, + ], + }, + { + title: "Moteur & API", + description: + "Intégrez les paquets TypeScript, consultez les formats JSON et approfondissez l'architecture du compilateur.", + href: "/fr/docs/reference/api/", + icon: "setting", + links: [ + { label: "Vue d'ensemble API", href: "/fr/docs/reference/api/" }, + { + label: "Formats de données", + href: "/fr/docs/reference/api/data-formats/", + }, + { + label: "Avertissements", + href: "/fr/docs/reference/api/warnings/", + }, + { + label: "Ordonnancement ALAP", + href: "/fr/docs/explanation/alap-scheduling/", + }, + ], + }, + ] satisfies Pillar[], + highlights: [ + { + badge: "={…}", + title: "États attendus", + description: + "Notez les repères visuels et sensoriels, avec un test de contrôle.", + href: "/fr/docs/reference/syntax/target-states/", + }, + { + badge: "a + b", + title: "Sommes de quantités", + description: + "Additionnez ou soustrayez plusieurs unités dans une même accolade.", + href: "/fr/docs/reference/syntax/ingredients/#sommes-de-quantités", + }, + { + badge: "a / b", + title: "Proportions avec unités", + description: + "Exprimez quantités et temps de cuisson proportionnels à un autre ingrédient.", + href: "/fr/docs/reference/syntax/relative-quantities/#proportions-avec-unités", + }, + { + badge: "1h30", + title: "Durées naturelles", + description: + "Écrivez les temps en unités composées, notation horaire ou primes.", + href: "/fr/docs/reference/syntax/times/#écrire-une-durée", + }, + ] satisfies Highlight[], + } + : { + eyebrow: `Documentation · v${GRAM_VERSION}`, + lead: "Write recipes in plain text with built-in scaling, mass conversions, nutrition estimates, shopping lists, and meal scheduling.", + primaryCta: "Getting started", + primaryHref: "/docs/tutorials/getting-started/", + secondaryCta: "Open Playground", + secondaryHref: "/play", + snippetTitle: "cookies.gram", + snippetCode: [ + "---", + "title: Brown butter cookies", + "portions: 12", + "---", + "", + "## Dough ->&dough", + "", + "Melt @butter{150 g} until ={nutty brown}.", + "", + "Mix @flour{250 g}, @sugar{1 cup + 2 tbsp}, and @eggs{1 / 250 g @&flour}, then chill ~_{1h30}.", + "", + "Bake at ^{180°C}(fan) until ={golden edges}.", + ].join("\n"), + pillarsHeading: "Browse by section", + newHeading: "What's new in v1.5", + newSub: "Key additions to the language and tooling in this release.", + pillars: [ + { + title: "Guides", + description: + "Understand Gram's philosophy, write your first recipe, and follow practical workflows.", + href: "/docs/tutorials/getting-started/", + icon: "rocket", + links: [ + { label: "What is Gram?", href: "/docs/explanation/philosophy/" }, + { + label: "Your first recipe", + href: "/docs/tutorials/first-recipe/", + }, + { label: "Plan a meal", href: "/docs/how-to/plan-a-meal/" }, + { + label: "Modular recipes", + href: "/docs/how-to/organize-modular-recipes/", + }, + ], + }, + { + title: "Language syntax", + description: + "Quick cheatsheet and complete reference for core markers and advanced expressions.", + href: "/docs/reference/syntax/cheatsheet/", + icon: "document", + links: [ + { label: "Cheatsheet", href: "/docs/reference/syntax/cheatsheet/" }, + { + label: "Ingredients", + href: "/docs/reference/syntax/ingredients/", + }, + { + label: "Times & scheduling", + href: "/docs/reference/syntax/times/", + }, + { + label: "Target states", + href: "/docs/reference/syntax/target-states/", + }, + ], + }, + { + title: "Tooling & integration", + description: + "Run recipes from the CLI, edit with VS Code and LSP, import via AI, or build a custom UI.", + href: "/docs/reference/tooling/cli/", + icon: "laptop", + links: [ + { label: "CLI commands", href: "/docs/reference/tooling/cli/" }, + { + label: "VS Code extension", + href: "/docs/reference/tooling/vscode-extension/", + }, + { + label: "Language server (LSP)", + href: "/docs/reference/tooling/language-server/", + }, + { + label: "Writing programmatically", + href: "/docs/reference/syntax/ai-generation-notes/", + }, + ], + }, + { + title: "Engine & API", + description: + "Integrate TypeScript packages, inspect compiled JSON schemas, and explore scheduling internals.", + href: "/docs/reference/api/", + icon: "setting", + links: [ + { label: "API overview", href: "/docs/reference/api/" }, + { + label: "Data formats", + href: "/docs/reference/api/data-formats/", + }, + { + label: "Compiler warnings", + href: "/docs/reference/api/warnings/", + }, + { + label: "ALAP scheduling", + href: "/docs/explanation/alap-scheduling/", + }, + ], + }, + ] satisfies Pillar[], + highlights: [ + { + badge: "={…}", + title: "Target states", + description: + "Mark visual or sensory cues with optional verification tests.", + href: "/docs/reference/syntax/target-states/", + }, + { + badge: "a + b", + title: "Sums of quantities", + description: + "Add or subtract mixed measures right inside ingredient braces.", + href: "/docs/reference/syntax/ingredients/#sums-of-quantities", + }, + { + badge: "a / b", + title: "Ratios with units", + description: + "Express ingredient amounts and cooking times relative to a target.", + href: "/docs/reference/syntax/relative-quantities/#ratios-with-units", + }, + { + badge: "1h30", + title: "Natural durations", + description: + "Write timers using compound units, clock notation, or primes.", + href: "/docs/reference/syntax/times/#writing-a-duration", + }, + ] satisfies Highlight[], + }; +--- + +
+
+
+ {copy.eyebrow} +

{copy.lead}

+ +
+ +
+
+ + {copy.snippetTitle} +
+ +
+
+ +
+

{copy.pillarsHeading}

+
+ { + copy.pillars.map((pillar) => ( +
+ +

{pillar.description}

+ +
+ )) + } +
+
+ +
+
+

{copy.newHeading}

+

{copy.newSub}

+
+
+ { + copy.highlights.map((item) => ( + + {item.badge} +
+ {item.title} + {item.description} +
+
+ )) + } +
+
+
+ + diff --git a/packages/docs/src/components/Header.astro b/packages/docs/src/components/Header.astro index 4dcaf374..e22653d7 100644 --- a/packages/docs/src/components/Header.astro +++ b/packages/docs/src/components/Header.astro @@ -16,11 +16,7 @@ const { currentLang = "en" } = Astro.props; @@ -76,11 +72,7 @@ const { currentLang = "en" } = Astro.props;
diff --git a/packages/docs/src/components/Homepage.astro b/packages/docs/src/components/Homepage.astro index 6d2680f2..9e72b10c 100644 --- a/packages/docs/src/components/Homepage.astro +++ b/packages/docs/src/components/Homepage.astro @@ -73,9 +73,7 @@ const mockNutrientRows = portionRows
{t.heroGetStarted} {t.readBookLink}: {t.readBookTitle} diff --git a/packages/docs/src/components/Sidebar.astro b/packages/docs/src/components/Sidebar.astro new file mode 100644 index 00000000..5c0198b1 --- /dev/null +++ b/packages/docs/src/components/Sidebar.astro @@ -0,0 +1,163 @@ +--- +import DefaultSidebar from "@astrojs/starlight/components/Sidebar.astro"; +import Icon from "./Icon.astro"; +import type { starlightIcons } from "../lib/starlight-icons"; + +type SidebarEntry = (typeof Astro.locals.starlightRoute.sidebar)[number]; + +const fullSidebar = Astro.locals.starlightRoute.sidebar; + +const TOPIC_ICONS: (keyof typeof starlightIcons)[] = [ + "rocket", + "document", + "laptop", + "setting", +]; + +function hasCurrent(entry: SidebarEntry): boolean { + if (entry.type === "link") return entry.isCurrent; + return entry.entries.some(hasCurrent); +} + +function firstHref(entry: SidebarEntry): string { + if (entry.type === "link") return entry.href; + for (const child of entry.entries) { + const href = firstHref(child); + if (href) return href; + } + return "#"; +} + +const topics = fullSidebar.map((entry, idx) => ({ + label: entry.label, + href: firstHref(entry), + icon: TOPIC_ICONS[idx] ?? "document", + active: hasCurrent(entry), + entries: entry.type === "group" ? entry.entries : [entry], +})); + +const activeTopic = topics.find((t) => t.active) ?? topics[0]; +if (activeTopic) { + activeTopic.active = true; +} +const activeEntries = activeTopic ? activeTopic.entries : fullSidebar; + +// Render Starlight's built-in Sidebar with only the active topic's tree so +// SidebarPersister hashes each topic independently. +Astro.locals.starlightRoute.sidebar = activeEntries; +--- + +{ + topics.length > 1 && ( +
+ +
+ ) +} + + + + diff --git a/packages/docs/src/components/SiteFooter.astro b/packages/docs/src/components/SiteFooter.astro index df64148b..ed3b3cb1 100644 --- a/packages/docs/src/components/SiteFooter.astro +++ b/packages/docs/src/components/SiteFooter.astro @@ -72,9 +72,7 @@ const prefix = currentLang === "fr" ? "/fr" : "";

{langText.resources}

  • - {langText.documentation} + {langText.documentation}
  • {langText.playground}
  • {langText.blog}
  • diff --git a/packages/docs/src/components/SiteTitle.astro b/packages/docs/src/components/SiteTitle.astro index b3a8f648..a8d7b5a6 100644 --- a/packages/docs/src/components/SiteTitle.astro +++ b/packages/docs/src/components/SiteTitle.astro @@ -1,8 +1,9 @@ --- import { GRAM_VERSION } from "../lib/gram-version"; -const { siteTitleHref, locale } = Astro.locals.starlightRoute; +const { locale } = Astro.locals.starlightRoute; const homeHref = locale === "fr" ? "/fr/" : "/"; +const docsHref = locale === "fr" ? "/fr/docs/" : "/docs/"; const changelogHref = locale === "fr" ? "/fr/docs/changelog" : "/docs/changelog"; --- @@ -10,7 +11,7 @@ const changelogHref = diff --git a/packages/docs/src/content/docs/docs/index.mdx b/packages/docs/src/content/docs/docs/index.mdx new file mode 100644 index 00000000..13c60fc6 --- /dev/null +++ b/packages/docs/src/content/docs/docs/index.mdx @@ -0,0 +1,9 @@ +--- +title: "Gram documentation" +description: "Learn the Gram recipe markup language, explore the CLI and editor tools, or integrate the compiler and scheduler APIs." +tableOfContents: false +--- + +import DocsHome from '../../../components/DocsHome.astro'; + + diff --git a/packages/docs/src/content/docs/docs/reference/syntax/times.mdx b/packages/docs/src/content/docs/docs/reference/syntax/times.mdx index 7e06b417..2d360fa6 100644 --- a/packages/docs/src/content/docs/docs/reference/syntax/times.mdx +++ b/packages/docs/src/content/docs/docs/reference/syntax/times.mdx @@ -33,6 +33,54 @@ These units resolve through Gram's multi-language time dictionary, so localized +## Active vs passive + +The Gram compiler builds a complete execution timeline for each recipe. To achieve realistic scheduling, it distinguishes hands-on kitchen work from autonomous background tasks. + +:::tip[💡 The Golden Rule: Does this step block YOU from starting the next step?] + +| Cook Status | Timer Type | Syntax | Culinary Examples | +| :--- | :--- | :--- | :--- | +| **YES** (Exclusive manual attention required) | **Active** | `~` | *Whisking by hand, stirring risotto, plating* | +| **NO** (Equipment or time does the work) | **Passive** | `~_` | *Oven baking, fermentation, simmering, chilling* | + +::: + +### Active (default) +By default, a `~timer` is active. It requires direct hands-on involvement: the step is **blocking** and demands undivided attention before moving on to subsequent operations. + +```gram +Whisk the @heavy cream{} continuously for ~{5min}. +``` +> ⏱️ **Result:** Adds 5 minutes to **active time**. + +### Passive (`_`) +Add the `_` modifier to designate a passive `~timer`. This represents a **background task**. You initiate the timer (e.g. putting a dish into the oven) and can immediately proceed with subsequent steps. + +```gram +Bake in the #oven for ~_{45min}. + +Meanwhile, prepare the glaze... +``` +> ⏱️ **Result:** Adds 0 minutes to active time, but extends **idle / passive duration** to ensure these 45 minutes elapse before removing the dish. + +### Sequential passive timers (named tracks) +By default, passive timers run concurrently with the rest of the recipe. However, certain background operations sharing equipment cannot physically overlap (e.g. blind-baking a crust for 10 minutes, then lowering the heat and continuing baking for 30 minutes in the same oven). + +To enforce **sequential** execution of passive timers, assign them the **same track name**: + +```gram +Bake in the #oven at 240°C for ~_baking{10min}. + +Lower the heat to 180°C and bake for ~_baking{30min}. +``` + +> ⏱️ **Result:** Because both timers share the track name `baking`, Gram places them on the same background track. The 30-minute timer will only start *after* the 10-minute timer completes. Idle waiting time increases by 40 minutes, while active hands-on time remains zero. + +:::tip[Without a track, overlapping waits are flagged] +Two passive timers that overlap in steps citing the **same cookware** (`#oven` in both) with no track in common are reported by `PASSIVE_OVERLAP_SAME_COOKWARE`: the message suggests a named track. It is only informational, since two trays can share an oven. See [Warnings](/docs/reference/api/warnings/#passive_overlap_same_cookware). +::: + ## Writing a duration @@ -121,54 +169,6 @@ Fry the @cutlets{4} ~{4 min / @&cutlets}. // 16 min - Scaling the recipe recalculates proportional times and updates the schedule automatically. - Multipliers (`~{15 min / 500 g @&roast * 2}`) and proportional section anchors are not supported yet. -## Active vs passive - -The Gram compiler builds a complete execution timeline for each recipe. To achieve realistic scheduling, it distinguishes hands-on kitchen work from autonomous background tasks. - -:::tip[💡 The Golden Rule: Does this step block YOU from starting the next step?] - -| Cook Status | Timer Type | Syntax | Culinary Examples | -| :--- | :--- | :--- | :--- | -| **YES** (Exclusive manual attention required) | **Active** | `~` | *Whisking by hand, stirring risotto, plating* | -| **NO** (Equipment or time does the work) | **Passive** | `~_` | *Oven baking, fermentation, simmering, chilling* | - -::: - -### Active (default) -By default, a `~timer` is active. It requires direct hands-on involvement: the step is **blocking** and demands undivided attention before moving on to subsequent operations. - -```gram -Whisk the @heavy cream{} continuously for ~{5min}. -``` -> ⏱️ **Result:** Adds 5 minutes to **active time**. - -### Passive (`_`) -Add the `_` modifier to designate a passive `~timer`. This represents a **background task**. You initiate the timer (e.g. putting a dish into the oven) and can immediately proceed with subsequent steps. - -```gram -Bake in the #oven for ~_{45min}. - -Meanwhile, prepare the glaze... -``` -> ⏱️ **Result:** Adds 0 minutes to active time, but extends **idle / passive duration** to ensure these 45 minutes elapse before removing the dish. - -### Sequential passive timers (named tracks) -By default, passive timers run concurrently with the rest of the recipe. However, certain background operations sharing equipment cannot physically overlap (e.g. blind-baking a crust for 10 minutes, then lowering the heat and continuing baking for 30 minutes in the same oven). - -To enforce **sequential** execution of passive timers, assign them the **same track name**: - -```gram -Bake in the #oven at 240°C for ~_baking{10min}. - -Lower the heat to 180°C and bake for ~_baking{30min}. -``` - -> ⏱️ **Result:** Because both timers share the track name `baking`, Gram places them on the same background track. The 30-minute timer will only start *after* the 10-minute timer completes. Idle waiting time increases by 40 minutes, while active hands-on time remains zero. - -:::tip[Without a track, overlapping waits are flagged] -Two passive timers that overlap in steps citing the **same cookware** (`#oven` in both) with no track in common are reported by `PASSIVE_OVERLAP_SAME_COOKWARE`: the message suggests a named track. It is only informational, since two trays can share an oven. See [Warnings](/docs/reference/api/warnings/#passive_overlap_same_cookware). -::: - ## How time is calculated Behind the scenes, Gram tracks four distinct time metrics to establish realistic schedules: diff --git a/packages/docs/src/content/docs/fr/docs/index.mdx b/packages/docs/src/content/docs/fr/docs/index.mdx new file mode 100644 index 00000000..e6136a32 --- /dev/null +++ b/packages/docs/src/content/docs/fr/docs/index.mdx @@ -0,0 +1,9 @@ +--- +title: "Documentation de Gram" +description: "Apprenez le langage de recettes Gram, découvrez la CLI et les outils d'édition, ou intégrez le compilateur et le moteur d'ordonnancement." +tableOfContents: false +--- + +import DocsHome from '../../../../components/DocsHome.astro'; + + diff --git a/packages/docs/src/content/docs/fr/docs/reference/syntax/times.mdx b/packages/docs/src/content/docs/fr/docs/reference/syntax/times.mdx index 62843977..c41d9dce 100644 --- a/packages/docs/src/content/docs/fr/docs/reference/syntax/times.mdx +++ b/packages/docs/src/content/docs/fr/docs/reference/syntax/times.mdx @@ -33,6 +33,54 @@ Ces unités s'appuient sur le dictionnaire temporel multilingue de Gram, ce qui +## Actif vs passif + +Le compilateur Gram construit une chronologie d'exécution complète pour chaque recette. Afin d'établir un ordonnancement réaliste, il distingue le travail mobilisant activement la brigade des opérations s'exécutant en tâche de fond. + +:::tip[💡 Règle d'or : l'étape m'empêche-t-elle de démarrer la suivante ?] + +| Statut du cuisinier | Nature du minuteur | Syntaxe | Exemples culinaires | +| :--- | :--- | :--- | :--- | +| **OUI** (Attention exclusive et continue) | **Actif** | `~` | *Fouetter à la main, surveiller un caramel, dresser* | +| **NON** (Le matériel ou le temps opère) | **Passif** | `~_` | *Cuisson au four, fermentation, mijotage, refroidissement* | + +::: + +### Actif (par défaut) +Par défaut, un `~minuteur` est actif. Il implique une mobilisation directe du cuisinier : l'étape est **bloquante** et requiert une attention exclusive avant de pouvoir enclencher l'opération suivante. + +```gram +Fouetter la @crème liquide{} en continu pendant ~{5 min}. +``` +> ⏱️ **Résultat :** Ajoute 5 minutes au **temps actif**. + +### Passif (`_`) +Ajoutez le préfixe `_` pour déclarer un `~minuteur` passif. Il s'agit d'une **tâche de fond**. Vous lancez l'opération (par exemple, enfourner une préparation) et pouvez immédiatement passer à l'étape suivante. + +```gram +Cuire dans le #four pendant ~_{45 min}. + +Pendant ce temps, préparer le glaçage... +``` +> ⏱️ **Résultat :** N'ajoute aucune minute au temps actif (0 min), mais prolonge le **temps passif / d'inactivité** pour garantir que ces 45 minutes s'écoulent avant l'étape de sortie du four. + +### Minuteurs passifs séquentiels (pistes nommées) +Par défaut, les minuteurs passifs s'exécutent en parallèle du flux principal. Cependant, certaines opérations sur équipement ne peuvent matériellement pas se chevaucher (par exemple, précuire un fond de tarte 10 minutes, puis baisser la température et poursuivre la cuisson 30 minutes supplémentaires dans le même four). + +Pour imposer l'exécution **séquentielle** de minuteurs passifs, attribuez-leur le **même nom d'équipement ou de piste** : + +```gram +Cuire dans le four à 240°C pendant ~_cuisson{10 min}. + +Baisser la température à 180°C et poursuivre la cuisson pendant ~_cuisson{30 min}. +``` + +> ⏱️ **Résultat :** En partageant la piste `cuisson`, Gram ordonnance ces deux minuteurs l'un après l'autre. Le second minuteur de 30 minutes ne démarrera qu'une fois les 10 premières minutes achevées. L'amplitude temporelle augmente de 40 minutes, sans impacter le temps actif. + +:::tip[Sans piste, les attentes qui se chevauchent sont signalées] +Deux minuteurs passifs qui se chevauchent dans des étapes citant le **même ustensile** (`#four` dans les deux), sans piste en commun, sont signalés par `PASSIVE_OVERLAP_SAME_COOKWARE` : le message suggère une piste nommée. C'est seulement informatif, puisque deux plaques peuvent partager un four. Voir [Avertissements](/fr/docs/reference/api/warnings/#passive_overlap_same_cookware). +::: + ## Écrire une durée @@ -121,54 +169,6 @@ Poêler les @côtelettes{4} ~{4 min / @&côtelettes}. // 16 min - La mise à l'échelle recalcule automatiquement ces durées et met le planning à jour. - Les multiplicateurs (`~{15 min / 500 g @&rôti * 2}`) et les ancres de section proportionnelles ne sont pas encore pris en charge. -## Actif vs passif - -Le compilateur Gram construit une chronologie d'exécution complète pour chaque recette. Afin d'établir un ordonnancement réaliste, il distingue le travail mobilisant activement la brigade des opérations s'exécutant en tâche de fond. - -:::tip[💡 Règle d'or : l'étape m'empêche-t-elle de démarrer la suivante ?] - -| Statut du cuisinier | Nature du minuteur | Syntaxe | Exemples culinaires | -| :--- | :--- | :--- | :--- | -| **OUI** (Attention exclusive et continue) | **Actif** | `~` | *Fouetter à la main, surveiller un caramel, dresser* | -| **NON** (Le matériel ou le temps opère) | **Passif** | `~_` | *Cuisson au four, fermentation, mijotage, refroidissement* | - -::: - -### Actif (par défaut) -Par défaut, un `~minuteur` est actif. Il implique une mobilisation directe du cuisinier : l'étape est **bloquante** et requiert une attention exclusive avant de pouvoir enclencher l'opération suivante. - -```gram -Fouetter la @crème liquide{} en continu pendant ~{5 min}. -``` -> ⏱️ **Résultat :** Ajoute 5 minutes au **temps actif**. - -### Passif (`_`) -Ajoutez le préfixe `_` pour déclarer un `~minuteur` passif. Il s'agit d'une **tâche de fond**. Vous lancez l'opération (par exemple, enfourner une préparation) et pouvez immédiatement passer à l'étape suivante. - -```gram -Cuire dans le #four pendant ~_{45 min}. - -Pendant ce temps, préparer le glaçage... -``` -> ⏱️ **Résultat :** N'ajoute aucune minute au temps actif (0 min), mais prolonge le **temps passif / d'inactivité** pour garantir que ces 45 minutes s'écoulent avant l'étape de sortie du four. - -### Minuteurs passifs séquentiels (pistes nommées) -Par défaut, les minuteurs passifs s'exécutent en parallèle du flux principal. Cependant, certaines opérations sur équipement ne peuvent matériellement pas se chevaucher (par exemple, précuire un fond de tarte 10 minutes, puis baisser la température et poursuivre la cuisson 30 minutes supplémentaires dans le même four). - -Pour imposer l'exécution **séquentielle** de minuteurs passifs, attribuez-leur le **même nom d'équipement ou de piste** : - -```gram -Cuire dans le four à 240°C pendant ~_cuisson{10 min}. - -Baisser la température à 180°C et poursuivre la cuisson pendant ~_cuisson{30 min}. -``` - -> ⏱️ **Résultat :** En partageant la piste `cuisson`, Gram ordonnance ces deux minuteurs l'un après l'autre. Le second minuteur de 30 minutes ne démarrera qu'une fois les 10 premières minutes achevées. L'amplitude temporelle augmente de 40 minutes, sans impacter le temps actif. - -:::tip[Sans piste, les attentes qui se chevauchent sont signalées] -Deux minuteurs passifs qui se chevauchent dans des étapes citant le **même ustensile** (`#four` dans les deux), sans piste en commun, sont signalés par `PASSIVE_OVERLAP_SAME_COOKWARE` : le message suggère une piste nommée. C'est seulement informatif, puisque deux plaques peuvent partager un four. Voir [Avertissements](/fr/docs/reference/api/warnings/#passive_overlap_same_cookware). -::: - ## Comment le temps est calculé En coulisses, Gram calcule quatre grandeurs temporelles distinctes pour établir une planification rigoureuse : diff --git a/packages/docs/src/pages/404.astro b/packages/docs/src/pages/404.astro index ad279bbc..9f2331a0 100644 --- a/packages/docs/src/pages/404.astro +++ b/packages/docs/src/pages/404.astro @@ -12,7 +12,7 @@ const copy = isFr homeLabel: "Retour à l'accueil", docsLabel: "Voir la documentation", homeHref: "/fr", - docsHref: "/fr/docs/explanation/philosophy", + docsHref: "/fr/docs/", } : { lang: "en", @@ -22,7 +22,7 @@ const copy = isFr homeLabel: "Back to home", docsLabel: "Browse the docs", homeHref: "/", - docsHref: "/docs/explanation/philosophy", + docsHref: "/docs/", }; --- diff --git a/packages/docs/src/pages/docs/index.astro b/packages/docs/src/pages/docs/index.astro deleted file mode 100644 index c9afe7ec..00000000 --- a/packages/docs/src/pages/docs/index.astro +++ /dev/null @@ -1,25 +0,0 @@ ---- -// Redirect /docs to the first documentation page, automatically routing by browser language. ---- - - - - - - - Redirecting to Gram Documentation... - - - -

    Redirecting to Gram Documentation...

    - - diff --git a/packages/docs/src/pages/en/docs/index.astro b/packages/docs/src/pages/en/docs/index.astro index dcfd4611..38fdb202 100644 --- a/packages/docs/src/pages/en/docs/index.astro +++ b/packages/docs/src/pages/en/docs/index.astro @@ -5,14 +5,14 @@ - - + + Redirecting to Gram Documentation... -

    Redirecting to Gram Documentation...

    +

    Redirecting to Gram Documentation...

    diff --git a/packages/docs/src/pages/fr/docs/index.astro b/packages/docs/src/pages/fr/docs/index.astro deleted file mode 100644 index 6d9f6727..00000000 --- a/packages/docs/src/pages/fr/docs/index.astro +++ /dev/null @@ -1,18 +0,0 @@ ---- -// Redirect /fr/docs to the French documentation entry page. ---- - - - - - - - Redirection vers la documentation Gram... - - - -

    Redirection vers la documentation Gram...

    - - -- 2.54.0 From 69bec7703de380b06ab601b31e4d0928bdaff853 Mon Sep 17 00:00:00 2001 From: abiwab Date: Wed, 18 Nov 2026 13:02:19 +0100 Subject: [PATCH 03/24] docs: refine docs landing hero, CLI block, and sharp radii --- packages/docs/src/components/DocsHome.astro | 477 +++++++++++++++++--- packages/docs/src/components/Sidebar.astro | 4 +- packages/docs/src/styles/global.css | 8 +- 3 files changed, 420 insertions(+), 69 deletions(-) diff --git a/packages/docs/src/components/DocsHome.astro b/packages/docs/src/components/DocsHome.astro index c0a60dce..a47da0ab 100644 --- a/packages/docs/src/components/DocsHome.astro +++ b/packages/docs/src/components/DocsHome.astro @@ -3,7 +3,6 @@ import type { CodeLanguage } from "astro"; import { Code } from "astro:components"; import gramGrammar from "@gram-lang/parser/textmate"; import Icon from "./Icon.astro"; -import { GRAM_VERSION } from "../lib/gram-version"; import type { starlightIcons } from "../lib/starlight-icons"; const gramLang = { @@ -44,7 +43,7 @@ const isFr = lang === "fr"; const copy = isFr ? { - eyebrow: `Documentation · v${GRAM_VERSION}`, + heroTitle: "Gram Docs", lead: "Écrivez vos recettes en texte brut, avec mise à l'échelle, conversions de masse, nutrition, listes de courses et planification intégrées.", primaryCta: "Premiers pas", primaryHref: "/fr/docs/tutorials/getting-started/", @@ -195,9 +194,44 @@ const copy = isFr href: "/fr/docs/reference/syntax/times/#écrire-une-durée", }, ] satisfies Highlight[], + cli: { + title: "Passer aux fourneaux", + description: + "Initialisez votre espace de recettes en local en quelques secondes avec la CLI.", + command: "npx @gram-lang/cli init", + copyLabel: "Copier", + copiedLabel: "Copié", + copyAria: "Copier la commande CLI dans le presse-papiers", + copiedStatus: "Commande copiée dans le presse-papiers", + linkLabel: "Commandes CLI", + linkHref: "/fr/docs/reference/tooling/cli/", + }, + community: { + heading: "Contribuer & communauté", + links: [ + { + label: "Dépôt officiel", + href: "https://git.gram-lang.org/gram-lang/gram", + icon: "code-branch" as keyof typeof starlightIcons, + umamiEvent: undefined as string | undefined, + }, + { + label: "Discord", + href: "https://discord.gg/nsCBkhjuAR", + icon: "rocket" as keyof typeof starlightIcons, + umamiEvent: "click-discord", + }, + { + label: "Reddit (r/gramlang)", + href: "https://www.reddit.com/r/gramlang/", + icon: "document" as keyof typeof starlightIcons, + umamiEvent: "click-reddit", + }, + ], + }, } : { - eyebrow: `Documentation · v${GRAM_VERSION}`, + heroTitle: "Gram Docs", lead: "Write recipes in plain text with built-in scaling, mass conversions, nutrition estimates, shopping lists, and meal scheduling.", primaryCta: "Getting started", primaryHref: "/docs/tutorials/getting-started/", @@ -338,37 +372,75 @@ const copy = isFr href: "/docs/reference/syntax/times/#writing-a-duration", }, ] satisfies Highlight[], + cli: { + title: "Start cooking", + description: + "Scaffold a new recipe workspace locally in seconds with the CLI.", + command: "npx @gram-lang/cli init", + copyLabel: "Copy", + copiedLabel: "Copied", + copyAria: "Copy CLI initialization command to clipboard", + copiedStatus: "Command copied to clipboard", + linkLabel: "CLI reference", + linkHref: "/docs/reference/tooling/cli/", + }, + community: { + heading: "Contribute & community", + links: [ + { + label: "Official repository", + href: "https://git.gram-lang.org/gram-lang/gram", + icon: "code-branch" as keyof typeof starlightIcons, + umamiEvent: undefined as string | undefined, + }, + { + label: "Discord", + href: "https://discord.gg/nsCBkhjuAR", + icon: "rocket" as keyof typeof starlightIcons, + umamiEvent: "click-discord", + }, + { + label: "Reddit (r/gramlang)", + href: "https://www.reddit.com/r/gramlang/", + icon: "document" as keyof typeof starlightIcons, + umamiEvent: "click-reddit", + }, + ], + }, }; ---
    -
    -
    - {copy.eyebrow} -

    {copy.lead}

    -
    - - {copy.primaryCta} - - - - {copy.secondaryCta} - +
    +
    +
    +

    {copy.heroTitle}

    +

    {copy.lead}

    +
    -
    -
    -
    - - {copy.snippetTitle} +
    +
    + + {copy.snippetTitle} +
    +
    -
    -
    +
    +

    {copy.pillarsHeading}

    { @@ -396,6 +468,37 @@ const copy = isFr
    +
    +
    +
    +

    {copy.cli.title}

    +

    {copy.cli.description}

    + + {copy.cli.linkLabel} + + +
    +
    + {copy.cli.command} + + +
    +
    +
    +

    {copy.newHeading}

    @@ -415,50 +518,139 @@ const copy = isFr }
    + +
    + {copy.community.heading} + +
    +
    + + diff --git a/packages/docs/src/components/Sidebar.astro b/packages/docs/src/components/Sidebar.astro index 5c0198b1..7968cbc4 100644 --- a/packages/docs/src/components/Sidebar.astro +++ b/packages/docs/src/components/Sidebar.astro @@ -84,7 +84,7 @@ Astro.locals.starlightRoute.sidebar = activeEntries; display: flex; flex-direction: column; gap: 0.125rem; - border-radius: 0.75rem; + border-radius: 3px; border: 1px solid var(--sl-color-gray-5); background-color: var(--sl-color-bg); } @@ -98,7 +98,7 @@ Astro.locals.starlightRoute.sidebar = activeEntries; align-items: center; gap: 0.65rem; padding: 0.45rem 0.65rem; - border-radius: 0.5rem; + border-radius: 3px; border: 1px solid transparent; font-size: 0.92rem; font-weight: 500; diff --git a/packages/docs/src/styles/global.css b/packages/docs/src/styles/global.css index 2e07bdb2..731cc31e 100644 --- a/packages/docs/src/styles/global.css +++ b/packages/docs/src/styles/global.css @@ -301,6 +301,7 @@ div[data-nova-code-container] pre, .post-content pre { background-color: var(--sl-color-bg) !important; border-color: var(--sl-color-gray-5) !important; + border-radius: 0 !important; } html[data-theme="dark"] .astro-code, @@ -351,6 +352,7 @@ div[data-nova-code-container] > div:first-child:not(pre) { .sl-markdown-content .code-tabs.code-tabs-border { border-color: var(--sl-color-gray-5) !important; background-color: var(--sl-color-bg) !important; + border-radius: 0 !important; } .sl-markdown-content .code-tabs [role="tablist"] { @@ -373,9 +375,9 @@ div[data-nova-code-container] > div:first-child:not(pre) { */ .sl-link-card, .sl-markdown-content .sl-link-card { - background-color: var(--sl-color-gray-6) !important; + background-color: var(--sl-color-gray-7) !important; border: 1px solid var(--sl-color-gray-5) !important; - border-radius: 0.5rem !important; + border-radius: 0 !important; box-shadow: none !important; transition: border-color 0.2s ease, @@ -425,7 +427,7 @@ div[data-nova-code-container] > div:first-child:not(pre) { .card:where(.astro-e6yapmfz) { background-color: var(--sl-color-gray-6) !important; border: 1px solid var(--sl-color-gray-5) !important; - border-radius: 0.5rem !important; + border-radius: 0 !important; } /* -- 2.54.0 From 0943610313e91b29e2764ff1bc8ea15bb955e415 Mon Sep 17 00:00:00 2001 From: abiwab Date: Wed, 18 Nov 2026 13:26:06 +0100 Subject: [PATCH 04/24] docs: flatten shadows and align sidebar background in dark mode --- packages/docs/src/components/DocsHome.astro | 13 ------------- packages/docs/src/components/Sidebar.astro | 8 +++----- packages/docs/src/styles/global.css | 2 +- 3 files changed, 4 insertions(+), 19 deletions(-) diff --git a/packages/docs/src/components/DocsHome.astro b/packages/docs/src/components/DocsHome.astro index a47da0ab..0c255182 100644 --- a/packages/docs/src/components/DocsHome.astro +++ b/packages/docs/src/components/DocsHome.astro @@ -602,17 +602,6 @@ const copy = isFr .docs-hero-band { width: 100%; border-bottom: 1px solid var(--sl-color-hairline); - background: - radial-gradient( - ellipse 55% 80% at 88% 15%, - rgba(255, 140, 26, 0.14), - transparent 70% - ), - linear-gradient( - 180deg, - var(--sl-color-gray-6) 0%, - var(--sl-color-bg) 100% - ); } .docs-hero { @@ -700,7 +689,6 @@ const copy = isFr border-radius: 0; border: 1px solid var(--sl-color-gray-5); background-color: var(--sl-color-bg); - box-shadow: var(--shadow-elevation-medium); overflow: hidden; } @@ -911,7 +899,6 @@ const copy = isFr padding: 1.25rem 1.35rem; border-radius: 0; border: 1px solid var(--sl-color-gray-5); - background-color: var(--sl-color-gray-6); } .docs-cli-copy { diff --git a/packages/docs/src/components/Sidebar.astro b/packages/docs/src/components/Sidebar.astro index 7968cbc4..e3b71256 100644 --- a/packages/docs/src/components/Sidebar.astro +++ b/packages/docs/src/components/Sidebar.astro @@ -86,7 +86,7 @@ Astro.locals.starlightRoute.sidebar = activeEntries; gap: 0.125rem; border-radius: 3px; border: 1px solid var(--sl-color-gray-5); - background-color: var(--sl-color-bg); + background-color: var(--sl-color-gray-7); } :global(:root[data-theme="light"]) .gram-topic-list { @@ -126,16 +126,14 @@ Astro.locals.starlightRoute.sidebar = activeEntries; font-weight: 600; background-color: var(--sl-color-gray-6); border-color: var(--sl-color-gray-5); - box-shadow: var(--sl-shadow-sm); + box-shadow: none; } :global(:root[data-theme="light"] #starlight__sidebar) a.gram-topic-link[data-active="true"] { background-color: var(--sl-color-bg); border-color: var(--sl-color-gray-5); - box-shadow: - 0 1px 2px rgba(0, 0, 0, 0.05), - 0 1px 1px rgba(0, 0, 0, 0.03); + box-shadow: none; } .gram-topic-icon { diff --git a/packages/docs/src/styles/global.css b/packages/docs/src/styles/global.css index 731cc31e..f21bdc82 100644 --- a/packages/docs/src/styles/global.css +++ b/packages/docs/src/styles/global.css @@ -58,7 +58,7 @@ samp { --sl-color-black: hsl(30, 16%, 7%); --sl-color-bg: hsl(30, 12%, 10%); --sl-color-bg-nav: var(--sl-color-gray-6); - --sl-color-bg-sidebar: var(--sl-color-gray-6); + --sl-color-bg-sidebar: var(--sl-color-bg); --sl-color-bg-inline-code: var(--sl-color-gray-5); --sl-color-border-inline-code: var(--sl-color-gray-4); --sl-color-hairline: var(--sl-color-gray-6); -- 2.54.0 From fe570e95067a86f93d8c47d8801a3a80cc07ecef Mon Sep 17 00:00:00 2001 From: abiwab Date: Wed, 18 Nov 2026 14:19:44 +0100 Subject: [PATCH 05/24] docs: add standalone changelog routes and homepage release callout --- package.json | 2 +- packages/docs/astro.config.mjs | 8 +- packages/docs/package.json | 2 +- packages/docs/scripts/generate-changelog.ts | 40 - .../docs/src/components/ChangelogPage.astro | 424 +++++++++ packages/docs/src/components/Homepage.astro | 51 +- packages/docs/src/components/Since.astro | 2 +- packages/docs/src/components/SiteFooter.astro | 2 +- packages/docs/src/components/SiteTitle.astro | 3 +- .../blog/en/2026-08-07-release-1.0.1.md | 2 +- .../blog/en/2026-08-16-release-1.1.0.md | 2 +- .../blog/en/2026-08-22-release-1.2.0.md | 2 +- .../blog/en/2026-08-25-release-1.2.1.md | 2 +- .../blog/en/2026-09-29-release-1.3.0.md | 2 +- .../blog/en/2026-11-13-release-1.4.0.md | 2 +- .../blog/en/2026-11-14-release-1.4.1.md | 2 +- .../blog/en/2026-11-17-release-1.4.2.md | 2 +- .../blog/fr/2026-08-07-release-1.0.1.md | 2 +- .../blog/fr/2026-08-16-release-1.1.0.md | 2 +- .../blog/fr/2026-08-22-release-1.2.0.md | 2 +- .../blog/fr/2026-08-25-release-1.2.1.md | 2 +- .../blog/fr/2026-09-29-release-1.3.0.md | 2 +- .../blog/fr/2026-11-13-release-1.4.0.md | 2 +- .../blog/fr/2026-11-14-release-1.4.1.md | 2 +- .../blog/fr/2026-11-17-release-1.4.2.md | 2 +- .../docs/src/content/docs/docs/changelog.md | 818 ------------------ .../content/docs/docs/how-to/deprecations.mdx | 2 +- .../docs/fr/docs/how-to/deprecations.mdx | 2 +- packages/docs/src/lib/changelog-anchors.ts | 14 +- packages/docs/src/lib/changelog.ts | 76 ++ .../src/lib/releases-and-changelog.test.ts | 124 +++ packages/docs/src/lib/releases.ts | 110 +++ packages/docs/src/pages/changelog.astro | 12 + packages/docs/src/pages/fr/changelog.astro | 12 + 34 files changed, 839 insertions(+), 897 deletions(-) delete mode 100644 packages/docs/scripts/generate-changelog.ts create mode 100644 packages/docs/src/components/ChangelogPage.astro delete mode 100644 packages/docs/src/content/docs/docs/changelog.md create mode 100644 packages/docs/src/lib/changelog.ts create mode 100644 packages/docs/src/lib/releases-and-changelog.test.ts create mode 100644 packages/docs/src/lib/releases.ts create mode 100644 packages/docs/src/pages/changelog.astro create mode 100644 packages/docs/src/pages/fr/changelog.astro diff --git a/package.json b/package.json index a5106695..2a50b754 100644 --- a/package.json +++ b/package.json @@ -40,7 +40,7 @@ "test": "bun test --only-failures", "change": "changeset", "check-changesets": "bun run check-changesets.ts", - "version-packages": "bun dedupe && bun prune && bun run generate-release-note.ts && changeset version && bun run --cwd packages/kitchen prebuild && bun run --cwd packages/docs scripts/generate-changelog.ts && bun update", + "version-packages": "bun dedupe && bun prune && bun run generate-release-note.ts && changeset version && bun run --cwd packages/kitchen prebuild && bun update", "release": "bun run scripts/publish-release.ts", "conformance": "bun run --cwd conformance conformance", "conformance:update": "bun run --cwd conformance conformance:update", diff --git a/packages/docs/astro.config.mjs b/packages/docs/astro.config.mjs index 193a8ad2..e597f258 100644 --- a/packages/docs/astro.config.mjs +++ b/packages/docs/astro.config.mjs @@ -36,6 +36,8 @@ const SITE_URL = 'https://gram-lang.org'; export default defineConfig({ site: 'https://gram-lang.org', redirects: { + '/docs/changelog': '/changelog', + '/fr/docs/changelog': '/fr/changelog', '/docs/explanation/mise-en-place-and-planning': '/docs/explanation/planning', '/docs/explanation/planning-in-real-time': '/docs/explanation/planning', '/fr/docs/explanation/mise-en-place-and-planning': '/fr/docs/explanation/planning', @@ -61,7 +63,8 @@ export default defineConfig({ exclude: [ '/play', '/play/', '/fr/play', '/fr/play/', '/en/docs', '/en/docs/', - '/blog', '/blog/', '/blog/**', '/fr/blog', '/fr/blog/', '/fr/blog/**' + '/blog', '/blog/', '/blog/**', '/fr/blog', '/fr/blog/', '/fr/blog/**', + '/changelog', '/changelog/', '/changelog/**', '/fr/changelog', '/fr/changelog/', '/fr/changelog/**' ] }) ], @@ -215,8 +218,7 @@ export default defineConfig({ { label: 'Scaling', translations: { fr: "Ajustement des proportions" }, slug: 'docs/explanation/scaling' }, { label: 'Planning & run sheet', translations: { fr: 'Planification & plan de marche' }, slug: 'docs/explanation/planning' } ] - }, - { label: 'Changelog', translations: { fr: 'Changelog' }, slug: 'docs/changelog' } + } ] } ], diff --git a/packages/docs/package.json b/packages/docs/package.json index 4af93806..c4024dfa 100644 --- a/packages/docs/package.json +++ b/packages/docs/package.json @@ -8,7 +8,7 @@ }, "scripts": { "dev": "astro dev", - "prebuild": "bun scripts/vendor-starlight-tokens.ts && bun scripts/generate-changelog.ts && bun scripts/generate-llms-full.ts", + "prebuild": "bun scripts/vendor-starlight-tokens.ts && bun scripts/generate-llms-full.ts", "build": "astro build && node scripts/check-bundle-size.mjs", "preview": "astro preview", "astro": "astro", diff --git a/packages/docs/scripts/generate-changelog.ts b/packages/docs/scripts/generate-changelog.ts deleted file mode 100644 index c0a47243..00000000 --- a/packages/docs/scripts/generate-changelog.ts +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env bun -// Mirrors the root CHANGELOG.md (the single source of truth, generated by -// changesets via generate-release-note.ts) into a Starlight content page, so the -// site never carries a second, hand-maintained copy of the release history. - -import { readFileSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; - -const ROOT_CHANGELOG = join(import.meta.dirname, "..", "..", "..", "CHANGELOG.md"); -const OUT_FILE = join( - import.meta.dirname, - "..", - "src", - "content", - "docs", - "docs", - "changelog.md", -); - -const FRONTMATTER = `--- -title: Changelog -description: Every release of Gram — new features, fixes, and breaking changes. -tableOfContents: - minHeadingLevel: 2 - maxHeadingLevel: 2 ---- - -`; - -function main() { - const source = readFileSync(ROOT_CHANGELOG, "utf-8"); - // Drop the leading "# Changelog" heading: the page's `title` frontmatter - // already renders as the H1, so keeping it would duplicate the heading. - const body = source.replace(/^# Changelog\n+/, ""); - - writeFileSync(OUT_FILE, FRONTMATTER + body, "utf-8"); - console.log("Synced CHANGELOG.md -> src/content/docs/docs/changelog.md"); -} - -main(); diff --git a/packages/docs/src/components/ChangelogPage.astro b/packages/docs/src/components/ChangelogPage.astro new file mode 100644 index 00000000..a2102a76 --- /dev/null +++ b/packages/docs/src/components/ChangelogPage.astro @@ -0,0 +1,424 @@ +--- +import { getCollection } from "astro:content"; +import { createMarkdownProcessor } from "@astrojs/markdown-remark"; +import { getChangelogReleases } from "../lib/changelog"; +import { resolveReleasePostsByVersion } from "../lib/releases"; + +interface Props { + lang: "en" | "fr"; +} + +const { lang } = Astro.props; +const isFr = lang === "fr"; + +const copy = isFr + ? { + title: "Changelog", + subtitle: + "Historique technique complet des paquets Gram. Pour une vue d'ensemble des grandes versions, consultez plutôt ", + blogCta: "les articles de release sur le blog", + blogHref: "/fr/blog/topic/releases", + tocTitle: "Sur cette page", + readPost: "Article de release", + compareLabel: "Diff", + langNote: + "Note : les notes techniques issues de CHANGELOG.md restent en anglais.", + } + : { + title: "Changelog", + subtitle: + "Full package-by-package release history from CHANGELOG.md. For guided overviews of major updates, read ", + blogCta: "the release articles on the blog", + blogHref: "/blog/topic/releases", + tocTitle: "On this page", + readPost: "Release notes", + compareLabel: "Compare", + langNote: undefined, + }; + +const [allPosts, processor] = await Promise.all([ + getCollection("blog"), + createMarkdownProcessor(), +]); + +const postsByVersion = resolveReleasePostsByVersion(allPosts, lang); +const dateFormatter = new Intl.DateTimeFormat(isFr ? "fr-FR" : "en-US", { + year: "numeric", + month: "short", + day: "numeric", + timeZone: "UTC", +}); + +const rawEntries = getChangelogReleases(); +const releases = await Promise.all( + rawEntries.map(async (entry) => { + const rendered = await processor.render(entry.bodyMarkdown); + const parsedDate = new Date(`${entry.date}T00:00:00Z`); + return { + ...entry, + formattedDate: Number.isNaN(parsedDate.valueOf()) + ? entry.date + : dateFormatter.format(parsedDate), + blogPost: postsByVersion.get(entry.version), + html: rendered.code, + }; + }), +); +--- + +
    +
    +

    {copy.title}

    +

    + {copy.subtitle}{copy.blogCta}. +

    + {copy.langNote &&

    {copy.langNote}

    } +
    + +
    + {copy.tocTitle} + +
    + +
    +
    + { + releases.map((release) => ( + + )) + } +
    + + +
    +
    + + diff --git a/packages/docs/src/components/Homepage.astro b/packages/docs/src/components/Homepage.astro index 9e72b10c..717e007f 100644 --- a/packages/docs/src/components/Homepage.astro +++ b/packages/docs/src/components/Homepage.astro @@ -1,15 +1,19 @@ --- import Layout from "../layouts/Layout.astro"; +import { getCollection } from "astro:content"; import { Code } from "astro:components"; import Icon from "./Icon.astro"; import gramGrammar from "@gram-lang/parser/textmate"; import FeaturePanel from "./FeaturePanel.astro"; import { GRAM_VERSION } from "../lib/gram-version"; -import { NUTRIENTS, type NutrientKey } from "@gram-lang/analyzer"; +import { getHomepageAnnouncement } from "../lib/releases"; +import type { NutrientKey } from "@gram-lang/analyzer"; import { nutritionRows } from "@gram-lang/renderer"; import { getDictionary } from "@gram-lang/i18n"; const { lang, t } = Astro.props; +const allPosts = await getCollection("blog"); +const announcement = getHomepageAnnouncement(allPosts, lang, GRAM_VERSION); const gramLang = { ...gramGrammar, name: "gram" } as any; const codeThemes: Record = { light: "github-light", @@ -65,6 +69,19 @@ const mockNutrientRows = portionRows
    + { + announcement && ( +

    + v{announcement.version} + + {lang === "fr" + ? "Nouveautés et notes de version" + : "What's new in this release"} + + +

    + ) + }

    {t.heroTitle}

    {t.heroSubtitle}

    @@ -83,7 +100,7 @@ const mockNutrientRows = portionRows

    @@ -658,6 +675,36 @@ const mockNutrientRows = portionRows flex: 1 1 400px; } + .release-callout { + display: flex; + align-items: baseline; + flex-wrap: wrap; + gap: 0.5rem; + margin: 0 0 1rem 0; + padding-left: 0.65rem; + border-left: 3px solid var(--gram-orange); + font-size: 0.95rem; + } + + .release-callout-tag { + font-family: var(--sl-font-mono); + font-weight: 700; + color: var(--sl-color-text-accent); + } + + .release-callout-link { + font-weight: 600; + color: var(--sl-color-text); + text-decoration: underline; + text-decoration-color: var(--gram-orange); + text-decoration-thickness: 2px; + text-underline-offset: 3px; + } + + .release-callout-link:hover { + color: var(--sl-color-white); + } + .version-badge { margin-top: 1rem; } diff --git a/packages/docs/src/components/Since.astro b/packages/docs/src/components/Since.astro index 7c26bc9f..4dbeee8a 100644 --- a/packages/docs/src/components/Since.astro +++ b/packages/docs/src/components/Since.astro @@ -50,7 +50,7 @@ function getDefaultReleaseUrl(ver: string, fr: boolean): string { } // Fallback to the release on the changelog page const anchor = changelogAnchor(ver); - return `${prefix}/docs/changelog${anchor ? `#${anchor}` : ""}`; + return `${prefix}/changelog${anchor ? `#${anchor}` : ""}`; } const targetUrl = href || getDefaultReleaseUrl(cleanVersion, isFrench); diff --git a/packages/docs/src/components/SiteFooter.astro b/packages/docs/src/components/SiteFooter.astro index ed3b3cb1..148c90ac 100644 --- a/packages/docs/src/components/SiteFooter.astro +++ b/packages/docs/src/components/SiteFooter.astro @@ -77,7 +77,7 @@ const prefix = currentLang === "fr" ? "/fr" : "";
  • {langText.playground}
  • {langText.blog}
  • - {langText.changelog} + {langText.changelog}
diff --git a/packages/docs/src/components/SiteTitle.astro b/packages/docs/src/components/SiteTitle.astro index a8d7b5a6..e8088d22 100644 --- a/packages/docs/src/components/SiteTitle.astro +++ b/packages/docs/src/components/SiteTitle.astro @@ -4,8 +4,7 @@ import { GRAM_VERSION } from "../lib/gram-version"; const { locale } = Astro.locals.starlightRoute; const homeHref = locale === "fr" ? "/fr/" : "/"; const docsHref = locale === "fr" ? "/fr/docs/" : "/docs/"; -const changelogHref = - locale === "fr" ? "/fr/docs/changelog" : "/docs/changelog"; +const changelogHref = locale === "fr" ? "/fr/changelog" : "/changelog"; ---
diff --git a/packages/docs/src/content/blog/en/2026-08-07-release-1.0.1.md b/packages/docs/src/content/blog/en/2026-08-07-release-1.0.1.md index 53ac48aa..2f69b838 100644 --- a/packages/docs/src/content/blog/en/2026-08-07-release-1.0.1.md +++ b/packages/docs/src/content/blog/en/2026-08-07-release-1.0.1.md @@ -15,4 +15,4 @@ This is a small patch release that focuses on improving the `gram import` comman - **Improved CLI guidance**: The `gram import` command now correctly points to `gram db sync` as the next step and accurately reports missing ingredients. - **Clearer help text**: Clarified the description of the `gram check` command. -For the full list of changes, please refer to the [Changelog](/docs/changelog). +For the full list of changes, please refer to the [Changelog](/changelog). diff --git a/packages/docs/src/content/blog/en/2026-08-16-release-1.1.0.md b/packages/docs/src/content/blog/en/2026-08-16-release-1.1.0.md index 792d5d46..64b66566 100644 --- a/packages/docs/src/content/blog/en/2026-08-16-release-1.1.0.md +++ b/packages/docs/src/content/blog/en/2026-08-16-release-1.1.0.md @@ -43,4 +43,4 @@ All AI-assisted commands (`gram import`, `gram db lint`, `gram db enrich`) now s - **Shopping list**: Fixed a bug where composite ingredients with `&` were listed twice. - **Percentages in mass totals**: Ingredients defined with relative percentages (like `@water{60% @&flour}`) are now properly included in total weights. -For the detailed list of changes and commit history, head over to the [Changelog](/docs/changelog/#110---2026-08-16). As always, feedback is very welcome! +For the detailed list of changes and commit history, head over to the [Changelog](/changelog/#110---2026-08-16). As always, feedback is very welcome! diff --git a/packages/docs/src/content/blog/en/2026-08-22-release-1.2.0.md b/packages/docs/src/content/blog/en/2026-08-22-release-1.2.0.md index a183cf32..1de5d30a 100644 --- a/packages/docs/src/content/blog/en/2026-08-22-release-1.2.0.md +++ b/packages/docs/src/content/blog/en/2026-08-22-release-1.2.0.md @@ -63,6 +63,6 @@ The online [Playground](/play) has been updated with full multi-file support: - **Nutritional Totals**: Spliced intermediate masses (`-> &`) are now consistently included in overall recipe nutrition and weight totals. - **Section-Scoped Cycle Detection**: Fixed false circular reference warnings when multiple sections independently used percentage-of formulas on same-named ingredients. -For the full list of changes and commit history, check out the [Changelog](/docs/changelog/#120---2026-08-22). We'd love to hear your feedback! +For the full list of changes and commit history, check out the [Changelog](/changelog/#120---2026-08-22). We'd love to hear your feedback! diff --git a/packages/docs/src/content/blog/en/2026-08-25-release-1.2.1.md b/packages/docs/src/content/blog/en/2026-08-25-release-1.2.1.md index 88d7fb2e..0ea2e9b0 100644 --- a/packages/docs/src/content/blog/en/2026-08-25-release-1.2.1.md +++ b/packages/docs/src/content/blog/en/2026-08-25-release-1.2.1.md @@ -14,4 +14,4 @@ A recipe without quantities isn't very useful! `v1.2.1` is a quick patch to fix - **Renderer**: Switched icons to embedded inline SVGs, removing external CDN dependencies (`unpkg.com`) and enabling full offline previews in VS Code. - **Documentation & Playground**: Improved accessibility and keyboard navigation across the website and interactive playground (ARIA roles, tab navigation, `prefers-reduced-motion`). -For the complete list of changes, check out the [Changelog](/docs/changelog/#121---2026-08-25). +For the complete list of changes, check out the [Changelog](/changelog/#121---2026-08-25). diff --git a/packages/docs/src/content/blog/en/2026-09-29-release-1.3.0.md b/packages/docs/src/content/blog/en/2026-09-29-release-1.3.0.md index 984d298d..69a84b9e 100644 --- a/packages/docs/src/content/blog/en/2026-09-29-release-1.3.0.md +++ b/packages/docs/src/content/blog/en/2026-09-29-release-1.3.0.md @@ -24,4 +24,4 @@ In return, the compiler is stricter: an unreadable quantity inside braces (like - **Ingredient database**: Lookups in `ingredients.yaml` now resolve through slug normalization (e.g. `Huile d'olive` matches `huile-dolive`), avoiding false "missing nutrition" alerts during volume-to-mass conversions. `gram db lint` also catches ambiguous aliases. - **Modules**: Intermediates declared in imported modules display their authored name (`pressed`) instead of an internal path prefix, and syntax errors in the main recipe are no longer blamed on an "imported module". -For the complete list of changes, check out the [Changelog](/docs/changelog/#130---2026-09-29). +For the complete list of changes, check out the [Changelog](/changelog/#130---2026-09-29). diff --git a/packages/docs/src/content/blog/en/2026-11-13-release-1.4.0.md b/packages/docs/src/content/blog/en/2026-11-13-release-1.4.0.md index 61784172..75112a2d 100644 --- a/packages/docs/src/content/blog/en/2026-11-13-release-1.4.0.md +++ b/packages/docs/src/content/blog/en/2026-11-13-release-1.4.0.md @@ -103,6 +103,6 @@ Beyond these big milestones, a few quality-of-life polish items to make life eas Culinary scheduling and real-world time management are intricate problems, so edge cases might have slipped through despite extensive testing. If you run into any unexpected behavior with your recipes, please don't hesitate to open an [issue](https://git.gram-lang.org/gram-lang/gram/issues) on the repository—your feedback is invaluable to help me polish the engine! -Check out the [full changelog](/docs/changelog/#140---2026-11-13) for the complete list of changes in this release. +Check out the [full changelog](/changelog/#140---2026-11-13) for the complete list of changes in this release. Happy cooking with Gram 1.4.0! diff --git a/packages/docs/src/content/blog/en/2026-11-14-release-1.4.1.md b/packages/docs/src/content/blog/en/2026-11-14-release-1.4.1.md index 92a72e87..31fc4bd5 100644 --- a/packages/docs/src/content/blog/en/2026-11-14-release-1.4.1.md +++ b/packages/docs/src/content/blog/en/2026-11-14-release-1.4.1.md @@ -17,4 +17,4 @@ A first round of polish right after 1.4.0! `v1.4.1` is a quick patch to make qua - **Quantity and unit analysis**: an ingredient whose unit holds a quantity of its own (`@tomatoes{1 tin of 400 g}`) no longer falls back to the database's per-piece weight (previously, 1 tin was counted as 1 tomato, skewing the shopping-list total; its mass is now reported as unknown). Quantities split across two units (`@flour{1 cup 5 tbsp}`) or prefixed with words (`@flour{about 200g}`) now raise an `INVALID_UNIT` warning. - **Section-header parsing and errors**: a malformed section header now raises a clear error instead of a misleading message or silently losing the section, and a section header on the very last line without a trailing newline is now recognized. -For the complete list of changes, check out the [Changelog](/docs/changelog/#141---2026-11-14). +For the complete list of changes, check out the [Changelog](/changelog/#141---2026-11-14). diff --git a/packages/docs/src/content/blog/en/2026-11-17-release-1.4.2.md b/packages/docs/src/content/blog/en/2026-11-17-release-1.4.2.md index 68d91d11..be0d21e5 100644 --- a/packages/docs/src/content/blog/en/2026-11-17-release-1.4.2.md +++ b/packages/docs/src/content/blog/en/2026-11-17-release-1.4.2.md @@ -16,4 +16,4 @@ description: "Quick fixes for mixed-unit shopping lists and diffs, step spacing, - **Single-line preparations**: an unclosed parenthesis in a preparation note (`@flour{200g}(sifted and`) no longer swallows the rest of the recipe — preparations now stay on one line, and unclosed or multi-line notes remain plain text. - **Temperature formatting**: temperatures with a space and trailing zeros (`^{160.0 °C}`) now collapse to `^{160°C}` in a single run of the formatter. -For the complete list of changes, check out the [Changelog](/docs/changelog/#142---2026-11-17). +For the complete list of changes, check out the [Changelog](/changelog/#142---2026-11-17). diff --git a/packages/docs/src/content/blog/fr/2026-08-07-release-1.0.1.md b/packages/docs/src/content/blog/fr/2026-08-07-release-1.0.1.md index 92a7ded2..26fd5ac4 100644 --- a/packages/docs/src/content/blog/fr/2026-08-07-release-1.0.1.md +++ b/packages/docs/src/content/blog/fr/2026-08-07-release-1.0.1.md @@ -15,4 +15,4 @@ Il s'agit d'une version corrective mineure axée sur l'amélioration de la comma - **Meilleur guidage dans la CLI** : la commande `gram import` renvoie désormais correctement vers `gram db sync` comme étape suivante et signale précisément les ingrédients manquants. - **Texte d'aide plus clair** : clarification de la description de la commande `gram check`. -Pour consulter la liste complète des modifications, veuillez vous référer au [Changelog](/docs/changelog). +Pour consulter la liste complète des modifications, veuillez vous référer au [Changelog](/fr/changelog). diff --git a/packages/docs/src/content/blog/fr/2026-08-16-release-1.1.0.md b/packages/docs/src/content/blog/fr/2026-08-16-release-1.1.0.md index c4685fb8..84438213 100644 --- a/packages/docs/src/content/blog/fr/2026-08-16-release-1.1.0.md +++ b/packages/docs/src/content/blog/fr/2026-08-16-release-1.1.0.md @@ -43,5 +43,5 @@ Toutes les commandes utilisant l'IA (`gram import`, `gram db lint`, `gram db enr - **Liste de courses** : Correction d'un bug qui dupliquait certains ingrédients composites avec `&`. - **Pourcentages et masse totale** : Les ingrédients définis en pourcentage d'un autre (comme `@eau{60% @&farine}`) sont maintenant bien inclus dans le calcul du poids total. -Pour consulter l'ensemble des modifications techniques, vous pouvez vous référer au [Changelog](/docs/changelog/#110---2026-08-16). Comme d'habitude, les retours sont les bienvenus ! +Pour consulter l'ensemble des modifications techniques, vous pouvez vous référer au [Changelog](/fr/changelog/#110---2026-08-16). Comme d'habitude, les retours sont les bienvenus ! diff --git a/packages/docs/src/content/blog/fr/2026-08-22-release-1.2.0.md b/packages/docs/src/content/blog/fr/2026-08-22-release-1.2.0.md index 4c244457..d7e38c17 100644 --- a/packages/docs/src/content/blog/fr/2026-08-22-release-1.2.0.md +++ b/packages/docs/src/content/blog/fr/2026-08-22-release-1.2.0.md @@ -63,4 +63,4 @@ Le [Playground en ligne](/fr/play) a lui aussi été mis à jour pour prendre en - **Totaux nutritionnels complets** : La masse des intermédiaires injectés (`-> &`) est maintenant bien prise en compte dans le calcul du poids total et des macronutriments de la recette. - **Détection des cycles par section** : Suppression d'une fausse alerte de référence circulaire qui pouvait survenir lorsque deux sections distinctes utilisaient des pourcentages relatifs sur des ingrédients portant le même nom. -Pour retrouver le détail de tous les changements techniques, n'hésitez pas à consulter le [Changelog](/docs/changelog/#120---2026-08-22). Comme toujours, vos retours et suggestions sont les bienvenus ! \ No newline at end of file +Pour retrouver le détail de tous les changements techniques, n'hésitez pas à consulter le [Changelog](/fr/changelog/#120---2026-08-22). Comme toujours, vos retours et suggestions sont les bienvenus ! \ No newline at end of file diff --git a/packages/docs/src/content/blog/fr/2026-08-25-release-1.2.1.md b/packages/docs/src/content/blog/fr/2026-08-25-release-1.2.1.md index 6e618d82..9630c007 100644 --- a/packages/docs/src/content/blog/fr/2026-08-25-release-1.2.1.md +++ b/packages/docs/src/content/blog/fr/2026-08-25-release-1.2.1.md @@ -14,4 +14,4 @@ Une recette sans quantités, c'est tout de suite moins pratique ! La version `v1 - **Rendu & Icônes SVG** : intégration directe des icônes SVG dans le code généré pour supprimer la dépendance CDN (`unpkg.com`) et permettre la prévisualisation hors-ligne dans VS Code. - **Accessibilité du site et du playground** : amélioration de l'accessibilité et de la navigation au clavier sur le site et le playground interactif (rôles ARIA, onglets, support de `prefers-reduced-motion`). -Pour retrouver l'ensemble des détails, consultez le [Changelog](/docs/changelog/#121---2026-08-25). +Pour retrouver l'ensemble des détails, consultez le [Changelog](/fr/changelog/#121---2026-08-25). diff --git a/packages/docs/src/content/blog/fr/2026-09-29-release-1.3.0.md b/packages/docs/src/content/blog/fr/2026-09-29-release-1.3.0.md index 00eba536..b52d8575 100644 --- a/packages/docs/src/content/blog/fr/2026-09-29-release-1.3.0.md +++ b/packages/docs/src/content/blog/fr/2026-09-29-release-1.3.0.md @@ -24,4 +24,4 @@ En contrepartie, le compilateur devient plus rigoureux : une quantité malformé - **Base d'ingrédients** : résolution insensible aux variantes de casse et tirets dans `ingredients.yaml` (ex. `Huile d'olive` associée à `huile-dolive`) pour fiabiliser la conversion en grammes et la nutrition. La commande `gram db lint` signale également les alias en conflit. - **Modules** : les intermédiaires de modules importés conservent leur nom d'origine (`pressed`) au lieu d'un identifiant interne préfixé, et les erreurs de syntaxe du fichier courant ne sont plus attribuées à tort à un module tiers. -Pour retrouver le détail complet des changements, consultez le [Changelog](/docs/changelog/#130---2026-09-29). +Pour retrouver le détail complet des changements, consultez le [Changelog](/fr/changelog/#130---2026-09-29). diff --git a/packages/docs/src/content/blog/fr/2026-11-13-release-1.4.0.md b/packages/docs/src/content/blog/fr/2026-11-13-release-1.4.0.md index 5f17be80..8b7ecae1 100644 --- a/packages/docs/src/content/blog/fr/2026-11-13-release-1.4.0.md +++ b/packages/docs/src/content/blog/fr/2026-11-13-release-1.4.0.md @@ -102,6 +102,6 @@ Au-delà de ces gros changements, quelques petites améliorations pour se simpli L'ordonnancement culinaire et la gestion fine du temps étant des sujets particulièrement complexes, il est tout à fait possible que des cas limites m'aient échappé malgré une batterie de tests intensifs. Si vous rencontrez le moindre comportement inattendu sur l'une de vos recettes, n'hésitez surtout pas à ouvrir un [ticket](https://git.gram-lang.org/gram-lang/gram/issues) sur le dépôt : vos retours me sont précieux pour perfectionner le moteur ! -Consultez le [Changelog complet](/docs/changelog/#140---2026-11-13) pour parcourir la liste détaillée de tous les changements de cette version. +Consultez le [Changelog complet](/fr/changelog/#140---2026-11-13) pour parcourir la liste détaillée de tous les changements de cette version. Bonne cuisine avec Gram 1.4.0 ! diff --git a/packages/docs/src/content/blog/fr/2026-11-14-release-1.4.1.md b/packages/docs/src/content/blog/fr/2026-11-14-release-1.4.1.md index 406c90db..74fc3930 100644 --- a/packages/docs/src/content/blog/fr/2026-11-14-release-1.4.1.md +++ b/packages/docs/src/content/blog/fr/2026-11-14-release-1.4.1.md @@ -17,4 +17,4 @@ Cette version `v1.4.1` est un correctif rapide pour soigner la lecture des quant - **Analyse des quantités et unités** : une unité qui contient déjà une quantité (`@tomates{1 boîte de 400 g}`) n'utilise plus le poids à la pièce de la base (auparavant, 1 boîte était comptée comme 1 tomate, ce qui faussait le total de la liste de courses ; sa masse est désormais laissée inconnue). De plus, les quantités à deux unités (`@farine{1 cup 5 tbsp}`) ou précédées de mots (`@farine{environ 200g}`) lèvent désormais un avertissement `INVALID_UNIT`. - **Erreurs sur les en-têtes de section** : un en-tête de section mal écrit renvoie désormais une erreur claire plutôt qu'un message trompeur ou une perte silencieuse de la section, et un en-tête placé en toute fin de fichier sans saut de ligne final est bien reconnu. -Pour retrouver l'ensemble des détails, consultez le [Changelog](/docs/changelog/#141---2026-11-14). +Pour retrouver l'ensemble des détails, consultez le [Changelog](/fr/changelog/#141---2026-11-14). diff --git a/packages/docs/src/content/blog/fr/2026-11-17-release-1.4.2.md b/packages/docs/src/content/blog/fr/2026-11-17-release-1.4.2.md index a935de9f..6bc32e59 100644 --- a/packages/docs/src/content/blog/fr/2026-11-17-release-1.4.2.md +++ b/packages/docs/src/content/blog/fr/2026-11-17-release-1.4.2.md @@ -16,4 +16,4 @@ La version `v1.4.2` regroupe quelques petits correctifs repérés en travaillant - **Préparations sur une seule ligne** : une parenthèse non fermée dans une note de préparation (`@farine{200g}(tamisée et`) n'avale plus la suite de la recette ; les préparations restent sur leur ligne et les parenthèses ouvertes ou sur plusieurs lignes restent du simple texte. - **Formatage des températures** : une température écrite avec un espace et des zéros finaux (`^{160.0 °C}`) est désormais ramenée à `^{160°C}` en un seul passage du formateur. -Pour retrouver l'ensemble des détails, consultez le [Changelog](/docs/changelog/#142---2026-11-17). +Pour retrouver l'ensemble des détails, consultez le [Changelog](/fr/changelog/#142---2026-11-17). diff --git a/packages/docs/src/content/docs/docs/changelog.md b/packages/docs/src/content/docs/docs/changelog.md deleted file mode 100644 index 28580cb7..00000000 --- a/packages/docs/src/content/docs/docs/changelog.md +++ /dev/null @@ -1,818 +0,0 @@ ---- -title: Changelog -description: Every release of Gram — new features, fixes, and breaking changes. -tableOfContents: - minHeadingLevel: 2 - maxHeadingLevel: 2 ---- - -## [1.4.2](https://git.gram-lang.org/gram-lang/gram/compare/v.1.4.1...v.1.4.2) - 2026-11-17 - -### Bug fixes and improvements -- **CLI / Cook**: Fixed `gram cook` timers that never finished: a timer now rings when its time is up and shows as done, ready to be dismissed with any key. -- **Format**: Fixed a temperature written with a space and trailing zeros, such as `^{160.0 °C}`, that took two runs of the formatter to become `^{160°C}`: it is now fixed in one. -- **Parser**: Fixed an unclosed parenthesis in a preparation note (such as `@flour{200g}(sifted and`) swallowing the rest of the recipe up to the next `)`, including later steps and sections. Preparations now stay on one line, so an unclosed `(` or a note split across lines is kept as plain step text. -- **Kitchen, Analyzer, Renderer & CLI**: Fixed lost, split, or skipped ingredient quantities across shopping lists, views, and diffs: - - Shopping lists now merge different spellings of the same unit (`1 cup` and `2 cups`, `1 c.à.s` and `2 tbsp`) onto a single line, which also makes those ingredients work again with `gram scale --target`. - - The HTML view now displays every quantity when an ingredient uses multiple units in the same section (`100 g + 1 cup`), instead of showing only the first. - - `gram shop` no longer drops ingredients whose quantity cannot be computed (such as a percentage of a missing intermediate) and lists them as written. - - `gram diff` now compares each unit separately when an ingredient appears in multiple units, and ignores changes that only affect how a unit is spelled. -- **Renderer**: Fixed a missing space between two consecutive elements in a step, such as an ingredient followed by a timer or cookware (`@flour{500 g} ~{1h}` rendered as "flour (500 g)1 h"), across all views and `gram view`. - ---- - -## [1.4.1](https://git.gram-lang.org/gram-lang/gram/compare/v.1.4.0...v.1.4.1) - 2026-11-14 - -### Bug fixes and improvements -- **Parser**: Section headers with leftover text after an anchor or intermediate (such as a multi-word `->&glazed rhubarb` missing braces) now raise a clear error instead of blaming the timer or turning the section into a step, and a section header on the last line with no trailing newline is now recognized. -- **Kitchen**: Split quantities across two units (`@flour{1 cup 5 tbsp}`) or prefixed with words (`@flour{about 200g}`) now raise an `INVALID_UNIT` warning instead of being misread or dropped when scaling (while unit-only descriptors like `{1 tin of 400 g}` or `{a pinch}` remain valid). -- **Analyzer**: An ingredient whose unit holds a quantity of its own (`@tomatoes{1 tin of 400 g}`) no longer falls back to the database's per-piece weight (which counted one tin as one tomato); its mass is reported as unknown until Gram parses the inner quantity. -- **Renderer**: Hovering a preparation (`&dough`) in HTML now highlights the entire section that makes it, `formatFraction` is now applied to ingredient quantities across recipe views, and ingredients written in `kg` or `mg` no longer repeat their standardized mass next to them. -- **Renderer & CLI**: Totals where you buy or read an overview (shopping list, recipe/section weight, nutrition base, `gram shop`) convert metric amounts from 1000 g/ml up to `kg` or `l` (`3.9 kg` instead of `3900 g`), while steps, section ingredients, the run sheet, and `gram cook` keep grams for weighing (API helpers: `toLargerMetricUnit`, `isMetricMassUnit` in `@gram-lang/i18n`). -- **Renderer & CLI**: Numbers follow the recipe's language (`lang` / project `language`, with decimal commas in French and no thousands separators in `gram shop`/`gram scale`), and spoons, cups, and imperial measures display as fractions (`1 3/4 cup`) across views and CLI commands while keeping machine attributes unchanged (API helpers: `formatNumber`, `localizeDecimals`, `toKitchenFraction` in `@gram-lang/i18n`). -- **CLI / Cook**: Timer countdowns in `gram cook` now honor the unit written in the recipe (`~{1h}` counts down 1 hour and `~{30 s}` 30 seconds, instead of treating every timer as minutes). - ---- - -## [1.4.0](https://git.gram-lang.org/gram-lang/gram/compare/v.1.3.0...v.1.4.0) - 2026-11-13 - -### New features -- **Scheduler**: The planning engine now lives in its own package, `@gram-lang/scheduler`, which `@gram-lang/kitchen` uses. Compiled recipes keep every field published in 1.3.0, and everything `@gram-lang/kitchen` exported before is still exported from it: - - `layout(tasks, { miseEnPlace, rests })` lays a recipe's list of tasks out on a timeline, for any mise en place plan and any choice of waits, and reports what cannot work (a time paradox, a track contention, a working day pushed before its 24 hours) - - `project(recipes, context)` places a recipe on the calendar from a serving time, a time zone and when the cook is available; it stretches or shortens the waits written as a range so the cook's own work avoids the night, and reports what it could not fix - - `runSheet(plan)` groups a plan into the days of the recipe, the visits to the kitchen (with the sections each one cooks and how early it could be done) and the waits that go on without the cook - - `findServeTimes()` ranks the serving times that work over a range of days, with the reasons of the others, and `earliestServe()` gives the first one that works if the cook starts now - - `parseAvailability()`, `parseMealTimes()` and the other readers of a project's settings (`08:00-22:00`, `fri=18:00-22:00`, `2026-10-09=none`) are shared by the CLI and the editor -- **Kitchen**: Recipes now know when each part of the mise en place should happen: - - New fields on the compiled recipe: `miseEnPlace` (how long each section's own preparation takes), `tasks` (the list of tasks and what each one waits for), `schedule` (a default timeline, with the preparation right before each section and the shortest rests), `days` (the working days of a timeline) and `generator` (the version that compiled it). A recipe with no step at all now has a preparation time of 0 - - Any other timeline comes from the same list, without compiling again: all the preparation at the start (`upfront`) or at the start of each working day (`perDay`), with the shortest, middle or longest of every rest written as a range (new `layout()`, from `@gram-lang/scheduler`) - - A timer is exact (`~_{12h}` lasts exactly 12 hours); a rest written as a range (`~_{12-24h}`) is planned on its shortest figure unless you pick another, and an active timer written as a range (`~{20-25min}`) on its longest, so dinner is never late. Only an anchor in days (`~{-1d}`) opens a working day - - New warnings: `DAY_OVERFLOW` flags a working day pushed before its 24 hours by a long rest, `DURATION_OUT_OF_RANGE` flags a duration over 1000 years (capped, instead of breaking the timeline with `0`, `Infinity` or `NaN`), and a `PASSIVE_OVERLAP_SAME_COOKWARE` notice flags two passive timers that overlap on the same cookware with no named track in common - - An intermediate (`&dough`) is gathered in the section that uses it, and JSON compiled before 1.4.0 still gets a total and idle time in the renderer outputs, the editor hint and `gram diff` -- **Run sheet**: A new run sheet shows what the scheduler computed, and replaces the Gantt chart as the view of the schedule: - - `runSheetToText`, `runSheetToMarkdown`, `runSheetToHTML` and `runSheetToPrintHTML` write the plan: the days of the recipe, then for each visit to the kitchen a worksheet in three parts: the mise en place (what to take out, with the weights, the preparations made before and the bases in stock), the execution (the steps of each section, numbered as in the recipe) and what to do on leaving (what goes on afterwards, and when to come back) - - Each visit says how early it could be done ("Possible from 18:00") or which wait holds it in place, and a wait the plan stretched or shortened is reported on its day - - A recipe with no serving time is told in days before the service (D-2, D-1, day D); the printed plan has one day per page, with boxes to tick for the mise en place - - The recipe views no longer carry schedule details: the run sheet is its own view. For developers, `describeRunSheet()` gives the same plan in words -- **Renderer / Mise en place**: The mise en place can now be planned right before each section, all at the start, or at the start of each working day: - - New `miseEnPlace` option (`"perSection"` by default, `"upfront"` or `"perDay"`) on the HTML, Markdown and print outputs, and a new `rests` option (`"shortest"` by default, `"balanced"` or `"longest"`) for the waits written as a range (`~_{12-24h}`) - - The total time follows the chosen schedule, and its tooltip explains how it adds up (preparation, active time and waits), then points to the run sheet for the hour-by-hour plan - - The recipe no longer shows the waiting time on its own, in any format: it is counted in the total time, and the run sheet is where the waits are planned -- **CLI / Plan**: A new `gram plan ` command plans a recipe: the days of work, the visits to the kitchen, what to take out and which steps of each section to read: - - `--serve "2026-10-11 13:00"` plans it backward from the time it is served; without it, the plan is told in days before the service (D-2, D-1, day D) and ends with the earliest time it could be ready if you start now - - `--tz Europe/Paris` sets the time zone and `--available` says when you can cook (`08:00-22:00` for every day, `fri=18:00-22:00` for a day of the week, `2026-10-09=none` for a date). By default they come from the new `timezone` and `availability` settings of `.gram/config.yaml` (`gram config set availability 08:00-22:00`), and only then from this machine - - A wait written as a range (`~_{8-16h}`) is made longer or shorter to keep your own work out of the hours you are not available, and the plan says which one and why; what cannot be fixed is listed at the top - - `--find 2026-10-12/2026-10-15` lists the serving times that work between two moments, at your meal times (`--meal-times 12:30,20:00`, or the new `mealTimes` setting), best first, and why each of the others does not - - `--format text|md|html|json` picks the output, and `--ics plan.ics` also writes a calendar file with an event and an alarm for every visit to the kitchen - - `--mise-en-place`, `--rests`, `--scale` and `--stock` work as they do in `gram view` -- **CLI / Run sheet**: `gram export` and `gram print` can now write the run sheet instead of the recipe: - - `--view run-sheet` (the recipe remains the default) supports `--serve`, `--tz` and `--available`; without `--serve`, the plan is told in days before the service (`D-2`, `D-1`, `Day D`) - - `gram export` writes `.run-sheet.md` (or `.html`, `.txt`) next to the recipe unless `--output` is given, and `gram print` puts one day per page - - Each view offers only the formats it has: asking the recipe for `--format text` says which formats it offers instead of writing something else -- **CLI / View & Export**: `gram view`, `gram export` and `gram print` accept a new `--mise-en-place ` option, to see the recipe with the mise en place planned right before each section (the default), all at the start, or at the start of each working day: - - A new `--rests ` option does the same for a wait written as a range (`~_{12-24h}`): the shortest by default, the middle or the longest, in the total time as in the length shown on the step itself - - `gram cook` accepts both options too, for the total time it shows and the length of the timer of such a wait -- **VS Code / Run sheet**: The editor shows the run sheet of the recipe in place of the Gantt chart: - - A new `Gram: Run Sheet` command opens it next to the recipe, in days before the service (D-2, D-1, day D); it follows the `gram.miseEnPlace`, `gram.rests` and `gram.comments` settings - - A **Served at** field at the top of the run sheet puts it on the calendar, with dates and clock times, in your project's time zone and hours (`timezone` and `availability` in `.gram/config.yaml`); **When to serve?** proposes the times that work over the next seven days, the earliest first, and says why the others do not. The serving time is kept per recipe while VS Code is open, never saved - - A **Scale and stock** section at the top of the recipe and of the run sheet adjusts this sitting, as `--scale`, `--stock` and `--bakers-reference` do in the CLI: a scale in percent or a target quantity of one ingredient, the baker's reference, and the imports already made. These choices are shared by every panel of the recipe and kept while VS Code is open, never saved -- **Analyzer / Diff**: `gram diff` now compares the total and idle times of the default schedule, with the mise en place right before each section, so the times it reports match what `gram view` shows by default; the active time is the schedule's too, so changing the range of a cooking time (`~{20-25min}`, planned on its longest figure) shows in the comparison, and the preparation time is compared as before -- **CLI / Settings**: Every setting of a recipe now has a flag named after it, on every command where it changes something, with the same values and default as in the editor and the playground: - - `--step-quantities show|hide` and `--nutrition-basis` are the new names of `--no-step-qty` and `--nutrition`, which still work - - What the analyzer computes can now be turned off on `gram view`, `gram print`, `gram export`, `gram cook`, `gram build`, `gram watch` and `gram shop`: `--no-mass-standardization`, `--no-yield-calculation`, `--no-nutrition-estimation` and `--no-bakers-math`; everything stays on by default - - An unknown value stops the command and lists the values it accepts, under the name you typed -- **VS Code / Settings**: The editor now offers every setting of a recipe, with the same values and default as the command line and the playground: - - `gram.miseEnPlace` (`perSection`, the default, `upfront` or `perDay`) chooses when the mise en place is planned, and `gram.rests` (`shortest`, the default, `balanced` or `longest`) how long a rest written as a range (`~_{12-24h}`) lasts; the preview, the run sheet and the total time hint next to the recipe title all follow them - - `gram.stepQuantities` writes the quantities in the text of the steps, or leaves them out, `gram.nutritionBasis` pins the basis of the nutrition (`auto` is the default) and `gram.bakersMathOnly` shows only the baker's percentages - - `gram.bakersMath`, `gram.massStandardization`, `gram.yieldCalculation` and `gram.nutritionEstimation` choose what is computed from the ingredient database; all are on by default - - Changing a `gram.*` setting now reaches the language server straight away, without reloading the window (this also applies to `gram.ingredientDatabase.path`), updates every open recipe, and a recipe already open when the editor starts follows it too -- **Renderer / Settings**: The renderer now describes, in one place, every setting a reader can choose about a recipe, so that tools built on Gram can offer the same choices as the command line, the editor and the playground: - - `VIEW_SETTINGS` lists what the views show (mise en place, rests, comments, nutrition basis, baker's percentages only, quantities in the steps) and `RECIPE_SETTINGS` what the analyzer computes (baker's percentages, weights in grams, preparation losses, nutrition), each with its values, its default and a short description - - `parseViewSettings()` and `parseRecipeSettings()` read them from any configuration object, and fall back on the default for anything missing or unknown, so a mistyped setting never blanks a view - - `viewSettingsToRendererOptions()` and `recipeSettingsToAnalyzerOptions()` turn them into the options of the renderer and of the analyzer -- **Comments**: You can now choose whether the comments of a recipe (`// like this`) are shown or left out, in every view: - - The renderer takes a new `comments: "show" | "hide"` option (default `"show"`) that the recipe views, the print and the run sheet follow; hiding leaves no empty notes section behind - - `gram export`, `gram print` and `gram plan` accept `--comments `, and the editor has a new `gram.comments` setting for the preview and the run sheet; the playground gets a **Display** section with a switch - - In the run sheet, a note alone on a line sits under its step in small muted text, and one at the end of a line stays in the sentence, between parentheses -- **Renderer / HTML recipe**: The HTML recipe has a new design, and the printed recipe follows it: - - A better organized header (title, description, author, source, tags), a summary bar with the portions, the yield, the mass and the energy, and a bar for the times - - Tooltips that stay readable wherever they open in the window, with more practical information: quantity, weight and how it was estimated, preparation, what a part is taken from - - A more interactive recipe: hover an ingredient or a piece of cookware to see the steps that use it, tick the steps off, and follow what a step makes to the steps that use it - - The printed recipe (`gram print`, `gram export --format html`) now looks like the one on screen, in black and white, with boxes to tick - - Each view keeps its own styles (`@gram-lang/renderer/gram.css` is imported as before and relies on the CSS `@scope` rule, supported by every current browser), so one view can no longer change another -- **Renderer / Nutrition**: The nutrition of the HTML recipe is now a compact table, like a European food label, and easy to reach from the top of the recipe: - - One column per basis, side by side (per 100 g, then per portion), with the energy as the first row in kJ and kcal and the whole recipe underneath; no more switching between bases - - A `%RI` column gives each nutrient's share of the reference intake of an average adult (8,400 kJ / 2,000 kcal), per portion - - The hero bar shows the energy (`493 kcal per portion`, or per 100 g when the recipe declares no portions); clicking it jumps to the table - - Sodium is now shown as salt, in grams (sodium × 2.5), and calories as energy, in every view and every language - - With the `nutritionBasis` setting set to one basis, the table and the hero bar show that basis alone - - The Markdown and plain text recipes show the same table by default, instead of the values per portion only -- **Renderer / Quantities**: Quantities read the same in every format, on screen and on paper: - - The quantity is written after its ingredient in the text of each step in the HTML views and the print, as Markdown already did, so a printed recipe shows them too, and the weight in grams is written next to the quantity as written in the recipe whenever it tells something more (`flour (250 ml, ~148 g)`, but `sugar (100 g)`), in Markdown as well - - Hiding the quantities of the steps (`hideStepQty`) now works in the HTML views and the print, not only in Markdown -- **Renderer / Durations**: Durations read more naturally, in the reader's language: - - A duration of a day or more is written in days and hours (a recipe of 25 hours shows `1d 1h`, `1j 1h` in French), and minutes are written `min` (`1h 30min`), in every view; the total time tooltip ends on the exact total (`= 25h 6min`) - - `formatDuration()` takes the language as an optional second argument and `{ days: false }` as a third, and a new `durationUnits` entry of `@gram-lang/i18n` holds the units of each language -- **Renderer / Text**: The recipe can now be written as plain text, for a terminal or a plain file: - - A box with the title, the servings and the times, then the shopping list, the cookware, each section with its numbered steps, the notes and the nutrition, in the reader's language and following the same settings as the other formats - - `gram export --format text` writes it next to the recipe (`brioche.txt`), and the playground offers it as a format of the recipe; for developers, `toText()` and the `text` format of the recipe view - - The Markdown, HTML and print versions of the recipe now speak the reader's language too: "Instructions", "Ingredients", "or", "optional" and the other words that were always in English follow the language setting (the English output is unchanged) -- **CLI / View**: `gram view` now shows the recipe the way every other view of Gram does: - - The headings, the labels and the nutrition follow the language of your project, instead of always being English - - The steps repeat the quantity next to each ingredient (`flour (200 g)`), comments are shown as notes (`--comments hide` leaves them out), and a wait written as a range (`8-16 h`) is shown as written - - The colors follow your terminal: plain text when the output goes to a file or another command, `NO_COLOR` respected, `FORCE_COLOR=1` to keep them in `gram view | less -R` -- **Renderer / Views**: A new `prepareViews()` gathers everything a view of a recipe is built from, worked out once and only when a view asks for it (the timeline, the run sheet, the serving time search): - - `views` lists the views of a recipe (the recipe, the run sheet) with the formats each one offers, the settings it follows and what it needs worked out, and `render(view, input, format)` writes one of them; `toHTML`, `runSheetToHTML` and the other functions stay as they are - - `inspectors` lists the looks at the pipeline (the composed AST as an S-expression, the analyzed recipe as JSON or as a folding tree) and `outputs` lists the views and the inspectors together, for an interface that offers both - - `describeError()` picks the error to show when a recipe stops compiling and gives its code, message, file, position and a title in the recipe's language, so every interface reports it the same way, and `suggestServeTimes()` puts the serving time search in words -- **Language Server / Views**: Editors can now request only active views through a dedicated views protocol: - - A client declaring `initializationOptions.views` specifies open recipe outputs via `gram/setOpenViews` and receives targeted updates in `gram/viewUpdated`: recipe and run sheet views as HTML, or AST and compiled JSON as text or interactive trees. Closed outputs are no longer evaluated - - When a recipe encounters compilation errors, open outputs are paused rather than replaced by an error card: editors retain their last valid rendered view, while localized error summaries are provided alongside standard LSP diagnostics - - `gram/setSession` configures transient session parameters for a recipe: target serving time (projecting the run sheet onto the calendar in the project's `timezone` and within its `availability`), scaling factor, pre-prepared imports in stock, and baker's percentage reference. Sessions are held per document in memory, while compiler diagnostics continue evaluating the recipe as written - - The outputs a client can open are listed in the `initialize` result, each with its name in the editor's language and what it reads from the plan, so an editor shows a new view of Gram without an update of its own, and offers a serving time for any view laid out in time - - A `gram/serveTimes` request gives the serving times to propose for a recipe, in words: those that work over the next seven days at the project's `mealTimes`, why the others do not, and the earliest one - - A `gram/sessionChoices` request gives what session controls offer for a recipe as written: its ingredients, its `@use` imports (nested ones included), whether baker's math is on, and why the session's scale could not be applied - - Editing `.gram/config.yaml` (its `timezone`, `availability` or `paths`) now updates the open recipes and their views right away, instead of at their next edit -- **VS Code / Views**: Unified view panels and new developer inspectors: - - A new `Gram: Show View...` command lists all available views and opens the selected one: recipe preview, run sheet, and developer inspectors (composed AST and compiled JSON, as source text or an interactive tree). `Gram: Live Preview`, `Gram: Run Sheet` and `Gram: Macros` remain available as direct shortcuts - - Open panels follow the active `.gram` editor tab, refresh when brought back into focus, and the language server computes only the panels that are visible - - When a recipe contains errors, panels keep their last valid rendering, dimmed beneath a banner with a button that jumps to the error, instead of going blank - - The live preview always shows the nutrition summary, as the playground does: the **Macros** button is gone, and `Gram: Macros` scrolls to the table - - The **Scale and stock** section has a **Portions** field, shown when the recipe states its portions, that scales the recipe when you change it -- **Playground**: The views of a recipe are now in front, and the studio offers every setting: - - The recipe and the run sheet are tabs above the output, always in sight. The inspectors (the AST, the JSON, the JSON tree) sit behind one quieter Inspect tab on the right, and turn into a dropdown when the tabs no longer fit, on a phone or in a narrow output column - - A slim bar above the view holds what changes with it, starting with a format menu that shows the view as HTML, Markdown or text (the run sheet can now be read and copied in Markdown and in plain text too), and a Print button opens the view in its print layout, to print it or save it as a PDF - - Every setting of a recipe is now offered, including the quantities in the steps and the nutrition basis, and remembered in the browser (except the serving time, which belongs to the visit); yield management and baker's percentages are on by default, as on the command line and in the editor - - The "Schedule & Service" settings say what they change (mostly the run sheet, and in the recipe only the total and idle times), and the "Portions & Scale" settings have a Portions field, opened by a click on the portions of the recipe, which replaces the small stepper the recipe used to show -- **I18n**: A new `fillTemplate(template, values)` fills the `{name}` placeholders of a dictionary string (`"Serve at {time}"` becomes `"Serve at 20:00"`), leaving a name with no value as written. - -### Bug fixes and improvements -- **Kitchen**: Scaling an already compiled recipe (`applyScale`) now also scales the quantity a step quotes for an intermediate (`Use &dough{100g}`), so it gives the same result as compiling the recipe with that scale factor -- **CLI / Stock**: `gram view`, `gram cook`, `gram check`, `gram scale`, `gram export` and `gram print` now warn on stderr when a `--stock` entry matches none of the recipe's `@use`, as `gram build` and `gram shop` already did, instead of ignoring it silently — most often a relative path typed from another directory, since it is resolved from the current directory -- **Language Server / Diagnostics**: Fixed diagnostics and previews that could go back to an older version of a recipe until the next edit, when it was edited quickly while its imports were being read. -- **CLI**: Every command now stops on an unexpected error the same way: a one-line message instead of a stack trace, which `--verbose` still shows. -- **Renderer / Markdown**: The Markdown recipe is tidier: the headings and alerts have no more emoji prefixes, a blank line separates the notes from the nutrition, and temperatures show a thermometer (`🌡️ 180 °C`, `🌡️ fridge`) instead of a flame. -- **Playground**: The Recipe Studio drawer is fully translated, in English and French: the scheduling settings, the summary of each section, the explanation of every setting, the physical analysis and the list of serving times that do not work, and the serving time field is called "Serving time" ("Heure de service" in French). - -#### Deprecated -- Renderer: the Gantt chart (`toGanttHTML`, `attachGanttInteractivity`, `formatTime`, `formatAxisTime`, the `Gantt*` types), `@gram-lang/renderer/gantt.css` and the `gantt_*` strings of the playground, removed in 2.0.0. No Gram surface draws it any more. Use the run sheet (`runSheetToHTML`), or build a view of your own from the data of `runSheet()`; `toGanttHTML` warns once on the console. The Deprecated features page shows how: https://gram-lang.org/docs/how-to/deprecations/ -- Kitchen: `steps[].timings` and `steps[].backgroundTasks`, removed in 2.0.0. Read the `step` and `passive` blocks of `schedule.blocks` instead -- Kitchen: `metrics.totalTime` and `metrics.idleTime`, removed in 2.0.0. Read `schedule.totalTime` and `schedule.idleTime` instead (the old `metrics.totalTime` is the total with every preparation first: `layout(tasks, { miseEnPlace: "upfront" })` gives the same number unless the recipe has intermediates, which it prepares once they exist) -- Kitchen: `metrics.activeTime`, removed in 2.0.0. Read `schedule.activeTime` instead (a timer written as a range counts as its average in `metrics.activeTime`, and as its longest figure in the schedule) -- Kitchen: `metrics.activeBreakdown`, `metrics.prepBreakdown` and `metrics.totalBreakdown`, removed in 2.0.0. Use `miseEnPlace` and `schedule` instead -- Kitchen: the `breakdown` returned by `calculatePreparationTime`, removed in 2.0.0 (the function then returns `{ total }`, so code reading `total` is unaffected). Read the `items` of `computeMiseEnPlace()` instead -- Kitchen: reading the old `metrics` fields when compiled JSON has no `tasks` (JSON compiled before 1.4.0), removed in 2.0.0. Compile your recipes again with 1.4.0 or later -- Everything above keeps working, with the same values, until 2.0.0. The Deprecated features page shows what to change for each of them: https://gram-lang.org/docs/how-to/deprecations/ -- VS Code: the `Gram: Gantt Chart` command, removed in 2.0.0. It still works and opens the run sheet, with a notice once. Use `Gram: Run Sheet` -- Language server: the `gram/ganttUpdated` notification, removed in 2.0.0. It is still sent to clients that do not declare the views protocol, and the VS Code extension no longer reads it. Read `gram/viewUpdated` with the `runSheet` output, or the data of the compiled recipe -- Renderer: the `interactiveScaling` option of `toHTML()`, and the `decreasePortions`, `increasePortions` and `editPortions` strings of `@gram-lang/i18n`, removed in 2.0.0. The portions stepper they draw only works where the page around the recipe handles its buttons, so it did nothing in an exported file or an editor preview. Scale the recipe before rendering it instead (`applyScale()` of `@gram-lang/kitchen`): the recipe then shows its portions and its scale factor by itself. The option keeps working until 2.0.0 -- Renderer: the `interactiveNutrition` option no longer has any effect, since every basis is shown at once, and is removed in 2.0.0. Remove it from your calls -- Language Server: the `gram/previewUpdated` notification, sent to clients that do not declare the views protocol, is deprecated and will be removed in 2.0.0. Adopt `gram/viewUpdated` with the `recipe` output instead (see the deprecations page of the docs) -- `@gram-lang/i18n`: the labels of the old view selector (`playground.viewLabel`, and `playground.views.json`, `ast`, `jsonTree`, `markdown`, `preview` and `runSheet`) are removed in 2.0.0. Use `renderer.outputs` (by output id), `renderer.formats` and `playground.output.views` / `inspect` - ---- - -## [1.3.0](https://git.gram-lang.org/gram-lang/gram/compare/v.1.2.1...v.1.3.0) - 2026-09-29 - -### New features -- **CLI / Requirements**: The CLI now requires Node.js 22 or later (Bun keeps working as before). -- **Parser & Kitchen**: Units written with abbreviation dots are now understood: - - `{1/2 c.à.s}`, `{1 c. à c.}`, `{2 fl. oz.}` and similar spellings now parse and are recognized as the same unit as `càs`, `càc` or `fl oz` - -### Bug fixes and improvements -- **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`. -- **Modules**: Fixed a misleading error message: a syntax error in the recipe you are editing was reported as coming from an "imported module", even when the recipe imports nothing. It now shows the plain syntax error, and the "imported module" wording is kept only for errors that really are in an imported file. -- **Analyzer**: Fixed ingredients being ignored for density conversion and nutrition when their entry in `ingredients.yaml` isn't spelled exactly like the recipe name, such as "Huile d'olive" stored under `huile-dolive`: - - Volumes like `@Huile d'olive{10ml}` are now converted to grams and no longer trigger "ingredient missing nutrition data" - - `gram db lint` now reports ingredients whose names or aliases would be confused with each other -- **Modules & Rendering**: Intermediates declared inside imported modules now show the name you wrote (for example `pressed`) instead of an internal path like `tofu$marinated$pressed`, in `gram view`, HTML and Markdown output. - -#### Breaking -- **CLI**: Node.js 20 reached end of life in April 2026 and is no longer supported: upgrade to Node.js 22+ before updating the CLI - -#### Fixed -- **Parser**: A quantity in braces that can't be read (for example `@salt{1 g/l}` or a missing `}`) is now reported as an error pointing at the brace, instead of being ignored and merging the ingredient with others that share the same first word - ---- - -## [1.2.1](https://git.gram-lang.org/gram-lang/gram/compare/v.1.2.0...v.1.2.1) - 2026-08-25 - -### Bug fixes and improvements -- **Renderer**: Switched icons to embedded inline SVGs, removing external CDN dependencies (`unpkg.com`) and enabling full offline previews in VS Code. -- **CLI / Export**: Fixed missing ingredient quantities in `gram print` and HTML exports (`gram export --format html`). -- **Documentation & Playground**: Improved accessibility and keyboard navigation across the website and interactive playground (ARIA roles, tab navigation, `prefers-reduced-motion`). - ---- - -## [1.2.0](https://git.gram-lang.org/gram-lang/gram/compare/v.1.1.0...v.1.2.0) - 2026-08-22 - -### New features -- **Parser & Kitchen**: Introduced modular recipes and multi-file imports via the `@use` directive: - - Import external base recipes directly into a recipe using `@use "./bases/shortcrust-pastry.gram" as &shortcrust`. - - Imported steps seamlessly interleave into the global ALAP scheduling timeline, preserving resting times and dependencies. - - Automatically scales imported base quantities when referenced with specific yields (e.g. `&shortcrust{250g}` halves a 500 g base recipe). - - Supports destructured multi-yield imports (e.g. `@use "./bases/tart-elements.gram" as { &crust, &frangipane }`) scaling each component independently. - - Supports multi-word bindings using bracket notation (e.g. `@use "..." as &pastry dough{}`). - - Resolves project-root paths (`@/bases/...`) and custom path aliases defined under `paths:` in `.gram/config.yaml`. - - Added `--stock` CLI flag to treat pre-made base imports as stock items (zero timeline overhead, single shopping list line, retaining full nutritional totals). - - Supports retro-planning timeline offsets directly on `@use` import lines (e.g. `@use "./bases/levain-starter.gram" as &starter ~{-2d}`). - - Spliced sections in HTML, Markdown, and print outputs display origin badges crediting their source module. - - `gram diff` and `gram watch` now track import additions, removals, rebinding, rescaling, and dependency file changes. - - Language Server and VS Code extension support live dependency composition, Go to Definition into base files, path auto-completion, and quick-fix diagnostics for missing exports. - - Exported `createMemoryHost` from `@gram-lang/modules` for browser and in-memory module graph resolution. - - Corrected whole-recipe mass and nutrition totals to accurately include spliced intermediate (`-> &`) masses. - - Normalized rescaled ingredient quantities to one decimal place for display consistency across all outputs. -- **CLI**: Added automatic update checking and a new `gram upgrade` command: - - gram now checks npm in the background and prints a short "update available" notice after a command finishes (skipped in CI and non-interactive runs). - - Added `gram upgrade` to check for and install the latest version on demand — it always performs a fresh check and asks for confirmation before running the install. - - Added an `updateCheck: false` setting in `config.yaml` (or the `GRAM_NO_UPDATE_CHECK` environment variable for a single run) to opt out of the passive notice. -- **Parser & Kitchen**: Composite ingredients written with a short, generic child name (like `@juice<@lemon`) are now protected against a silent ingredient-database mix-up: - - The compiler now warns when the same short composite name (e.g. "juice") is drawn from two different parents within one recipe (lemon in one step, orange in another) — until now this went unnoticed and the two usages silently shared one entry in the ingredient database. - - `gram db sync` reports the same conflict across your whole recipe collection, so two unrelated recipes that happen to use the same generic composite name don't overwrite each other's nutrition and density data. - - The AI recipe importer (`gram import`) now writes composite ingredients with their full name (e.g. "lemon juice") instead of a short generic one, so newly imported recipes don't create this conflict in the first place. - -### Bug fixes and improvements -- **Parser & Kitchen**: Fixed `gram scale` (and any other caller that re-scales an already-compiled recipe) silently leaving alternative ingredient groups (`@butter|@margarine`) and composite parent-draw quantities (`@egg-yolks{2}<@eggs{3}`) unscaled. -- **Parser & Kitchen**: Improved clarity and tone for diagnostic messages and revised severity tiers: - - Reworded compiler and module diagnostic messages to provide actionable guidance and avoid alarmist phrasing for standard culinary approximations. - - Reclassified non-critical notices (`MISSING_MACROS`, `UNKNOWN_MASS`, `TRACK_CONTENTION`) to `info` severity so they do not clutter warning counters. - - Enhanced Playground and editor diagnostic styling with dedicated color schemes for errors (red), warnings (amber), and notices (blue). -- **Language Server**: Normalized error states and unified diagnostic handling across Playground and VSCode extensions: - - Unified Playground diagnostics into a centralized full-width debug console with filter pills and interactive jump-to-location navigation. - - Added mobile segmented tab navigation (`[Editor]` / `[Preview]`) and responsive single-row toolbar layout for mobile viewports. - - Resolved nutrition diagnostics disconnection in the analyzer by merging physical and nutritional warnings into primary compiler warnings — the editor only turns these into squiggles when they carry a real position, so an incomplete-nutrition notice no longer misplaces itself at the top of the file. - - Markdown and print HTML exports keep their explicit "incomplete data" note next to the affected nutrition figures; the interactive HTML preview conveys the same gap through its coverage badge instead. - - A scale-target that fails to resolve (e.g. an unconvertible unit) now correctly turns the Playground's status badge and error panel red instead of being undersold as a warning, without marking the file tab as if the recipe itself had a syntax error. - - The Playground diagnostics console no longer gets stuck filtered on a category that just emptied out (e.g. after fixing the warning it was showing). - - Resolved silent compilation failures in the Language Server by capturing pipeline exceptions and pushing actionable error notifications to webviews — including when the thrown error carries no message, which previously slipped past the check silently. - - A compile-time failure (parses fine, but `compile()`/`analyze()` throws) now also surfaces as an editor diagnostic, not only as a webview notification, so it's still visible with the preview panel closed. - - Added bidirectional webview messaging in the VSCode extension to jump directly to error offsets in the active editor. - - Localized the Playground diagnostics console's collapse/expand tooltip, previously hardcoded in French regardless of site locale. -- **Parser & Kitchen**: Fixed a false circular reference warning when multiple sections used percentage-of formulas on same-named ingredients by scoping cycle detection per section. - ---- - -## [1.1.0](https://git.gram-lang.org/gram-lang/gram/compare/v.1.0.1...v.1.1.0) - 2026-08-16 - -### New features -- **CLI / Import**: Support importing recipes directly from **YouTube videos and Shorts** via `gram import`: - - Uses Gemini multimodal video understanding to analyze cooking videos and generate structured `.gram` recipes. - - Automatically populates `title:`, `author:` (channel name), and `source:` metadata from YouTube. - - Automatically normalizes YouTube Shorts URLs to standard video formats. - - Added `--max-duration` (default 20 minutes) to prevent accidental token overconsumption on long videos. - - Displays upfront video duration and estimated token cost when `YOUTUBE_API_KEY` is configured. -- **CLI / AI**: Explicit AI model and provider selection for all AI commands (`gram import`, `gram db lint`, `gram db enrich`): - - Added `--model`, `--provider`, and `--pick-model` CLI flags to inspect or override the active model per run without altering persistent config. - - The CLI now displays the active AI provider, model, and configuration source before execution. - - Isolated provider API keys so credentials configured for a specific provider are never leaked or reused when switching providers. - - Fixed `gram import` hanging in non-interactive environments when `--output` was used without `--yes`. -- **CLI / Database**: Added physical coherence and sanity checks across `gram db validate` and `gram db enrich`: - - `gram db validate` checks calorie consistency against Atwater estimates (4 kcal/g protein/carbs, 9 kcal/g fat, 7 kcal/g alcohol). - - `gram db validate` checks sub-macro coherence (sugars exceeding total carbs, fat sub-types exceeding total fat). - - `gram db validate` enforces category-based density sanity ranges and unit weight bounds. - - `gram db enrich` constrains AI estimates within physical limits and prompts self-verification of Atwater consistency. - - `gram db enrich` passes known ingredient categories to the AI to reduce guesswork. -- **CLI / Database**: `gram db enrich` now walks you through an interactive review before writing AI estimates to `ingredients.yaml`: - - Preview, accept, edit, or skip AI-proposed density, unit weight, and nutrition values per ingredient. - - Unedited AI values are tagged with `# [LLM]` in `ingredients.yaml` to track provenance. - - Added `--report` (`-r`) to preview needed database enrichments without writing changes, matching `gram db lint --report` (replaces `--dry-run` / `-n`). - - Added `--yes` (`-y`) to accept all estimates automatically for non-interactive scripting. - - Automatically falls back to accepting values with a warning when executed in non-interactive (non-TTY) environments. -- **CLI / Import**: Added integrity guardrails and diagnostic reporting to `gram import`: - - Validates compiled AST tokens against AI output to detect lost ingredients or truncated steps, aborting instead of writing corrupted files (overridable with `--force`). - - Reports uncorrected AI generation errors with actionable diagnostics. - - Identifies imported ingredients missing quantities and lists their line numbers for easy manual completion. - - Reports unknown database ingredients and unweighed units when an ingredient database is present. - - Prevented hallucinated placeholder metadata in `author:` and `source:` fields. - - Redirected progress indicators to `stderr` so stdout redirection (`gram import ... > recipe.gram`) produces clean recipe files. -- **Nutrition & Rendering**: Support flexible nutrition serving bases (per portion and per 100 g) alongside whole-recipe totals: - - Declaring `portions:` in recipe frontmatter now calculates per-portion nutrition and keeps values constant when scaling recipes. - - Added a standardized `per-100g` nutrition basis calculated from raw assembled recipe mass. - - Added the `--nutrition ` option to `gram view`, `gram export`, and `gram print`. - - Added nutrition basis toggles in the web playground and VS Code live preview. - - Localized all nutrient names and table headers across supported languages (French and English). - -### Bug fixes and improvements -- **Parser & Kitchen**: Fixed an issue where multi-word composite ingredients marked with `&` (e.g. `@juice{1}<@&unwaxed lemon{}`) were duplicated in the shopping list instead of being combined into a single purchase item. -- **Analyzer & Language Server**: Improved nutrient calculation completeness and editor hover precision: - - Saturated, monounsaturated, polyunsaturated fats, and alcohol are now included in recipe nutrition totals instead of being omitted. - - `gram db enrich` can now propose monounsaturated and polyunsaturated fat values during ingredient enrichment. - - Fixed the editor hover tooltip incorrectly displaying sodium in grams instead of milligrams. -- **Analyzer**: Fixed recipe total mass and section weights to include ingredients defined as relative percentages of another ingredient (e.g. `@water{60% @&flour}`). - ---- - -## [1.0.1](https://git.gram-lang.org/gram-lang/gram/compare/v.1.0.0...v.1.0.1) - 2026-08-07 - -### Bug fixes and improvements -- Fixed the `--help` description of `gram check` to clarify that it also checks database completeness by default, unless `--skip-db` is used. -- Reduced the AI provider costs of running `gram import`: - - Prompt caching is now enabled, so retries reuse the cached prompt instead of paying full price. - - The command now sends a minimized recipe payload instead of the full raw webpage data. - - The self-correction loop no longer spends retries on informational warnings (like missing database ingredients). - - Formatting is now handled locally instead of spending an AI call to fix it. -- Improved the quality and correctness of recipes generated by `gram import`: - - Fixed an issue where English words would leak into non-English recipes. - - Fixed grammatical errors (dropped articles) around ingredient and cookware references in non-English output. - - Descriptive adjectives (like "boneless skinless") are now correctly extracted as preparation steps instead of creating unwieldy ingredient names. - - Corrected the generated syntax for multi-word cookware references. - - Fixed an issue where the target language was sometimes incorrectly inferred. - - Improved decoding of accented characters and punctuation from the source recipe. -- Improved the CLI guidance printed after running `gram import`: - - It now correctly points to `gram db sync` as the recommended next step. - - It accurately reports any remaining compiler warnings (e.g., missing ingredients) instead of silently discarding them. -- Fixed `gram init` to ensure the interactive AI provider setup accurately offers the currently recommended models (e.g., llama4). - ---- - -## [1.0.0](https://git.gram-lang.org/gram-lang/gram/compare/v.1.0.0-beta.5...v.1.0.0) - 2026-08-06 - -### Breaking changes -- Gram v1.0.0 Official Launch! 🎉 This milestone release marks the official 1.0.0 launch of Gram: - - **Brand-New Website & Documentation**: Rebuilt using Astro and Starlight with refined guides and an integrated blog. - - **Refreshed Visual Identity**: Brand-new logo. - - **Infrastructure & Stability**: Monorepo stability, test coverage, and migration to new Forgejo (`git.gram-lang.org`) mirrored to GitHub and Codeberg. - ---- - -## [1.0.0-beta.5] - 7/26/2026 - -### New features -- Introduce `@gram-lang/format`, a standalone canonical code formatting engine for `.gram` files with 13 deterministic rules, used by the CLI and Language Server. -- `convertUnit`, `standardizeMass`, and `analyze()` now accept an optional `lang` parameter/option, so unit names are resolved against the recipe's own language when there's an ambiguity between languages, instead of always falling back to a single global guess. `UNIT_CONVERSIONS` (the mass/volume conversion table) has moved to `@gram-lang/i18n` — if you imported it from `@gram-lang/analyzer`, import it from `@gram-lang/i18n` instead. -- The `language:` setting in `.gram/config.yaml` now also affects unit conversion and the shopping list's category order (e.g. a database with French category names like "Légumes" now sorts correctly when `language: "fr"` is set) — previously it only affected AI-generated content. -- Fixed two bugs in the recipe formatter: - - A `#cookware` reference at the very start of a line (e.g. `#pan(20cm)`) was incorrectly treated as a malformed section header and got a space inserted after the `#`, turning it into plain text and silently breaking the recipe. - - Blank-line spacing before a `## Section` header was being promoted to two blank lines instead of Gram's actual convention of exactly one blank line between every step and/or section. The formatter now consistently enforces a single blank line everywhere, including before section headers. As a result, the `sectionSpacing` counter (previously reported alongside `consecutiveBlankLines`) has been removed — this kind of spacing fix is now reported as part of `consecutiveBlankLines`. -- `@gram-lang/i18n` now also owns the numeric conversion factors for units (grams, milliliters, etc.) and time (minutes, hours, etc.), exported as `UNIT_CONVERSIONS` and `TIME_TO_MINUTES` — previously split across `@gram-lang/analyzer` and hardcoded inside `@gram-lang/kitchen`. No behavior changes; this just puts everything about units and time in one place. -- Food categories now have stable, language-independent keys (`CATEGORY_KEYS`, `CategoryKey`, `getCategoryLabels`, `isCategoryKey`) instead of only translated display labels. This means `gram db enrich` now stores a category identity that stays consistent regardless of your configured language, rather than a French or English label baked in at write time. -- The Markdown, HTML, and printable/PDF outputs now show the same information consistently: - - Markdown recipes now include a nutrition summary (calories, carbs, protein, fat, etc.), which was previously only shown in HTML and print. - - Recipe comments now appear as numbered footnotes in Markdown and print output too, instead of only in HTML. - - When a shopping-list ingredient's purchasing weight differs from what actually goes in the bowl (e.g. "1 avocado" vs. its usable flesh), Markdown and print now show the extra "gross weight" note, matching HTML. - - When the same ingredient appears in incompatible units that can't be combined (e.g. "100g" and "1 cup" with no density available), Markdown and print now group them together with a "mixed units" warning, matching HTML. -- `gram format` and the editor's "format on save" now share the exact same formatting rules, so a recipe formatted by one always looks identical when opened in the other. This adds a few new automatic cleanups to both: normalizing spacing around composite ingredients (`@a{} < @b{}` → `@a{}<@b{}`), tidying up intermediate-result declarations (`->&name {}` → `->&name{}`), making sure section headers have exactly one space after the `#`s, and converting tabs to spaces. -- Add an interactive Gantt Chart view to the VS Code extension and export reusable Gantt chart rendering helpers (`toGanttHTML`, `attachGanttInteractivity`) from `@gram-lang/renderer`. Provides a real-time timeline visualization of recipe steps, background timers, and target serving times directly in your editor and the web playground. - -### Bug fixes and improvements -- Fixed a bug where the wrong API key could be sent to the wrong AI provider. If you had, say, `GEMINI_API_KEY` set in your environment but configured `provider: openai` in `.gram/config.yaml`, your Gemini key could be sent to OpenAI instead. Each provider now only ever uses its own key. -- Baker's Percentage is now shown on an ingredient's inline mention within step text, not just in the recipe's ingredient list and shopping list — a dead type check meant this data was computed but never actually reached the inline token. -- The ingredient database schema no longer requires `density` on every entry that has a `physical` block — an ingredient described only by `unit_weight` (e.g. "1 avocado") is valid, matching the analyzer's own documented example. Previously, `gram db enrich` could write entries that `gram build`/`gram db validate` would then reject. -- `gram diff` (and `diffRecipes`) now detects quantity changes inside composite ingredients (`<@parent`) and alternative groups (`@a|@b`), which it previously ignored entirely — a recipe that doubled a composite or alternative's quantities used to be reported as having no changes at all. It also no longer loses one of two same-titled sections, or two same-named timers/temperatures within a single section, when comparing two recipes. -- Fixed the same ingredient sometimes getting two different `normalizedMass` values in one analyzed recipe (e.g. `250.78328000000002` in a recipe section vs. `250.78` in the shopping list) — the section-level and composite-child mass calculations now go through the same rounding as the shopping list, instead of duplicating the sequence without it. -- Removed all uses of `any` from the physical/nutrition analysis layer's internal types, typing them against the real shapes already exported by `@gram-lang/kitchen` and this package's own `AnalyzedUsage`/`NutritionItem`. No behavior change for this package beyond the fixes already released separately (see the relative-quantity type changeset). The renderer's printable/PDF view gained one internal `any` to stay compatible with the analyzer's now-stricter shopping-list type — purely a type-level adjustment, no output change. -- A relative-quantity ingredient's resolved quantity (e.g. `@water{50% @&flour}`) is now tagged with the correct `"single"` type instead of a value that didn't match any of the documented quantity shapes — it happened to still render correctly today only because of an unrelated fallback, so this is a safety fix rather than a visible change. -- Fixed a major parsing bug where a bare `@ingredient` or `#cookware` mention (one written without its own `{}`) would silently swallow an unrelated timer, temperature, cookware, or ingredient that appeared later on the same line into its own name, if that later element happened to close with a valid quantity — losing that element from the recipe entirely. For example, `Brown the @&chicken for ~{3min}.` used to lose the timer completely, turning it into a single ingredient named "chicken for ~". Both the ingredient and cookware name now stop at the same sigils (`@`, `#`, `~`, `^`, `&`) that a bare reference (`&name`) already correctly stopped at. -- Warnings about invalid ingredient database entries now go to stderr instead of stdout, so commands like `gram build recipe.gram | jq` no longer break when the database has a bad entry. -- `gram shop` now groups the shopping list by the same category names used everywhere else in the project (e.g. "Seafood" instead of "Fish", "Vegetables" instead of "Produce") instead of its own inconsistent list. -- Fixed `gram format` rewriting values inside the recipe's frontmatter (the `---` metadata block at the top of a `.gram` file). For example, an email address like `Jean@Example.com` in `author:` used to get incorrectly lowercased to `Jean@example.com`. Frontmatter is no longer touched by formatting rules meant for the recipe body. File writes are also now atomic and lock-protected, matching the rest of the CLI. -- Fixed several French unit words silently resolving to the wrong physical quantity: - - `quart`/`quarts` no longer resolves to the US liquid quart (946 mL) in French recipes — it's a false friend ("un quart d'heure" means "a quarter of an hour", not a unit of volume). It's now reported as an unknown unit instead of silently misinterpreted. The English word `quart`/`quarts` still works in English recipes; only the spelled-out alias was removed, `qt` still works everywhere. - - `livre` now converts using the French "livre métrique" (500 g) instead of being silently treated as the imperial pound (453.592 g) — a ~10% error. - - `tasse` now converts using the French cup (250 mL) instead of being silently treated as the US cup (236.588 mL) — a ~6% error. - - `pinte` no longer resolves at all: the historical French pinte has no single reliable modern value, so an explicit "unknown unit" is better than a confident-looking wrong number. - - `gallon`/`gallons` now resolve correctly (previously only the abbreviation `gal` worked). -- The compiler now detects indirect circular dependencies between section intermediates (e.g. section A's result depends on section B's, whose result depends back on section A's) and reports a `CIRCULAR_REFERENCE` warning for each one — previously only a direct self-reference was caught. -- Removed all uses of `any` from the compiler's internal types, replacing them with the real shapes already exported by the package (`Usage`, `CompositeItem`, `StepToken`, etc.), and cleaned up dead code paths in shopping-list aggregation. -- Scaling a recipe by an extreme factor now fails with a clear error instead of silently producing `Infinity` (serialized as `null` in the output JSON). Scaled quantities are also rounded consistently, including a composite ingredient's total, so results no longer show float noise like `110.00000000000001`. -- Scaling a fraction quantity (e.g. `1/2 cup`) no longer produces a malformed value in the compiled JSON (`{"type": "fraction", "value": 1}` with no numerator/denominator) — it's now correctly represented as a plain numeric quantity. -- Fixed several compiler correctness bugs: - - An empty section (or one containing only a comment) between two sections with steps used to break ALAP scheduling: the step right after the gap could get scheduled to overlap a timer still running from before the gap. It now correctly chains past the gap. - - `applyScale()` (used by `gram scale` and the playground) now scales cookware quantities. Previously it only scaled cookware "by accident" when called from inside `compile({ scaleFactor })`, so `applyScale(compile(recipe), factor)` silently left cookware unscaled. - - A timer with an unrecognized time unit (e.g. `~{3 bananas}`) or a missing unit no longer silently contributes a fabricated duration to the recipe's total/active time. Both now raise a warning instead, matching how temperatures and retro-planning already behave. - - Timer units are now displayed consistently (e.g. always "min", never a mix of "min"/"mins"/"minutes" for the same physical duration in the same recipe). -- Fixed a spurious `TRACK_CONTENTION` warning on the ordinary, intended use of named passive tracks (`~_name{...}`) — chaining several steps on the same physical resource (an oven, a fridge shelf) back-to-back no longer warns just because nothing else linked those steps together. The scheduler now understands that shared-track ordering the same way it already understands `&intermediate` dependencies, so the warning only fires when a real, unforeseen conflict remains. -- Fixed several ways the language server could crash the whole editor session instead of just failing gracefully: a malformed entry in `ingredients.yaml` (e.g. missing `name`) no longer crashes the server, opening a project in a virtual or remote workspace no longer crashes initialization, and a failed background database reload can no longer take down the process. Formatting, rename, and code actions also now always operate on the current document content instead of a possibly-stale cached version. -- `ASTNode` is now a fully exhaustive, discriminated union that matches what the parser actually produces (`CompositeAST`, `QuantityAST`, `TextQuantityAST`, and `RelativeQuantityAST` were previously missing from it), and composite ingredients (`<@parent`) now carry source location info like every other node. Making these types honest surfaced and fixed three real bugs in the language server: outline (document symbols), syntax highlighting (semantic tokens), and go-to-definition/rename/hover (reference and intermediate lookups) could silently miss or crash on content that isn't wrapped in a `## Section` header — a recipe with no headers at all, or with a comment before the first header. -- Fixed two silent quantity-corruption bugs in fraction parsing: a decimal numerator (e.g. `1.5/2`) used to be truncated to an integer before dividing, silently turning `1.5/2` into `0.5` instead of `0.75`; a zero denominator (e.g. `1/0`) used to produce `Infinity`, which serializes to `null` in JSON, instead of being rejected outright. -- The `hideStepQty` rendering option (hides ingredient quantities from step text) now works with `toHTML` and `toMarkdown`, not just `toPrintHTML` — it was previously silently ignored by the other two. -- Fixed an HTML injection vulnerability (XSS) in `toHTML`'s timing-card tooltips: a section title or named timer containing HTML would render unescaped in the "Active Time" / "Total Time" tooltips, exploitable via the playground or the VS Code preview. Both are now properly escaped like every other text field. -- `toHTML`, `toMarkdown`, and `toPrintHTML` now type their `data` parameter instead of accepting `any`. Typing it surfaced two real bugs, now fixed: the HTML nutrition panel's "incomplete data" warning was never actually shown (it read a field that never existed, always showing a blank 0-calorie panel instead), and the printable/PDF view displayed sodium in grams instead of milligrams (1000x too high). -- Fixed syntax highlighting (TextMate grammar): a bare `@ingredient`, `#cookware`, or `<@parent` mention with no `{}` of its own would have its highlighted span incorrectly extend all the way to the next unrelated `{...}` on the line (e.g. a later `&reference{}`), coloring everything in between as if it were part of the same name. The name-matching patterns now stop at `@`, `#`, `~`, `^`, and `&`, the same sigils the compiler itself stops at. -- `toMarkdown` now neutralizes raw HTML (`<` and `&`) in recipe titles, ingredient names, and step text. Previously, a recipe containing something like `` in its title would pass through untouched, which could run as a script if that Markdown was later converted to HTML — this is now escaped automatically, closing that gap for imported or shared recipes. -- `gram import ` now refuses to fetch addresses that aren't publicly routable (localhost, private networks, link-local/cloud metadata addresses), including on redirects — closing a way for a malicious or compromised page to make the CLI fetch internal network resources. API keys stored via `gram init`/`gram config set` are now actually picked up when running the CLI under Node (previously only worked when run via Bun). `gram db enrich` now clearly reports when nothing was written to disk instead of claiming success; AI-suggested ingredient values that are physically implausible (like an ingredient density far outside any real food) are now rejected instead of being written to your ingredient database. -- `QuantityValueAST` (the parser's internal representation of a parsed number/fraction/range) is now a proper discriminated union instead of a flat interface with every field optional. This is an internal type-safety improvement with no behavior change — it's what would have caught, at compile time, a real bug fixed earlier in `diffRecipes` (checking `qty.from`/`qty.to`, fields that never existed on any variant). - ---- - -## [1.0.0-beta.4] - 7/23/2026 - -### Breaking changes -- Section retro-planning (e.g. `## Section ~{-2h}`) now enforces a strict signed-duration syntax instead of accepting arbitrary free text, preventing invalid timeline calculations. Added support for the `d` (day) time unit. - -### New features -- Added support for ALAP (As Late As Possible) scheduling. Passive timers and their dependencies are now natively pushed backwards from the end of the recipe, ensuring ingredients are prepared just-in-time rather than sitting idle on the counter. Also introduces two new compiler warnings for timeline conflicts: `TIME_PARADOX` and `TRACK_CONTENTION`. -- Exported the `runPipeline` function alongside its associated types from `@gram-lang/cli` to facilitate library and programmatic usage of the core compiler orchestration. -- Renamed the `cookTime` metric to `idleTime` across the ecosystem to better reflect hands-off wait time. Additionally, passive timers sharing the same name are now automatically sequenced one after another on the same background track. -- Added `llms.txt` and `llms-full.txt` to the documentation site, providing a curated index and full concatenated specification tailored for AI assistants and agents. - -### Bug fixes and improvements -- Fixed the display of alternative ingredient and cookware groups (`@egg|@tofu`). They now correctly render inline as a single joined line in shopping and section lists, rather than being dropped or rendered as oddly-wrapped sub-lists. -- Fixed mass standardization silently failing for alternative ingredient groups. Mass and estimate metrics are now properly computed for each option independently, fixing missing totals in the shopping list. -- Added support for bare single-word children in composite ingredients (e.g., `@juice<@lemon`), and allowed independent preparation instructions on the parent side. Fixed section ingredient lists silently dropping the parent reference. -- Fixed bare ingredient names incorrectly absorbing trailing punctuation (like periods). Also fixed multi-word unbraced names breaking alternative group parsing. (An orphan `|` in step text is now correctly flagged as a parse error). -- Fixed a bug where scaled fractions (e.g., when doubling a recipe) would incorrectly display their original, unscaled text values in section ingredient lists instead of the correctly multiplied amount. -- Fixed an issue where scaled fractions resulting in values below 1 (e.g., `0.5`) were rendered as raw decimals instead of common fractions (e.g., `1/2`) in the section ingredient list. -- Updated the AI generation prompt to accurately reflect the latest language syntax, strict retro-planning rules, and active/passive timer terminology. -- Fixed shopping list ingredient names defaulting to the database's canonical wording when the recipe used a valid alias. The lists now correctly preserve the recipe's original wording or translated alias, ensuring consistent language throughout. -- Fixed a parser crash that occurred when a section header named the section (`->&name`) before defining its retro-planning (`~{-2h}`). -- Fixed section and mise-en-place ingredient lists displaying raw database slug IDs (e.g., `oeufs`) instead of their correct, localized display names (e.g., `œufs`). -- Added detailed per-contribution time breakdowns (Active, Prep, Total) to compiled recipe metrics, and surfaced them as explanatory tooltips on the time summary badges in the HTML renderer. - ---- - -## [1.0.0-beta.3] - 7/14/2026 - -### Bug fixes and improvements -- `gram check` now resolves syntax error line numbers from the parser's structured `GramParseError.offset` instead of regexing "line N" out of ohm's prose message — line numbers are now always correct, not just when they happened to match that pattern. -- Downgrade minimum VS Code version requirement to 1.75.0 -- Updated deployment configuration to automate npmjs packages publication -- Updated docs for clarity and accuracy. - ---- - -## [1.0.0-beta.2] - 7/13/2026 - -### Breaking changes -- fix!: load valid ingredients even when the database has a bad entry, and fix five correctness bugs -- fix!: `gram check` only fails on structural errors by default (use `--strict` for the old behavior), fix LSP completion race, and add ingredients.yaml live reload -- feat!: validate and normalize temperature units, add a shared warning severity map, and fix accented/non-Latin ingredient slugs -- feat!: replace the `°` temperature sigil with `^`, the `~&` passive timer marker with `~_`, and add mixed/Unicode fraction support - -### New features -- Added a bilingual (EN/FR) "API Reference" section covering the programmatic API of `@gram-lang/parser`, `@gram-lang/kitchen`, `@gram-lang/analyzer`, `@gram-lang/renderer`, and `@gram-lang/i18n` — function signatures, options, JSON data formats, and the full warning-code catalogue. Reference tables (warning codes, AST node types, unit conversions, categories) are generated at build time directly from each package's source, so they can't drift out of sync with the code. Also fixed an incorrect `analyze()` call example in `how-to/build-custom-ui.md`. -- Export `fetchRecipe` and `validateGram` from the recipe-import service, enabling direct testing and reuse of the import validation pipeline. -- Add `round2(value: number): number`, exported from `@gram-lang/kitchen`. It centralizes the 2-decimal rounding rule (`parseFloat(x.toFixed(2))`) previously duplicated across kitchen, analyzer, and renderer, giving quantity/mass rounding a single documented implementation. No observable output changes — same rounding rule as before, just in one place. -- `getAST` now throws `GramParseError` instead of a plain `Error` on syntax errors. This new error type includes structured fields (`offset` and `expected`) while preserving the original human-readable message. The language server now uses the `offset` field to report parse-error diagnostics at their exact location in the document, rather than defaulting to line 1 column 1. -- The playground now shows a red squiggly marker at the exact location of a syntax error using the new `offset` field. Fixed a crash in the playground on mount in real browsers caused by an aggressive automated lint fix that removed necessary Vue `