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
15 changes: 14 additions & 1 deletion apps/web/src/features/recipes/RecipeCreatePage.css
Original file line number Diff line number Diff line change
Expand Up @@ -336,11 +336,13 @@
background: var(--color-surface-selected);
}

/* Move up / move down / remove buttons at the end of each row. */
.recipe-create-page__delete-control {
display: flex;
align-items: center;
justify-content: center;
width: var(--target-size-min);
gap: var(--space-1);
min-width: var(--target-size-min);
height: var(--target-size-min);
}

Expand Down Expand Up @@ -381,6 +383,17 @@
padding-block: var(--space-8) var(--space-12);
}

/* Move/remove buttons get their own line under the fields, so the
fields keep their full width on phones. */
.recipe-create-page__repeatable-row {
grid-template-columns: auto minmax(0, 1fr);
}

.recipe-create-page__repeatable-row > .recipe-create-page__delete-control {
grid-column: 2;
justify-self: end;
}

.recipe-create-page__content {
margin-top: var(--space-6);
}
Expand Down
51 changes: 50 additions & 1 deletion apps/web/src/features/recipes/RecipeCreatePage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ describe('RecipeCreatePage', () => {
expect(screen.queryByLabelText('Step 2')).not.toBeInTheDocument();
});

it('supports structured ingredients and button-based reordering', async () => {
it('supports structured ingredients and reordering by dragging the handle', async () => {
const user = userEvent.setup();

mount();
Expand Down Expand Up @@ -346,3 +346,52 @@ it('does not fetch or reset the new recipe form after list invalidation', () =>
expect(title).toHaveValue('New draft');
expect(fetch).not.toHaveBeenCalled();
});
it('reorders ingredients and steps with the keyboard, keeping focus and announcing the position', async () => {
const user = userEvent.setup();
mount();
// Fill fields directly: this test is about moving rows, not typing, and
// per-keystroke typing made it too slow for the CI runner's 5 s limit.
const fill = (label: string, value: string) =>
fireEvent.change(screen.getByLabelText(label), { target: { value } });
fill('Ingredient 1', 'Flour');
await user.click(screen.getByRole('button', { name: 'Add ingredient' }));
fill('Ingredient 2', 'Sugar');
await user.click(screen.getByRole('button', { name: 'Add ingredient' }));
fill('Ingredient 3', 'Salt');

// The first row cannot move up; the last cannot move down.
expect(
screen.getByRole('button', { name: 'Move ingredient 1 up' }),
).toBeDisabled();
expect(
screen.getByRole('button', { name: 'Move ingredient 3 down' }),
).toBeDisabled();

screen.getByRole('button', { name: 'Move ingredient 1 down' }).focus();
await user.keyboard('{Enter}');
expect(screen.getByLabelText('Ingredient 1')).toHaveValue('Sugar');
expect(screen.getByLabelText('Ingredient 2')).toHaveValue('Flour');
// Focus follows the moved row, so pressing again keeps moving Flour.
expect(
screen.getByRole('button', { name: 'Move ingredient 2 down' }),
).toHaveFocus();
expect(screen.getByRole('status')).toHaveTextContent(
'Ingredient moved to position 2 of 3.',
);
await user.keyboard('{Enter}');
expect(screen.getByLabelText('Ingredient 3')).toHaveValue('Flour');
// At the last place the down button is disabled, so focus moves to up.
expect(
screen.getByRole('button', { name: 'Move ingredient 3 up' }),
).toHaveFocus();

fill('Step 1', 'Mix');
await user.click(screen.getByRole('button', { name: 'Add step' }));
fill('Step 2', 'Bake');
await user.click(screen.getByRole('button', { name: 'Move step 2 up' }));
expect(screen.getByLabelText('Step 1')).toHaveValue('Bake');
expect(screen.getByLabelText('Step 2')).toHaveValue('Mix');
expect(screen.getByRole('status')).toHaveTextContent(
'Step moved to position 1 of 2.',
);
});
138 changes: 122 additions & 16 deletions apps/web/src/features/recipes/RecipeCreatePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
} from 'react';

import { DeleteIcon, DragHandleIcon } from '../../icons/actions';
import { ChevronDownIcon, ChevronUpIcon } from '../../icons/navigation';
import Button from '../../components/ui/Button/Button';
import Field from '../../components/ui/Field/Field';
import FeedbackMessage from '../../components/ui/FeedbackMessage/FeedbackMessage';
Expand Down Expand Up @@ -54,13 +55,27 @@ type IngredientFieldErrors = {

type FormStatus = 'idle' | 'draft';

/*
* Rows carry a stable key so React keeps each row's DOM (focus, typed text)
* with its data when rows are moved or removed; array indexes would not.
*/
type IngredientDraft = {
key: string;
name: string;
amount: string;
unit: string;
note?: string;
};

type InstructionDraft = { key: string; text: string };
type RowType = 'ingredient' | 'instruction';

let lastRowKey = 0;
function newRowKey() {
lastRowKey += 1;
return `row-${lastRowKey}`;
}

function moveItem<T>(items: T[], fromIndex: number, toIndex: number) {
const nextItems = [...items];
const [movedItem] = nextItems.splice(fromIndex, 1);
Expand Down Expand Up @@ -92,14 +107,26 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
);
const [difficulty, setDifficulty] = useState(recipe?.difficulty ?? '');
const [ingredients, setIngredients] = useState<IngredientDraft[]>(
recipe?.ingredients.map((item) => ({
...item,
amount: String(item.amount),
})) ?? [{ name: '', amount: '', unit: 'g' }],
() =>
recipe?.ingredients.map((item) => ({
key: newRowKey(),
name: item.name,
amount: String(item.amount),
unit: item.unit,
note: item.note ?? undefined,
})) ?? [{ key: newRowKey(), name: '', amount: '', unit: 'g' }],
);
const [instructions, setInstructions] = useState(
recipe?.instructions.map((item) => item.text) ?? [''],
const [instructions, setInstructions] = useState<InstructionDraft[]>(
() =>
recipe?.instructions.map((item) => ({
key: newRowKey(),
text: item.text,
})) ?? [{ key: newRowKey(), text: '' }],
);
// Announced after a row is moved with the keyboard buttons.
const [moveAnnouncement, setMoveAnnouncement] = useState('');
// Id of the control to focus after the next render (see moveRow).
const pendingFocusId = useRef<string | null>(null);
const [draggingRow, setDraggingRow] = useState<
{ type: 'ingredient' | 'instruction'; index: number } | undefined
>();
Expand All @@ -121,7 +148,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
function addIngredient() {
setIngredients((currentIngredients) => [
...currentIngredients,
{ name: '', amount: '', unit: 'g' },
{ key: newRowKey(), name: '', amount: '', unit: 'g' },
]);
}

Expand Down Expand Up @@ -173,7 +200,10 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
);

function addInstruction() {
setInstructions((currentInstructions) => [...currentInstructions, '']);
setInstructions((currentInstructions) => [
...currentInstructions,
{ key: newRowKey(), text: '' },
]);
}

function removeInstruction(index: number) {
Expand All @@ -187,7 +217,9 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
function updateInstruction(index: number, value: string) {
setInstructions((currentInstructions) =>
currentInstructions.map((instruction, instructionIndex) =>
instructionIndex === index ? value : instruction,
instructionIndex === index
? { ...instruction, text: value }
: instruction,
),
);
setErrors((currentErrors) => ({
Expand Down Expand Up @@ -287,6 +319,37 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
setDraggingRow({ type, index });
}

/*
* Keyboard alternative to dragging (WCAG 2.5.7): moves a row one place,
* keeps focus on the moved row's button (or its other move button when it
* reaches the first/last place) and announces the new position.
*/
function moveRow(type: RowType, index: number, direction: -1 | 1) {
const rows = type === 'ingredient' ? ingredients : instructions;
const target = index + direction;
if (target < 0 || target >= rows.length) return;
if (type === 'ingredient') reorderIngredients(index, target);
else reorderInstructions(index, target);
const atEdge = target === 0 || target === rows.length - 1;
const button = atEdge
? target === 0
? 'down'
: 'up'
: direction === -1
? 'up'
: 'down';
pendingFocusId.current = `${type}-${rows[index]!.key}-move-${button}`;
setMoveAnnouncement(
`${type === 'ingredient' ? 'Ingredient' : 'Step'} moved to position ${target + 1} of ${rows.length}.`,
);
}

useEffect(() => {
if (!pendingFocusId.current) return;
document.getElementById(pendingFocusId.current)?.focus();
pendingFocusId.current = null;
});

function validateForm(): RecipeErrors {
const nextErrors: RecipeErrors = {};

Expand Down Expand Up @@ -345,10 +408,10 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
)
nextErrors.ingredients = ingredientErrors;

const instructionErrors = instructions.map((instruction) =>
!instruction.trim()
const instructionErrors = instructions.map(({ text }) =>
!text.trim()
? 'Add an instruction.'
: instruction.trim().length > 5000
: text.trim().length > 5000
? 'Keep instructions under 5000 characters.'
: '',
);
Expand Down Expand Up @@ -420,7 +483,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
unit: item.unit,
note: item.note,
})),
instructions: instructions.map((text) => text.trim()),
instructions: instructions.map(({ text }) => text.trim()),
tags: tags
.split(',')
.map((tag) => tag.trim())
Expand Down Expand Up @@ -460,6 +523,9 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
onSubmit={handleSubmit}
noValidate
>
<p className="sr-only" role="status" aria-live="polite">
{moveAnnouncement}
</p>
<fieldset
disabled={pending}
className="recipe-create-page__content"
Expand Down Expand Up @@ -686,7 +752,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
? ' recipe-create-page__repeatable-row--dragging'
: ''
}`}
key={`ingredient-${index}`}
key={ingredient.key}
data-recipe-row-type="ingredient"
data-recipe-row-index={index}
>
Expand Down Expand Up @@ -755,6 +821,26 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
</Select>
</div>
<div className="recipe-create-page__delete-control">
<IconButton
id={`ingredient-${ingredient.key}-move-up`}
icon={ChevronUpIcon}
aria-label={`Move ingredient ${index + 1} up`}
title={`Move ingredient ${index + 1} up`}
type="button"
size="sm"
onClick={() => moveRow('ingredient', index, -1)}
disabled={index === 0}
/>
<IconButton
id={`ingredient-${ingredient.key}-move-down`}
icon={ChevronDownIcon}
aria-label={`Move ingredient ${index + 1} down`}
title={`Move ingredient ${index + 1} down`}
type="button"
size="sm"
onClick={() => moveRow('ingredient', index, 1)}
disabled={index === ingredients.length - 1}
/>
<IconButton
icon={DeleteIcon}
aria-label={`Remove ingredient ${index + 1}`}
Expand Down Expand Up @@ -797,7 +883,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
? ' recipe-create-page__repeatable-row--dragging'
: ''
}`}
key={`instruction-${index}`}
key={instruction.key}
data-recipe-row-type="instruction"
data-recipe-row-index={index}
>
Expand All @@ -814,7 +900,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
label={`Step ${index + 1}`}
id={`instruction-${index}`}
className="recipe-create-page__step-textarea"
value={instruction}
value={instruction.text}
error={errors.instructions?.[index]}
onChange={(event) =>
updateInstruction(index, event.target.value)
Expand All @@ -823,6 +909,26 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
rows={2}
/>
<div className="recipe-create-page__delete-control">
<IconButton
id={`instruction-${instruction.key}-move-up`}
icon={ChevronUpIcon}
aria-label={`Move step ${index + 1} up`}
title={`Move step ${index + 1} up`}
type="button"
size="sm"
onClick={() => moveRow('instruction', index, -1)}
disabled={index === 0}
/>
<IconButton
id={`instruction-${instruction.key}-move-down`}
icon={ChevronDownIcon}
aria-label={`Move step ${index + 1} down`}
title={`Move step ${index + 1} down`}
type="button"
size="sm"
onClick={() => moveRow('instruction', index, 1)}
disabled={index === instructions.length - 1}
/>
<IconButton
icon={DeleteIcon}
aria-label={`Remove step ${index + 1}`}
Expand Down
8 changes: 8 additions & 0 deletions apps/web/src/icons/navigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ export function SearchIcon(props: IconProps) {
);
}

export function ChevronUpIcon(props: IconProps) {
return (
<IconBase {...props}>
<path d="m6 15 6-6 6 6" />
</IconBase>
);
}

export function ChevronDownIcon(props: IconProps) {
return (
<IconBase {...props}>
Expand Down