From 62aa908512984c0337c29206796f4d05585dc3c7 Mon Sep 17 00:00:00 2001 From: Michael Genson <71845777+michael-genson@users.noreply.github.com> Date: Thu, 24 Sep 2026 13:18:44 -0500 Subject: [PATCH] feat: convert between metric/imperial units (#8292) --- dev/code-generation/gen_ts_unit_systems.py | 107 +++++++ dev/code-generation/main.py | 4 +- dev/code-generation/unit_systems.py | 268 ++++++++++++++++++ dev/code-generation/utils/static.py | 1 + docker/Dockerfile | 5 + .../Domain/Recipe/RecipePage/RecipePage.vue | 44 ++- .../RecipePageParts/RecipePageScale.vue | 7 +- .../Domain/Recipe/RecipeUnitSystemButton.vue | 84 ++++++ .../__tests__/use-unit-conversion.test.ts | 260 +++++++++++++++++ .../recipes/__tests__/use-unit-system.test.ts | 46 +++ frontend/app/composables/recipes/index.ts | 2 + .../app/composables/recipes/unit-systems.ts | 63 ++++ .../recipes/use-unit-conversion.ts | 211 ++++++++++++++ .../composables/recipes/use-unit-system.ts | 36 +++ frontend/app/lang/locales/af-ZA.ts | 4 + frontend/app/lang/locales/ar-SA.ts | 4 + frontend/app/lang/locales/bg-BG.ts | 4 + frontend/app/lang/locales/ca-ES.ts | 4 + frontend/app/lang/locales/cs-CZ.ts | 4 + frontend/app/lang/locales/da-DK.ts | 4 + frontend/app/lang/locales/de-DE.ts | 4 + frontend/app/lang/locales/el-GR.ts | 4 + frontend/app/lang/locales/en-GB.ts | 4 + frontend/app/lang/locales/en-US.ts | 4 + frontend/app/lang/locales/es-ES.ts | 4 + frontend/app/lang/locales/et-EE.ts | 4 + frontend/app/lang/locales/fi-FI.ts | 4 + frontend/app/lang/locales/fr-BE.ts | 4 + frontend/app/lang/locales/fr-CA.ts | 4 + frontend/app/lang/locales/fr-FR.ts | 4 + frontend/app/lang/locales/gl-ES.ts | 4 + frontend/app/lang/locales/he-IL.ts | 4 + frontend/app/lang/locales/hr-HR.ts | 4 + frontend/app/lang/locales/hu-HU.ts | 4 + frontend/app/lang/locales/is-IS.ts | 4 + frontend/app/lang/locales/it-IT.ts | 4 + frontend/app/lang/locales/ja-JP.ts | 4 + frontend/app/lang/locales/ko-KR.ts | 4 + frontend/app/lang/locales/lt-LT.ts | 4 + frontend/app/lang/locales/lv-LV.ts | 4 + frontend/app/lang/locales/nl-NL.ts | 4 + frontend/app/lang/locales/no-NO.ts | 4 + frontend/app/lang/locales/pl-PL.ts | 4 + frontend/app/lang/locales/pt-BR.ts | 4 + frontend/app/lang/locales/pt-PT.ts | 4 + frontend/app/lang/locales/ro-RO.ts | 4 + frontend/app/lang/locales/ru-RU.ts | 4 + frontend/app/lang/locales/sk-SK.ts | 4 + frontend/app/lang/locales/sl-SI.ts | 4 + frontend/app/lang/locales/sr-SP.ts | 4 + frontend/app/lang/locales/sv-SE.ts | 4 + frontend/app/lang/locales/tr-TR.ts | 4 + frontend/app/lang/locales/uk-UA.ts | 4 + frontend/app/lang/locales/vi-VN.ts | 4 + frontend/app/lang/locales/zh-CN.ts | 4 + frontend/app/lang/locales/zh-TW.ts | 4 + frontend/app/lang/messages/en-US.json | 7 + frontend/app/tests/setup.ts | 9 +- frontend/app/tests/utils.ts | 9 +- frontend/nuxt.config.ts | 16 ++ 60 files changed, 1332 insertions(+), 15 deletions(-) create mode 100644 dev/code-generation/gen_ts_unit_systems.py create mode 100644 dev/code-generation/unit_systems.py create mode 100644 frontend/app/components/Domain/Recipe/RecipeUnitSystemButton.vue create mode 100644 frontend/app/composables/recipes/__tests__/use-unit-conversion.test.ts create mode 100644 frontend/app/composables/recipes/__tests__/use-unit-system.test.ts create mode 100644 frontend/app/composables/recipes/unit-systems.ts create mode 100644 frontend/app/composables/recipes/use-unit-conversion.ts create mode 100644 frontend/app/composables/recipes/use-unit-system.ts diff --git a/dev/code-generation/gen_ts_unit_systems.py b/dev/code-generation/gen_ts_unit_systems.py new file mode 100644 index 000000000..e5f424535 --- /dev/null +++ b/dev/code-generation/gen_ts_unit_systems.py @@ -0,0 +1,107 @@ +from jinja2 import Template +from unit_systems import UnitDimension, UnitSystem, build_table +from utils import CodeDest, log + +UNIT_SYSTEMS_TEMPLATE = """// This Code is auto generated by gen_ts_unit_systems.py +export type UnitDimension = {{ dimension_union }}; + +export type UnitSystem = {{ system_union }}; + +export interface StandardizedUnit { + dimension: UnitDimension; + /** How many base units (grams for mass, millilitres for volume) are in one of this unit. */ + base: number; + /** Customary rather than metric, so a recipe using it is already in a customary system. */ + customary: boolean; +} + +export interface UnitRung { + /** The pint unit name. */ + unit: string; + /** Key into the seeded unit names merged into i18n messages under `unit-names`. */ + seedKey: string; + base: number; + /** Whole units needed before this rung takes over from the one below it. */ + takeover: number; + fraction: boolean; +} + +export const STANDARDIZED_UNITS: Record = { +{%- for name, unit in units.items() %} + {{ name }}: { dimension: "{{ unit.dimension }}", base: {{ unit.base }}, customary: {{ unit.customary }} }, +{%- endfor %} +}; + +/** Systems made of customary units. An ingredient already in the reader's system is left alone. */ +export const CUSTOMARY_SYSTEMS: UnitSystem[] = [{{ customary_systems }}]; + +export const UNIT_SYSTEMS: Record> = { +{%- for system, dimensions in systems.items() %} + {{ system }}: { + {%- for dimension, rungs in dimensions.items() %} + {{ dimension }}: [ + {%- for rung in rungs %} + {{ rung }}, + {%- endfor %} + ], + {%- endfor %} + }, +{%- endfor %} +}; + +""" + + +def number(value: float) -> str: + """Render a float without the noise pint's arithmetic leaves behind. + + Pint computes `pound` as 453.5923700000001 and `cup` as 236.58823649999994; the trailing + digits are artifacts of operation order rather than precision. 14 significant digits sits + well inside a double and recovers the exact defined values. + """ + + return repr(float(f"{value:.14g}")) + + +def rung_literal(rung: dict) -> str: + """Render one rung as a single-line object literal, so the template stays readable.""" + + return ( + f'{{ unit: "{rung["unit"]}", seedKey: "{rung["seed_key"]}", base: {number(rung["base"])}, ' + f"takeover: {number(rung['takeover'])}, fraction: {'true' if rung['fraction'] else 'false'} }}" + ) + + +def generate_unit_systems_ts_file(): + table = build_table() + tmpl = Template(UNIT_SYSTEMS_TEMPLATE) + + rendered = tmpl.render( + dimension_union=" | ".join(f'"{dimension.value}"' for dimension in UnitDimension), + system_union=" | ".join(f'"{system.value}"' for system in UnitSystem), + units={ + name: { + "dimension": unit["dimension"], + "base": number(unit["base"]), + "customary": "true" if unit["customary"] else "false", + } + for name, unit in table["units"].items() + }, + customary_systems=", ".join(f'"{system}"' for system in table["customary_systems"]), + systems={ + system: {dimension: [rung_literal(rung) for rung in rungs] for dimension, rungs in dimensions.items()} + for system, dimensions in table["systems"].items() + }, + ) + + log.debug(f"generating unit systems ts file -> {CodeDest.unit_systems}") + with open(CodeDest.unit_systems, "w") as f: + f.write(rendered) + + +def main(): + generate_unit_systems_ts_file() + + +if __name__ == "__main__": + main() diff --git a/dev/code-generation/main.py b/dev/code-generation/main.py index b2d0f2264..e37084f4c 100644 --- a/dev/code-generation/main.py +++ b/dev/code-generation/main.py @@ -6,6 +6,7 @@ import gen_py_pytest_routes import gen_py_schema_exports import gen_ts_locales import gen_ts_types +import gen_ts_unit_systems from utils import log CWD = Path(__file__).parent @@ -16,7 +17,7 @@ def main(): parser.add_argument( "generators", nargs="*", - help="Specific generators to run (schema, types, locales, data-paths, routes). If none specified, all will run.", # noqa: E501 - long line + help="Specific generators to run (schema, types, locales, unit-systems, data-paths, routes). If none specified, all will run.", # noqa: E501 - long line ) args = parser.parse_args() @@ -25,6 +26,7 @@ def main(): "schema": (gen_py_schema_exports.main, "schema exports"), "types": (gen_ts_types.main, "frontend types"), "locales": (gen_ts_locales.main, "locales"), + "unit-systems": (gen_ts_unit_systems.main, "unit systems"), "data-paths": (gen_py_pytest_data_paths.main, "test data paths"), "routes": (gen_py_pytest_routes.main, "pytest routes"), } diff --git a/dev/code-generation/unit_systems.py b/dev/code-generation/unit_systems.py new file mode 100644 index 000000000..fd0ed4e4f --- /dev/null +++ b/dev/code-generation/unit_systems.py @@ -0,0 +1,268 @@ +""" +Source of truth for displaying recipe quantities in a preferred unit system. + +Every number here is resolved through Pint. The only hand-authored content is `SELECTION`: +which of Pint's units are kitchen units, and how many of each are needed before it takes over. +Ordering, base factors, dimensions, and the fraction flag are all derived. + +This is build-time tooling, not application code. `gen_ts_unit_systems.py` emits the table +below to TypeScript so the client can render conversions without duplicating any factors; the +backend never evaluates it. If conversions ever need to happen server-side, this module moves +into `mealie/services/` and gains a caller — until then it stays out of the shipped package. +""" + +from __future__ import annotations + +import json +from dataclasses import asdict, dataclass +from enum import StrEnum +from functools import cache +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from mealie.schema.recipe.recipe_ingredient import StandardizedUnitType + +if TYPE_CHECKING: + from pint import UnitRegistry + + +class UnitDimension(StrEnum): + MASS = "mass" + VOLUME = "volume" + + +class UnitSystem(StrEnum): + METRIC = "metric" + US = "us" + + +#: The unit each dimension is measured in. This asserts nothing about Pint: Pint decides which +#: units share a dimension, and `dimension_of` asks it by comparing dimensionalities against +#: these. All this does is name the two dimensions we display and fix the scale of the emitted +#: numbers, so the generated table reads in grams and millilitres rather than Pint's own base +#: units of kilograms and cubic metres (where a cup is 2.4e-4). +BASE_UNITS: dict[UnitDimension, str] = { + UnitDimension.MASS: "gram", + UnitDimension.VOLUME: "milliliter", +} + +#: Pint systems whose members are customary rather than metric, used to derive the fraction +#: flag. Both are listed because that is what "customary" means, not because both are offered +#: as ladders -- `ounce` and `pound` belong to either one. +#: +#: Naming them is unavoidable. Pint's `SI` system is just its root group -- 417 members, +#: including `cup`, `ounce` and `pound` -- so customary cannot be derived as the complement of +#: metric. These are Pint's own identifiers, and `get_system` raises on an unknown name, so a +#: typo fails the build rather than silently emitting a wrong table. +#: +#: There is no metric entry: metric kitchen units are generated from SI prefixes rather than +#: being members of any group, so `mks` holds `liter` but neither `milliliter` nor `kilogram`. +CUSTOMARY_PINT_SYSTEMS: tuple[str, ...] = ("US", "imperial") + +#: The only hand-authored policy in this module: for each system and dimension, which Pint +#: units may be displayed, and the takeover multiple for each — how many whole units are +#: needed before it takes over from the rung below. 1.0 is the norm; cups take over at a +#: quarter cup, which is how US recipes are written. +#: +#: This only ever applies to quantities being converted *into* this system. An ingredient the +#: author already wrote in cups or tablespoons is passed through untouched, so the boundary +#: cannot restate "4 tablespoons" as "1/4 cup". +#: +#: Order is not authored; rungs are sorted by magnitude, which Pint supplies. +#: +#: There is deliberately no imperial ladder. It would share `ounce` and `pound` with `us` — pint +#: puts both in either system — so it would only differ on volume, and essentially nobody cooks +#: in imperial: the UK weighs in grams, Australia and New Zealand are metric, and Canada follows +#: US customary. If a third ladder is ever wanted, metric-with-cups for AU/NZ is the likelier ask. +SELECTION: dict[tuple[UnitSystem, UnitDimension], dict[str, float]] = { + (UnitSystem.METRIC, UnitDimension.MASS): {"gram": 1.0, "kilogram": 1.0}, + (UnitSystem.METRIC, UnitDimension.VOLUME): {"milliliter": 1.0, "liter": 1.0}, + (UnitSystem.US, UnitDimension.MASS): {"ounce": 1.0, "pound": 1.0}, + (UnitSystem.US, UnitDimension.VOLUME): { + "teaspoon": 1.0, + "tablespoon": 1.0, + "cup": 0.25, + "quart": 1.0, + "gallon": 1.0, + }, +} + + +#: Display names are not authored here. They come from the ingredient unit seed data, which is +#: already translated into every locale Mealie ships and is managed in Crowdin. The frontend +#: loads the same files, so this only has to emit the key to look up. +SEED_UNITS_FILE = ( + Path(__file__).parents[2] / "mealie" / "repos" / "seed" / "resources" / "units" / "locales" / "en-US.json" +) + + +@dataclass(frozen=True) +class Rung: + """A display unit, and the point at which it takes over from the rung below it.""" + + unit: str + """The Pint unit name. Doubles as the i18n key for the unit's display names.""" + + base: float + """How many base units (see `BASE_UNITS`) are in one of this unit.""" + + takeover: float + """Whole units needed before this rung takes over. Hand-authored; everything else is not.""" + + fraction: bool + """Whether to render as a fraction rather than a decimal.""" + + seed_key: str + """Key into the ingredient unit seed data, where this rung's translated names live.""" + + +class UnitNotSupported(Exception): + """Raised when a unit has no dimension we can display.""" + + +@cache +def _registry() -> UnitRegistry: + from pint import UnitRegistry + + return UnitRegistry() + + +@cache +def _customary_units() -> frozenset[str]: + """Every unit belonging to a Pint system we treat as customary rather than metric. + + Used to decide whether a rung renders as a fraction. Derived rather than authored, so a + metric rung sitting inside a customary ladder would correctly stay decimal. + """ + + registry = _registry() + members: set[str] = set() + for pint_system in CUSTOMARY_PINT_SYSTEMS: + members |= set(registry.get_system(pint_system, create_if_needed=False).members) + + return frozenset(members) + + +def dimension_of(unit: str) -> UnitDimension: + """The dimension of a Pint unit, or raise if it isn't one we can display. + + Pint answers this, by comparing the unit's dimensionality against each dimension's + reference unit. Nothing here spells out what a mass or a volume is. + """ + + registry = _registry() + try: + dimensionality = registry(unit).dimensionality + except Exception as e: + raise UnitNotSupported(f"Unit '{unit}' not found in unit registry") from e + + for dimension, reference in BASE_UNITS.items(): + if dimensionality == registry(reference).dimensionality: + return dimension + + raise UnitNotSupported(f"Unit '{unit}' has unsupported dimensionality '{dimensionality}'") + + +def base_factor(unit: str) -> tuple[UnitDimension, float]: + """How many base units are in one of `unit`, alongside the dimension those are in. + + The dimension is read off the unit itself and the base chosen to match, so this can never + convert across dimensions. Do not reimplement this in terms of `UnitConverter.convert`: + that applies `_resolve_ounce`, which would silently read the mass unit `ounce` as + `fluid_ounce` whenever the target is a volume, putting it on the volume ladder at 29.57 ml. + """ + + dimension = dimension_of(unit) + registry = _registry() + quantity = registry(unit).to(BASE_UNITS[dimension]) + return dimension, float(quantity.magnitude) + + +@cache +def _seed_unit_keys() -> frozenset[str]: + """The keys available in the ingredient unit seed data.""" + + with open(SEED_UNITS_FILE) as f: + return frozenset(json.load(f)) + + +def seed_key_for(unit: str) -> str: + """The seed data key holding this unit's translated display names. + + Currently always the pint unit name, but kept distinct because it is a translation key + rather than a physics identifier. The two diverge as soon as a ladder uses a qualified pint + unit — `imperial_pint` would display under the seed data's unqualified `pint`. + """ + + if unit not in _seed_unit_keys(): + raise UnitNotSupported(f"Unit '{unit}' has no seed data, so it has no translated names") + + return unit + + +def is_customary_system(system: UnitSystem) -> bool: + """Whether a system is made of customary units rather than metric ones. + + Lets the client skip a recipe already written in the system the reader asked for, instead of + restating "1 pint" as "2 cups". + """ + + customary = _customary_units() + return any(rung.unit in customary for dimension in UnitDimension for rung in rungs_for(system, dimension)) + + +def rungs_for(system: UnitSystem, dimension: UnitDimension) -> list[Rung]: + """The display ladder for a system and dimension, ordered smallest to largest.""" + + customary = _customary_units() + rungs = [] + for unit, takeover in SELECTION[(system, dimension)].items(): + unit_dimension, base = base_factor(unit) + if unit_dimension != dimension: + raise UnitNotSupported(f"Unit '{unit}' is {unit_dimension}, but was selected for {dimension}") + + rungs.append( + Rung( + unit=unit, + base=base, + takeover=takeover, + fraction=unit in customary, + seed_key=seed_key_for(unit), + ) + ) + + rungs.sort(key=lambda rung: rung.base) + return rungs + + +def build_table() -> dict[str, Any]: + """Resolve everything through Pint into a JSON-able table for the frontend. + + `units` maps each standardized unit an ingredient may be stored in to its dimension, base + factor and whether it is customary, which is what lets the client compute an ingredient's + base magnitude and tell whether it already matches the reader's chosen system. `systems` + holds the display ladders. + """ + + customary = _customary_units() + + units: dict[str, Any] = {} + for standardized_unit in StandardizedUnitType: + dimension, base = base_factor(standardized_unit.value) + units[standardized_unit.value] = { + "dimension": dimension.value, + "base": base, + "customary": standardized_unit.value in customary, + } + + systems: dict[str, Any] = {} + for system in UnitSystem: + systems[system.value] = { + dimension.value: [asdict(rung) for rung in rungs_for(system, dimension)] for dimension in UnitDimension + } + + return { + "units": units, + "systems": systems, + "customary_systems": [system.value for system in UnitSystem if is_customary_system(system)], + } diff --git a/dev/code-generation/utils/static.py b/dev/code-generation/utils/static.py index cba8a5c1b..a334cb273 100644 --- a/dev/code-generation/utils/static.py +++ b/dev/code-generation/utils/static.py @@ -17,6 +17,7 @@ class CodeDest: interface = PARENT / "generated" / "interface.js" pytest_routes = PARENT / "generated" / "test_routes.py" use_locales = PROJECT_DIR / "frontend" / "app" / "composables" / "use-locales" / "available-locales.ts" + unit_systems = PROJECT_DIR / "frontend" / "app" / "composables" / "recipes" / "unit-systems.ts" class CodeKeys: diff --git a/docker/Dockerfile b/docker/Dockerfile index 9b9a573f9..a6766fa90 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -10,6 +10,11 @@ WORKDIR /frontend COPY frontend . +# The lang files import the seeded ingredient unit names, which live with the backend rather +# than in frontend/. Copy them to the same path they occupy in the repo, so the relative import +# in app/lang/locales/*.ts resolves identically here and in local dev. +COPY mealie/repos/seed/resources/units/locales /mealie/repos/seed/resources/units/locales + RUN pnpm clean-install RUN pnpm generate diff --git a/frontend/app/components/Domain/Recipe/RecipePage/RecipePage.vue b/frontend/app/components/Domain/Recipe/RecipePage/RecipePage.vue index ccec28cad..d0383ea14 100644 --- a/frontend/app/components/Domain/Recipe/RecipePage/RecipePage.vue +++ b/frontend/app/components/Domain/Recipe/RecipePage/RecipePage.vue @@ -79,7 +79,7 @@ > @@ -119,7 +119,7 @@ v-model="recipe" class="px-1 my-4 d-print-none" /> - + @@ -189,7 +189,7 @@ v-model="recipe.recipeInstructions" v-model:assets="recipe.assets" class="overflow-y-hidden mt-n5 px-2 px-md-4" - :recipe="recipe" + :recipe="displayedRecipe" :scale="scale" :ingredient-storage-key="ingredientStorageKey" /> @@ -251,6 +251,7 @@ import RecipeDialogBulkAdd from "~/components/Domain/Recipe/RecipeDialogBulkAdd. import RecipeNotes from "~/components/Domain/Recipe/RecipeNotes.vue"; import { useLoggedInState } from "~/composables/use-logged-in-state"; import { useNavigationWarning } from "~/composables/use-navigation-warning"; +import { useUnitConversion, useUnitSystem } from "~/composables/recipes"; import { useHouseholdSelf } from "~/composables/use-households"; const recipe = defineModel>({ required: true }); @@ -276,8 +277,35 @@ const api = useUserApi(); const { pageMode, setMode, isEditForm, isEditJSON, isCookMode, isEditMode, isParsing, toggleCookMode, toggleIsParsing } = usePageState(recipe.value.slug); const { deactivateNavigationWarning } = useNavigationWarning(); +const scale = ref(1); + +const { unitSystem } = useUnitSystem(); +const { convertIngredient } = useUnitConversion(); + +/** + * The recipe as the reader asked to see it — the recipe itself unless they've opted into a unit + * system. Cook mode, print and the ingredient list all read this, so they convert together. + * + * Returns `recipe` by identity whenever nothing is being converted, and always does so in edit + * mode. That is load-bearing rather than cosmetic: `recipe` is a defineModel the editors below + * mutate in place, so handing them a derived copy would silently drop edits. Conversion is + * display-only and never reaches anything that saves. + */ +const displayedRecipe = computed>(() => { + if (isEditMode.value || !unitSystem.value) { + return recipe.value; + } + + return { + ...recipe.value, + recipeIngredient: recipe.value.recipeIngredient.map( + ingredient => convertIngredient(ingredient, unitSystem.value!, scale.value), + ), + }; +}); + const notLinkedIngredients = computed(() => { - return recipe.value.recipeIngredient.filter((ingredient) => { + return displayedRecipe.value.recipeIngredient.filter((ingredient) => { return !recipe.value.recipeInstructions.some(step => step.ingredientReferences?.map(ref => ref.referenceId).includes(ingredient.referenceId), ); @@ -518,8 +546,6 @@ function chipClicked(item: RecipeTag | RecipeCategory | RecipeTool, itemType: st router.push(`/g/${groupSlug.value}?${itemType}=${item.id}`); } -const scale = ref(1); - // expose to template // (all variables used in template are top-level in diff --git a/frontend/app/components/Domain/Recipe/RecipePage/RecipePageParts/RecipePageScale.vue b/frontend/app/components/Domain/Recipe/RecipePage/RecipePageParts/RecipePageScale.vue index 52e4af3c1..14901ffa2 100644 --- a/frontend/app/components/Domain/Recipe/RecipePage/RecipePageParts/RecipePageScale.vue +++ b/frontend/app/components/Domain/Recipe/RecipePage/RecipePageParts/RecipePageScale.vue @@ -1,5 +1,9 @@