feat(i18n): recompose from the largest measured fraction, show diffs as bought, and make subtraction by kind clear #162

Merged
abiwab merged 1 commit from feat/compound-display-polish into dev/1.5 2026-11-15 18:21:29 +01:00
18 changed files with 83 additions and 22 deletions

View file

@ -12,4 +12,4 @@
- A sum counts exactly as its terms written one after the other: one kind of amount adds up into one total, exactly (`1 cup + 1 tbsp` is 17 tbsp, a range by its bounds), and is usable with `gram scale --target`; a volume and a weight (`1 cup + 20 g`) stay two lines of the shopping list. Scaling multiplies each term. A step shows a sum as written; a scaled amount, the ingredients a section adds up and the shopping list are written the way a cook measures (`2 cup + 2 tbsp`, never `2 1/8 cup` or `34 tbsp`; `2.4 kg` in a step, `1.5 kg` to buy), for any amount, not only sums, in the views as in `gram shop` and `gram scale`; the renderer's new `formatUsageQuantity` writes an amount this way for other tools. - A sum counts exactly as its terms written one after the other: one kind of amount adds up into one total, exactly (`1 cup + 1 tbsp` is 17 tbsp, a range by its bounds), and is usable with `gram scale --target`; a volume and a weight (`1 cup + 20 g`) stay two lines of the shopping list. Scaling multiplies each term. A step shows a sum as written; a scaled amount, the ingredients a section adds up and the shopping list are written the way a cook measures (`2 cup + 2 tbsp`, never `2 1/8 cup` or `34 tbsp`; `2.4 kg` in a step, `1.5 kg` to buy), for any amount, not only sums, in the views as in `gram shop` and `gram scale`; the renderer's new `formatUsageQuantity` writes an amount this way for other tools.
- Gram never guesses: a term without a unit, a percentage, a multiplication, a range taken away, a subtraction from another kind of amount or a sum that comes to nothing raises the new `INVALID_QUANTITY` warning, with the result to write when it can tell (`{100 g + 10%}` suggests `{110 g}`), and the sum is not counted. The new `OZ_AFTER_VOLUME` note says that `oz` is a weight in `{1 cup + 2 oz}`, and `INVALID_UNIT` now asks for two quantities written side by side (`{1 kg 200 g}`) to be written as a sum. - Gram never guesses: a term without a unit, a percentage, a multiplication, a range taken away, a subtraction from another kind of amount or a sum that comes to nothing raises the new `INVALID_QUANTITY` warning, with the result to write when it can tell (`{100 g + 10%}` suggests `{110 g}`), and the sum is not counted. The new `OZ_AFTER_VOLUME` note says that `oz` is a weight in `{1 cup + 2 oz}`, and `INVALID_UNIT` now asks for two quantities written side by side (`{1 kg 200 g}`) to be written as a sum.
- In the compiled JSON, a sum keeps its terms in a new `parts` field (`minus: true` on a term taken away), and its total in `qty` / `unit` as before; a sum of several kinds of amount keeps its text in `unit`, like a quantity written in words. A warning that a tool can act on carries a new `data` field (its reason and suggestion). - In the compiled JSON, a sum keeps its terms in a new `parts` field (`minus: true` on a term taken away), and its total in `qty` / `unit` as before; a sum of several kinds of amount keeps its text in `unit`, like a quantity written in words. A warning that a tool can act on carries a new `data` field (its reason and suggestion).
- Masses and nutrition weigh a sum by its parts: `@flour{1 cup + 20 g}` weighs its cup (with the flour's density) plus its 20 g, a term taken away weighs against the total, and a sum with a part Gram cannot weigh gets no mass rather than a partial one. `gram diff` shows amounts as written (`202-203 g`), from the new `fromText` / `toText` fields of an ingredient change. - Masses and nutrition weigh a sum by its parts: `@flour{1 cup + 20 g}` weighs its cup (with the flour's density) plus its 20 g, a term taken away weighs against the total, and a sum with a part Gram cannot weigh gets no mass rather than a partial one. `gram diff` shows amounts as the shopping list writes them (`1 cup + 1 tbsp → 1 cup + 3 tbsp`, `202-203 g`), from the new `fromText` / `toText` fields of an ingredient change.

View file

@ -574,7 +574,7 @@
}, },
{ {
"code": "INVALID_QUANTITY", "code": "INVALID_QUANTITY",
"message": "Quantity \"1 tbsp - 1 cup\" of \"butter\" is not read: what is taken away is as much as what is added, or more: the sum comes to nothing. It is not counted in the shopping list or the nutrition.", "message": "Quantity \"1 tbsp - 1 cup\" of \"butter\" is not read: what is taken away is as much as what is added, or more, so the sum comes to nothing. Each kind of amount is counted on its own: in {1 cup - 2 tbsp + 30 g}, the 2 tbsp come off the cup only. It is not counted in the shopping list or the nutrition.",
"item": "butter", "item": "butter",
"loc": { "loc": {
"start": 187, "start": 187,
@ -598,7 +598,7 @@
}, },
{ {
"code": "INVALID_QUANTITY", "code": "INVALID_QUANTITY",
"message": "Quantity \"1 cup - 20 g\" of \"oil\" is not read: an amount is only taken away from one of its kind (a volume from a volume, a weight from a weight): Gram cannot check the rest is left above zero. It is not counted in the shopping list or the nutrition.", "message": "Quantity \"1 cup - 20 g\" of \"oil\" is not read: an amount is only taken away from one of its kind: a volume from a volume, a weight from a weight. Here nothing of its kind is added to take it from. {1 cup - 2 tbsp + 30 g} works (the 2 tbsp come off the cup); {1 cup - 20 g} does not. It is not counted in the shopping list or the nutrition.",
"item": "oil", "item": "oil",
"loc": { "loc": {
"start": 243, "start": 243,

View file

@ -547,7 +547,7 @@
}, },
{ {
"code": "INVALID_QUANTITY", "code": "INVALID_QUANTITY",
"message": "Quantity \"1 tbsp - 1 cup\" of \"butter\" is not read: what is taken away is as much as what is added, or more: the sum comes to nothing. It is not counted in the shopping list or the nutrition.", "message": "Quantity \"1 tbsp - 1 cup\" of \"butter\" is not read: what is taken away is as much as what is added, or more, so the sum comes to nothing. Each kind of amount is counted on its own: in {1 cup - 2 tbsp + 30 g}, the 2 tbsp come off the cup only. It is not counted in the shopping list or the nutrition.",
"item": "butter", "item": "butter",
"loc": { "loc": {
"start": 187, "start": 187,
@ -571,7 +571,7 @@
}, },
{ {
"code": "INVALID_QUANTITY", "code": "INVALID_QUANTITY",
"message": "Quantity \"1 cup - 20 g\" of \"oil\" is not read: an amount is only taken away from one of its kind (a volume from a volume, a weight from a weight): Gram cannot check the rest is left above zero. It is not counted in the shopping list or the nutrition.", "message": "Quantity \"1 cup - 20 g\" of \"oil\" is not read: an amount is only taken away from one of its kind: a volume from a volume, a weight from a weight. Here nothing of its kind is added to take it from. {1 cup - 2 tbsp + 30 g} works (the 2 tbsp come off the cup); {1 cup - 20 g} does not. It is not counted in the shopping list or the nutrition.",
"item": "oil", "item": "oil",
"loc": { "loc": {
"start": 243, "start": 243,

View file

@ -211,12 +211,15 @@ const numericQty = (item: ShoppingItem): number | null =>
numericTotal(termsOfUsage(item)); numericTotal(termsOfUsage(item));
/** /**
* The amount of an entry as text, its unit included (`2-3 g`), or * The amount of an entry as text, its unit included, written the way the
* `undefined` when it has no terms (a text quantity, no quantity). * shopping list writes it (`1 cup + 1 tbsp` for 17 tbsp, `2-3 g`, `1.5 kg`),
* or `undefined` when it has no terms (a text quantity, no quantity).
*/ */
const amountText = (item: ShoppingItem): string | undefined => { const amountText = (item: ShoppingItem): string | undefined => {
const terms = termsOfUsage(item); const terms = termsOfUsage(item);
return terms.length > 0 ? formatTerms(terms, { minus: " - " }) : undefined; return terms.length > 0
? formatTerms(terms, { minus: " - ", mode: "computed", buying: true })
: undefined;
}; };
/** `fromText` / `toText` of a delta, each only when there is one. */ /** `fromText` / `toText` of a delta, each only when there is one. */

View file

@ -163,4 +163,22 @@ describe("diffRecipes() on amounts", () => {
toText: "202-203 g", toText: "202-203 g",
}); });
}); });
it("writes cups and spoons as the shopping list does, not as a total in spoons", () => {
const diff = diffRecipes(
compiled("Add @flour{1 cup + 1 tbsp} and @milk{1 cup + 1-2 tbsp}."),
compiled("Add @flour{1 cup + 3 tbsp} and @milk{1 cup + 2-3 tbsp}."),
);
const byId = (id: string) => diff.ingredients.find((d) => d.id === id);
expect(byId("flour")).toMatchObject({
fromQty: 17,
toQty: 19,
fromText: "1 cup + 1 tbsp",
toText: "1 cup + 3 tbsp",
});
expect(byId("milk")).toMatchObject({
fromText: "1 cup + 1-2 tbsp",
toText: "1 cup + 2-3 tbsp",
});
});
}); });

View file

@ -172,7 +172,7 @@ describe("buildScaleComparison", () => {
expect(flour?.originalText).toBe("2 cup + 2 tbsp"); expect(flour?.originalText).toBe("2 cup + 2 tbsp");
expect(flour?.scaledText).toBe("3 cup + 3 tbsp"); expect(flour?.scaledText).toBe("3 cup + 3 tbsp");
expect(sugar?.originalText).toBe("13-14 tbsp"); expect(sugar?.originalText).toBe("13-14 tbsp");
expect(sugar?.scaledText).toBe("1 cup + 10-12 tbsp"); expect(sugar?.scaledText).toBe("1 1/2 cup + 2-4 tbsp");
}); });
it("marks items without a numeric quantity as nonScalable", () => { it("marks items without a numeric quantity as nonScalable", () => {

View file

@ -551,6 +551,8 @@ A few rules keep a sum readable:
- **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). - **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. - **No range after `-`**: `{1 cup - 1-2 tbsp}` would swap its bounds; write the range on a term that is added.
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.
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 ` + `. 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] :::caution[oz is a weight]
@ -2350,7 +2352,7 @@ A [sum of quantities](/docs/reference/syntax/ingredients/#sums-of-quantities) Gr
| `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. | | `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). | | `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). |
Subtraction is checked kind by kind, so `{1 cup - 2 tbsp + 30 g}` is fine. 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.
### `OZ_AFTER_VOLUME` ### `OZ_AFTER_VOLUME`
*(since v1.5.0)* *(since v1.5.0)*

View file

@ -80,7 +80,7 @@ A [sum of quantities](/docs/reference/syntax/ingredients/#sums-of-quantities) Gr
| `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. | | `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). | | `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). |
Subtraction is checked kind by kind, so `{1 cup - 2 tbsp + 30 g}` is fine. 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.
### `OZ_AFTER_VOLUME` ### `OZ_AFTER_VOLUME`
<Since v="1.5.0" /> <Since v="1.5.0" />

View file

@ -227,6 +227,8 @@ A few rules keep a sum readable:
- **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). - **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. - **No range after `-`**: `{1 cup - 1-2 tbsp}` would swap its bounds; write the range on a term that is added.
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.
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 ` + `. 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] :::caution[oz is a weight]

View file

@ -48,7 +48,7 @@ The Gram Language Server implements the following standard capabilities:
<Since v="1.5.0" /> On a [sum of quantities](/docs/reference/syntax/ingredients/#sums-of-quantities), the editor helps in three ways: <Since v="1.5.0" /> 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 volume next to a weight reads `volume + mass, counted apart`) and, when the ingredient database can weigh every term, its mass. A sum Gram refuses shows nothing more than its warning. - **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`). - **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. - **Completion** offers units for each term: after `{1 cup + 2`, the units come back.

View file

@ -81,7 +81,7 @@ Une [somme de quantités](/fr/docs/reference/syntax/ingredients/#sommes-de-quant
| `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. | | `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). | | `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). |
La soustraction se vérifie nature par nature : `{1 tasse - 2 càs + 30 g}` passe. 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.
### `OZ_AFTER_VOLUME` ### `OZ_AFTER_VOLUME`
<Since v="1.5.0" /> <Since v="1.5.0" />

View file

@ -227,6 +227,8 @@ Quelques règles gardent une somme lisible :
- **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é). - **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é. - **Pas de fourchette après un `-`** : `{1 tasse - 1-2 càs}` inverserait ses bornes ; mettez la fourchette sur un terme ajouté.
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 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 ` + `. 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] :::caution[oz est une masse]

View file

@ -48,7 +48,7 @@ Le Serveur de Langage Gram implémente les capacités standardisées suivantes :
<Since v="1.5.0" /> Sur une [somme de quantités](/fr/docs/reference/syntax/ingredients/#sommes-de-quantités), l'éditeur aide de trois façons : <Since v="1.5.0" /> 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` ; un volume à côté d'une masse donne `volume + mass, 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. - **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`). - **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. - **La complétion** propose les unités de chaque terme : après `{1 kg + 2`, les unités reviennent.

View file

@ -528,7 +528,16 @@ function decompose(
out.push({ value: exactly, unit }); out.push({ value: exactly, unit });
break; break;
} }
const whole = Math.floor(value + 1e-9); // The largest unit takes the largest amount it measures, fraction
// included (`1 1/2 cup + 1 1/2 tbsp`, not `1 cup + 9 1/2 tbsp`); the
// units below take whole ones.
const whole =
i === 0
? Math.max(
0,
...measuredCandidates(value, unit).filter((c) => c <= value + 1e-9),
)
: Math.floor(value + 1e-9);
if (whole > 0) { if (whole > 0) {
out.push({ value: whole, unit }); out.push({ value: whole, unit });
rest -= whole * size; rest -= whole * size;

View file

@ -488,6 +488,16 @@ describe("formatTerms, computed", () => {
expect(computed([t(0.7, "tsp")], { rounding: true })).toBe("3/4 tsp"); expect(computed([t(0.7, "tsp")], { rounding: true })).toBe("3/4 tsp");
}); });
it("starts from the largest fraction the largest unit measures, not whole units", () => {
expect(computed([t(25.5, "tbsp")], { buying: true })).toBe(
"1 1/2 cup + 1 1/2 tbsp",
);
expect(computed([t(21, "tbsp")], { buying: true })).toBe(
"1 1/4 cup + 1 tbsp",
);
expect(computed([t(22, "oz")], { buying: true })).toBe("1 1/4 lb + 2 oz");
});
it("never climbs above the largest unit written in a step", () => { it("never climbs above the largest unit written in a step", () => {
expect(computed([t(34, "tbsp")])).toBe("34 tbsp"); expect(computed([t(34, "tbsp")])).toBe("34 tbsp");
}); });

View file

@ -224,11 +224,11 @@ const QUANTITY_HINTS: Record<InvalidQuantityReason, string> = {
quantityInUnit: quantityInUnit:
"this term's unit holds a quantity of its own: write the amount in one unit (e.g. {450 g} rather than {1 tin of 400 g + 50 g}).", "this term's unit holds a quantity of its own: write the amount in one unit (e.g. {450 g} rather than {1 tin of 400 g + 50 g}).",
nonPositiveTotal: nonPositiveTotal:
"what is taken away is as much as what is added, or more: the sum comes to nothing.", "what is taken away is as much as what is added, or more, so the sum comes to nothing. Each kind of amount is counted on its own: in {1 cup - 2 tbsp + 30 g}, the 2 tbsp come off the cup only.",
rangeAfterMinus: rangeAfterMinus:
"a range cannot be taken away (its bounds would swap): write the range on a term that is added, or the total as a range.", "a range cannot be taken away (its bounds would swap): write the range on a term that is added, or the total as a range.",
minusAcrossFamilies: minusAcrossFamilies:
"an amount is only taken away from one of its kind (a volume from a volume, a weight from a weight): Gram cannot check the rest is left above zero.", "an amount is only taken away from one of its kind: a volume from a volume, a weight from a weight. Here nothing of its kind is added to take it from. {1 cup - 2 tbsp + 30 g} works (the 2 tbsp come off the cup); {1 cup - 20 g} does not.",
}; };
export const warningTemplates: { export const warningTemplates: {

View file

@ -87,11 +87,17 @@ function buildSumSection(
`**Total**: ${written} = **${formatTerms([{ value: total.qty, unit: total.unit }])}**`, `**Total**: ${written} = **${formatTerms([{ value: total.qty, unit: total.unit }])}**`,
); );
} else { } else {
const families = termsByFamily(sum.terms).map((group) => // Each kind adds up, and takes away, on its own: show what each comes
familyName(group[0]?.unit ?? null), // to (`1 cup - 2 tbsp + 30 g` is 14 tbsp of volume and 30 g of weight).
); const kinds = termsByFamily(sum.terms).map((group) => {
const kindTotal = termsTotal(group);
const amount = kindTotal
? formatTerms([{ value: kindTotal.qty, unit: kindTotal.unit }])
: formatTerms(group);
return `**${amount}** _(${familyName(group[0]?.unit ?? null)})_`;
});
lines.push( lines.push(
`**Total**: ${written} _(${families.join(" + ")}, counted apart)_`, `**Total**: ${written} = ${kinds.join(" + ")}, counted apart: each kind adds up and takes away on its own`,
); );
} }

View file

@ -111,11 +111,20 @@ describe("hover on a sum", () => {
it("shows the mass of the sum, part by part", () => { it("shows the mass of the sum, part by part", () => {
const text = recipe("Add @flour{1 cup + 20 g}."); const text = recipe("Add @flour{1 cup + 20 g}.");
const hover = hoverAt(text, "@flour", db); const hover = hoverAt(text, "@flour", db);
expect(hover).toContain("volume + weight, counted apart"); expect(hover).toContain(
"**1 cup** _(volume)_ + **20 g** _(weight)_, counted apart",
);
// 1 cup ≈ 236.59 ml × 0.53 ≈ 125.4 g, plus 20 g. // 1 cup ≈ 236.59 ml × 0.53 ≈ 125.4 g, plus 20 g.
expect(hover).toMatch(/1 cup \+ 20 g ≈ \*\*145 g\*\*/); expect(hover).toMatch(/1 cup \+ 20 g ≈ \*\*145 g\*\*/);
}); });
it("shows what each kind comes to when a sum takes away within one kind", () => {
const text = recipe("Add @butter{1 cup - 2 tbsp + 30 g}.");
expect(hoverAt(text, "@butter", db)).toContain(
"= **14 tbsp** _(volume)_ + **30 g** _(weight)_, counted apart: each kind adds up and takes away on its own",
);
});
it("shows the total of an ingredient the database lacks", () => { it("shows the total of an ingredient the database lacks", () => {
const text = recipe("Add @sugar{1 cup - 2 tbsp}."); const text = recipe("Add @sugar{1 cup - 2 tbsp}.");
expect(hoverAt(text, "@sugar", db)).toContain("= **14 tbsp**"); expect(hoverAt(text, "@sugar", db)).toContain("= **14 tbsp**");