Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@ it('loads details and scales ingredient quantities without changing the server',
mount();
expect(await screen.findByRole('heading', { name: 'API soup' })).toBeTruthy();
expect(screen.getByText('Boil the water.')).toBeTruthy();
expect(screen.getByText('1 l')).toBeTruthy();
expect(screen.getByText('1 L')).toBeTruthy();
await userEvent
.setup()
.click(screen.getAllByRole('button', { name: 'Increase servings' })[0]!);
expect(screen.getByText('1.5 l')).toBeTruthy();
expect(screen.getByText('1.5 L')).toBeTruthy();
expect(screen.getByRole('button', { name: 'Rate Recipe' })).toBeTruthy();
});
it('treats inaccessible private recipes as unavailable', async () => {
Expand Down
3 changes: 2 additions & 1 deletion apps/web/src/features/recipe-detail/RecipeDetailPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
} from '../recipes/recipeApi';
import { useRecipeQuery } from '../recipes/useRecipeQuery';
import RecipeQueryStatus from '../recipes/RecipeQueryStatus';
import { unitLabel } from '../../lib/ingredientUnits';
import { formatAmount, scaleAmount } from '../../lib/recipeScaling';
import ServingsStepper from './ServingsStepper';
import './RecipeDetailPage.css';
Expand Down Expand Up @@ -498,7 +499,7 @@ function RecipeDetailContent({ recipe }: RecipeDetailContentProps) {
);

const amountWithUnit =
`${scaledAmount} ${ingredient.unit}`.trim();
`${scaledAmount} ${unitLabel(ingredient.unit)}`.trim();

return (
<li key={ingredient.id}>
Expand Down
25 changes: 25 additions & 0 deletions apps/web/src/features/recipes/RecipeCreatePage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,31 @@ it('does not fetch or reset the new recipe form after list invalidation', () =>
expect(title).toHaveValue('New draft');
expect(fetch).not.toHaveBeenCalled();
});
it('opens recipes with legacy Norwegian units as English and saves English', async () => {
let input: unknown;
mockRecipeFetch((operation, variables) => {
const recipe = {
...apiRecipe,
isCreatedByCurrentUser: true,
ingredients: [{ ...apiRecipe.ingredients[0], unit: 'ss' }],
};
if (operation === 'UpdateRecipe') {
input = variables.input;
return { data: { updateRecipe: recipe } };
}
return { data: { recipe } };
});
mount('/recipes/' + apiRecipe.id + '/edit');
await screen.findByRole('heading', { name: 'Edit Recipe' });
expect(screen.getByLabelText('Ingredient 1 unit')).toHaveValue('tbsp');
expect(screen.queryByRole('option', { name: 'ss' })).toBeNull();
const user = userEvent.setup();
await user.click(screen.getByRole('button', { name: 'Save changes' }));
await screen.findByRole('heading', { name: 'Saved recipe destination' });
expect(input).toMatchObject({
ingredients: [expect.objectContaining({ unit: 'tbsp' })],
});
});
it('reorders ingredients and steps with the keyboard, keeping focus and announcing the position', async () => {
const user = userEvent.setup();
mount();
Expand Down
23 changes: 11 additions & 12 deletions apps/web/src/features/recipes/RecipeCreatePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { useRecipeQuery } from './useRecipeQuery';
import RecipeQueryStatus from './RecipeQueryStatus';
import LinkButton from '../../components/ui/LinkButton/LinkButton';
import RecipeImageField from './RecipeImageField';
import { INGREDIENT_UNITS, normalizeUnit } from '../../lib/ingredientUnits';
import { MAX_SERVINGS, MIN_SERVINGS } from '@t31/validation/recipe';

import './RecipeCreatePage.css';
Expand Down Expand Up @@ -113,7 +114,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
key: newRowKey(),
name: item.name,
amount: String(item.amount),
unit: item.unit,
unit: normalizeUnit(item.unit),
note: item.note ?? undefined,
})) ?? [{ key: newRowKey(), name: '', amount: '', unit: 'g' }],
);
Expand Down Expand Up @@ -804,21 +805,19 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
updateIngredient(index, 'unit', event.target.value)
}
>
{!['', 'g', 'kg', 'l', 'dl', 'ss', 'ts', 'stk'].includes(
ingredient.unit,
{/* Keep a custom stored unit (e.g. "cloves") selectable. */}
{!INGREDIENT_UNITS.some(
(unit) => unit.value === ingredient.unit,
) && (
<option value={ingredient.unit}>
{ingredient.unit || 'No unit'}
{ingredient.unit}
</option>
)}
<option value="">No unit</option>
<option value="g">g</option>
<option value="kg">kg</option>
<option value="l">L</option>
<option value="dl">dL</option>
<option value="ss">ss</option>
<option value="ts">ts</option>
<option value="stk">stk</option>
{INGREDIENT_UNITS.map((unit) => (
<option key={unit.value} value={unit.value}>
{unit.label}
</option>
))}
</Select>
</div>
<div className="recipe-create-page__delete-control">
Expand Down
32 changes: 32 additions & 0 deletions apps/web/src/lib/ingredientUnits.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { describe, expect, it } from 'vitest';
import { INGREDIENT_UNITS, normalizeUnit, unitLabel } from './ingredientUnits';

describe('ingredient units', () => {
it('translates legacy Norwegian units to English', () => {
expect(normalizeUnit('ss')).toBe('tbsp');
expect(normalizeUnit('ts')).toBe('tsp');
expect(normalizeUnit('STK')).toBe('pcs');
expect(unitLabel('ss')).toBe('tbsp');
});

it('keeps English and custom units as stored', () => {
expect(normalizeUnit('g')).toBe('g');
expect(unitLabel('dl')).toBe('dL');
expect(unitLabel('cloves')).toBe('cloves');
expect(unitLabel('')).toBe('');
});

it('offers no Norwegian units in the editor', () => {
const values: string[] = INGREDIENT_UNITS.map((unit) => unit.value);
for (const legacy of ['ss', 'ts', 'stk'])
expect(values).not.toContain(legacy);
});

it.each(['__proto__', 'constructor', 'toString', 'hasOwnProperty'])(
'keeps the free-text unit "%s" as typed, not an inherited property',
(unit) => {
expect(normalizeUnit(unit)).toBe(unit);
expect(unitLabel(unit)).toBe(unit);
},
);
});
45 changes: 45 additions & 0 deletions apps/web/src/lib/ingredientUnits.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* Ingredient units offered in the recipe editor, stored by `value` and shown
* by `label`. Units are free text in the API, so recipes may also contain
* other units (e.g. "cloves"); those are kept and shown as stored.
*/
export const INGREDIENT_UNITS = [
{ value: '', label: 'No unit' },
{ value: 'g', label: 'g' },
{ value: 'kg', label: 'kg' },
{ value: 'ml', label: 'ml' },
{ value: 'dl', label: 'dL' },
{ value: 'l', label: 'L' },
{ value: 'tsp', label: 'tsp' },
{ value: 'tbsp', label: 'tbsp' },
{ value: 'cup', label: 'cup' },
{ value: 'pcs', label: 'pcs' },
] as const;

/*
* Earlier versions of the editor stored Norwegian abbreviations. They are
* translated when a recipe is shown or opened for editing, so existing
* recipes keep working without a data migration; saving stores English.
*/
const LEGACY_UNITS: Record<string, string> = {
ss: 'tbsp', // spiseskje
ts: 'tsp', // teskje
stk: 'pcs', // stykk
};

/** The stored value to use for a unit, translating legacy Norwegian units. */
export function normalizeUnit(unit: string) {
const key = unit.trim().toLowerCase();
// Units are free text: only the mappings defined above count, never
// inherited object properties such as "__proto__" or "constructor".
return Object.hasOwn(LEGACY_UNITS, key) ? LEGACY_UNITS[key]! : unit;
}

/** How a stored unit is displayed next to an amount ('' for no unit). */
export function unitLabel(unit: string) {
const value = normalizeUnit(unit);
if (!value) return '';
return (
INGREDIENT_UNITS.find((option) => option.value === value)?.label ?? value
);
}