diff --git a/conformance/cases/045-quantity-compound-mixed-family/analyzed.json b/conformance/cases/045-quantity-compound-mixed-family/analyzed.json index 67f867cf..45c0822c 100644 --- a/conformance/cases/045-quantity-compound-mixed-family/analyzed.json +++ b/conformance/cases/045-quantity-compound-mixed-family/analyzed.json @@ -203,7 +203,7 @@ { "id": "butter", "_usageId": "5", - "unit": "1 cup + 30 g - 2 tbsp", + "unit": "1 cup - 2 tbsp + 30 g", "parts": [ { "qty": 1, @@ -311,7 +311,7 @@ { "id": "butter", "_usageId": "5", - "unit": "1 cup + 30 g - 2 tbsp", + "unit": "1 cup - 2 tbsp + 30 g", "parts": [ { "qty": 1, diff --git a/conformance/cases/045-quantity-compound-mixed-family/compiled.json b/conformance/cases/045-quantity-compound-mixed-family/compiled.json index 893d7b44..054ef42a 100644 --- a/conformance/cases/045-quantity-compound-mixed-family/compiled.json +++ b/conformance/cases/045-quantity-compound-mixed-family/compiled.json @@ -194,7 +194,7 @@ { "id": "butter", "_usageId": "5", - "unit": "1 cup + 30 g - 2 tbsp", + "unit": "1 cup - 2 tbsp + 30 g", "parts": [ { "qty": 1, @@ -299,7 +299,7 @@ { "id": "butter", "_usageId": "5", - "unit": "1 cup + 30 g - 2 tbsp", + "unit": "1 cup - 2 tbsp + 30 g", "parts": [ { "qty": 1, 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 de130960..bc9fb7f4 100644 --- a/packages/docs/src/content/docs/docs/reference/api/i18n.mdx +++ b/packages/docs/src/content/docs/docs/reference/api/i18n.mdx @@ -178,7 +178,7 @@ function sameLadder(rawUnits: readonly (string | undefined | null)[], lang?: str - **`UNIT_LADDERS`**: the units that convert by a whole ratio, each counted in its ladder's smallest unit: US volume (`tsp` 1, `tbsp` 3, `fl oz` 6, `cup` 48, `pt` 96, `qt` 192, `gal` 768), imperial mass (`oz` 1, `lb` 16), metric mass (`mg`, `g`, `livre`, `kg`) and metric volume (`ml`, `cl`, `dl`, `tasse`, `l`). They agree with `UNIT_CONVERSIONS` to 0.01%. `pinch`, `dash` and unknown units are on no ladder. - **`termsTotal`**: one unit keeps its unit (`1 tasse + 1 tasse` stays in `tasse`, never converted); units of one ladder add up in the smallest unit written, with exact whole-number arithmetic; one family across systems gives grams or milliliters; anything else (a volume and a weight, unknown units) gives `null`. Ranges add up bound by bound, and a total with a range stays a range. -- **`mergeTerms`**: `"unit"` adds up the terms of each unit (a run sheet's kit), `"ladder"` the terms of each ladder (the shopping list). Terms added always come before terms taken away (`1 cup − 2 tbsp`, never `−2 tbsp + 1 cup`). +- **`mergeTerms`**: `"unit"` adds up the terms of each unit (a run sheet's kit), `"ladder"` the terms of each ladder (the shopping list). An amount never starts with a term taken away: `formatTerms` keeps the written order (`1 cup − 2 tbsp + 30 g`, each kind taking away on its own) and only moves the terms added first when it would (`1 cup − 2 tbsp`, never `−2 tbsp + 1 cup`). - **`formatTerms`**: `mode: "written"` (default) writes the terms as the author did; `mode: "computed"` writes an amount Gram worked out the way a cook measures it (see [scaling sums of quantities](/docs/explanation/scaling/#scaling-sums-of-quantities)). Options: `lang`, `buying` (a shopping list: move up to the unit you buy), `rounding` (round to what a cook can measure, after scaling), `plus` / `minus` separators, and `number` / `text` to write numbers your own way. ```typescript 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 b8d37548..03f0a8d1 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 @@ -179,7 +179,7 @@ function sameLadder(rawUnits: readonly (string | undefined | null)[], lang?: str - **`UNIT_LADDERS`** : les unités qui se convertissent par un rapport entier, comptées dans la plus petite unité de leur échelle : volume américain (`tsp` 1, `tbsp` 3, `fl oz` 6, `cup` 48, `pt` 96, `qt` 192, `gal` 768), masse impériale (`oz` 1, `lb` 16), masse métrique (`mg`, `g`, `livre`, `kg`) et volume métrique (`ml`, `cl`, `dl`, `tasse`, `l`). Elles concordent avec `UNIT_CONVERSIONS` à 0,01 % près. `pincée` et les unités inconnues n'appartiennent à aucune échelle. - **`termsTotal`** : une seule unité garde son unité (`1 tasse + 1 tasse` reste en `tasse`, jamais converti) ; les unités d'une même échelle s'additionnent dans la plus petite unité écrite, en arithmétique entière exacte ; une même nature sur deux systèmes donne des grammes ou des millilitres ; tout le reste (un volume et une masse, des unités inconnues) donne `null`. Les fourchettes s'additionnent borne par borne, et un total qui en contient une reste une fourchette. -- **`mergeTerms`** : `"unit"` additionne les termes de chaque unité (les ingrédients d'un passage du plan de marche), `"ladder"` ceux de chaque échelle (la liste de courses). Les termes ajoutés passent toujours avant les termes retirés (`1 cup − 2 tbsp`, jamais `−2 tbsp + 1 cup`). +- **`mergeTerms`** : `"unit"` additionne les termes de chaque unité (les ingrédients d'un passage du plan de marche), `"ladder"` ceux de chaque échelle (la liste de courses). Une quantité ne commence jamais par un terme retiré : `formatTerms` garde l'ordre écrit (`1 cup − 2 tbsp + 30 g`, chaque nature se soustrayant de son côté) et ne remet les termes ajoutés devant que lorsqu'elle commencerait ainsi (`1 cup − 2 tbsp`, jamais `−2 tbsp + 1 cup`). - **`formatTerms`** : `mode: "written"` (par défaut) écrit les termes comme l'auteur ; `mode: "computed"` écrit une quantité calculée par Gram comme on la mesure en cuisine (voir [mettre à l'échelle une somme de quantités](/fr/docs/explanation/scaling/#mettre-à-léchelle-une-somme-de-quantités)). Options : `lang`, `buying` (une liste de courses : passer à l'unité dans laquelle on achète), `rounding` (arrondir à ce qu'on peut mesurer, après mise à l'échelle), les séparateurs `plus` / `minus`, et `number` / `text` pour écrire les nombres à votre façon. ```typescript diff --git a/packages/i18n/src/quantity.ts b/packages/i18n/src/quantity.ts index 8ba7cd3c..146c7d4f 100644 --- a/packages/i18n/src/quantity.ts +++ b/packages/i18n/src/quantity.ts @@ -15,9 +15,29 @@ import { sameLadder, toLargerMetricUnit, UNIT_CONVERSIONS, + UNIT_DICTIONARIES, unitSpelling, } from "./units"; +/** + * True when a written unit is spelled the way the reader's language spells it + * and English does not (`càs`, `cuillère à soupe` in French): a unit Gram + * brings in then takes the reader's spelling (`càc`). Otherwise (`cup`, + * `tbsp`, `tablespoons`) it takes Gram's own (`tsp`), never a mix of both. + */ +function localSpelling(unit: string | null, lang?: string): boolean { + const base = lang?.toLowerCase().split("-")[0]; + if (!unit || !base || base === "en") return false; + const local = (UNIT_DICTIONARIES as Record>)[ + base + ]; + if (!local) return false; + const written = unit.toLowerCase().trim(); + const isIn = (dict: Record) => + Object.values(dict).some((aliases) => aliases.includes(written)); + return isIn(local) && !isIn(UNIT_DICTIONARIES.en); +} + /** * A numeric value as the compiled recipe stores it: a plain number, or the * parser's single / fraction / range shape (structurally the parser's @@ -645,7 +665,10 @@ function computedGroup( for (const t of group) if (size(t) > size(cap)) cap = t; const capUnit = canonical(cap); const spell = (unit: string): string => - group.find((t) => canonical(t) === unit)?.unit ?? unitSpelling(unit, lang); + group.find((t) => canonical(t) === unit)?.unit ?? + (group.some((t) => localSpelling(t.unit, lang)) + ? unitSpelling(unit, lang) + : unit); const write = (value: number, unit: string): string => `${w.number(value, unit)} ${unit}`; const span = (min: string, max: string, unit: string): string => @@ -700,21 +723,41 @@ function computedGroup( } if (!buying && measuredAsTheyAre(group, canonical, steps)) return asWritten(); - const a = decompose(total.min, from, steps); + let a = decompose(total.min, from, steps); let b = decompose(total.max, from, steps); - // A range keeps the shape of its low bound when the high one fits it - // (`2 cup + 2-4 tbsp`, not `2 cup + 2 tbsp – 2 1/4 cup`). - const lastLow = a[a.length - 1]; - if (lastLow && total.max !== total.min) { - const prefix = a.slice(0, -1); - const used = prefix.reduce( - (n, p) => n + p.value * (steps[p.unit] as number), - 0, - ); - const rest = (total.max - used) / (steps[lastLow.unit] as number); - const fits = measured(rest, lastLow.unit); - if (fits !== undefined) - b = [...prefix, { value: fits, unit: lastLow.unit }]; + // A range shares what both bounds have in common and puts the spread on + // one term (`2 cup + 2-4 tbsp`, not `2 cup + 2 tbsp – 2 1/4 cup`): the + // most precise term where both bounds are amounts its unit measures and + // the high one stays below the unit above (`1 cup + 3 1/2-5 tbsp`, never + // `1 cup + 3 tbsp + 1 3/4-6 1/4 tsp`). + if (total.max !== total.min) { + for (let cut = a.length - 1; cut >= 0; cut--) { + const prefix = a.slice(0, cut); + const unit = (a[cut] as { unit: string }).unit; + const size = steps[unit] as number; + const used = prefix.reduce( + (n, p) => n + p.value * (steps[p.unit] as number), + 0, + ); + // A scaled amount may be rounded to what the unit measures, as its + // last term is (`decompose`); an exact one must fall on it. + const fit = (value: number) => + options.rounding === false + ? measured(value, unit) + : value > 0 + ? nearestMeasured(value, unit) + : undefined; + const lo = fit((total.min - used) / size); + const hi = fit((total.max - used) / size); + const above = + cut > 0 + ? (steps[(prefix[cut - 1] as { unit: string }).unit] as number) + : Infinity; + if (lo === undefined || hi === undefined || hi * size >= above) continue; + a = [...prefix, { value: lo, unit }]; + b = [...prefix, { value: hi, unit }]; + break; + } } if ( options.rounding === false && @@ -769,8 +812,9 @@ function computedNumber(lang?: string) { } /** - * The terms as text, terms added first (`1 cup + 1 tbsp`, `1 cup − 2 tbsp`). - * A list that starts with a term taken away still writes it after the others. + * The terms as text, in their written order (`1 cup + 1 tbsp`, + * `1 cup − 2 tbsp + 30 g`); a list that would start with a term taken away + * writes the terms added first (`1 cup − 2 tbsp`, never `−2 tbsp + 1 cup`). * * `"written"` mode (the default) writes each term as the author wrote it. * `"computed"` mode writes an amount Gram worked out, ladder by ladder (two @@ -802,12 +846,16 @@ export function formatTerms( (computed ? computedNumber(options.lang) : RAW_WRITER.number), text: options.text ?? RAW_WRITER.text, }; + // The written order is kept (`1 cup − 2 tbsp + 30 g`: the 2 tbsp come off + // the cup); terms added are only moved first when the amount would start + // with a term taken away (`−2 tbsp + 1 cup`). + const source = terms[0]?.minus ? addedFirst(terms) : terms; const pieces: Piece[] = computed - ? groupTerms(addedFirst(terms), "ladder").flatMap((group) => + ? groupTerms(source, "ladder").flatMap((group) => computedGroup(group, w, options), ) - : terms.map((term) => ({ text: writeTerm(term, w), minus: term.minus })); - return addedFirst(pieces) + : source.map((term) => ({ text: writeTerm(term, w), minus: term.minus })); + return (pieces[0]?.minus ? addedFirst(pieces) : pieces) .map((piece, i) => { if (i === 0) return piece.minus ? `${minus.trimStart()}${piece.text}` : piece.text; diff --git a/packages/i18n/tests/quantity.test.ts b/packages/i18n/tests/quantity.test.ts index 812ec0ec..a5d63ead 100644 --- a/packages/i18n/tests/quantity.test.ts +++ b/packages/i18n/tests/quantity.test.ts @@ -456,6 +456,48 @@ describe("formatTerms, computed", () => { const t = (value: Term["value"], unit: string | null, minus?: true): Term => minus ? { value, unit, minus } : { value, unit }; + it("brings in a unit spelled like the written ones, never a mix of both", () => { + const scaled = (terms: Term[]) => + computed(scaleTerms(terms, 1.1), { lang: "fr", rounding: true }); + // Written in cups and tbsp: Gram's own spelling, even for a French reader. + expect(scaled([t(1, "cup"), t(1, "tbsp")])).toBe( + "1 cup + 2 tbsp + 2 1/8 tsp", + ); + // Written the French way: the French spelling. + expect(scaled([t(1, "cup"), t(1, "càs")])).toBe( + "1 cup + 2 càs + 2 1/8 càc", + ); + }); + + it("puts a range on the most precise term that measures both bounds", () => { + const range = { + type: "range" as const, + value: 1.5, + range: { min: 1, max: 2 }, + }; + // 58.5-63 tsp: `1 cup + 3 1/2-5 tbsp`, never `… + 1 3/4-6 1/4 tsp`. + expect( + computed(scaleTerms([t(0.75, "cup"), t(range, "tbsp")], 1.5), { + rounding: true, + }), + ).toBe("1 cup + 3 1/2-5 tbsp"); + expect(computed(scaleTerms([t(1, "cup"), t(range, "tbsp")], 2))).toBe( + "2 cup + 2-4 tbsp", + ); + }); + + it("keeps the written order, each kind taking away on its own", () => { + const sum = [t(1, "cup"), t(2, "tbsp", true), t(30, "g")]; + expect(formatTerms(sum)).toBe("1 cup − 2 tbsp + 30 g"); + expect(computed(scaleTerms(sum, 0.5), { rounding: true })).toBe( + "1/2 cup − 1 tbsp + 15 g", + ); + // Never starts with a term taken away. + expect(formatTerms([t(2, "tbsp", true), t(1, "cup")])).toBe( + "1 cup − 2 tbsp", + ); + }); + it("recomposes a scaled sum term by term, never into a fraction no spoon measures", () => { const doubled = scaleTerms([t(1, "cup"), t(1, "tbsp")], 2); expect(computed(doubled)).toBe("2 cup + 2 tbsp");