diff --git a/apps/web/src/features/recipes/RecipeCreatePage.css b/apps/web/src/features/recipes/RecipeCreatePage.css index 416ee0e..72cd4af 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.css +++ b/apps/web/src/features/recipes/RecipeCreatePage.css @@ -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); } @@ -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); } diff --git a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx index b05c11c..d9502ac 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.test.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.test.tsx @@ -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(); @@ -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.', + ); +}); diff --git a/apps/web/src/features/recipes/RecipeCreatePage.tsx b/apps/web/src/features/recipes/RecipeCreatePage.tsx index 625399f..5995106 100644 --- a/apps/web/src/features/recipes/RecipeCreatePage.tsx +++ b/apps/web/src/features/recipes/RecipeCreatePage.tsx @@ -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'; @@ -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(items: T[], fromIndex: number, toIndex: number) { const nextItems = [...items]; const [movedItem] = nextItems.splice(fromIndex, 1); @@ -92,14 +107,26 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { ); const [difficulty, setDifficulty] = useState(recipe?.difficulty ?? ''); const [ingredients, setIngredients] = useState( - 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( + () => + 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(null); const [draggingRow, setDraggingRow] = useState< { type: 'ingredient' | 'instruction'; index: number } | undefined >(); @@ -121,7 +148,7 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { function addIngredient() { setIngredients((currentIngredients) => [ ...currentIngredients, - { name: '', amount: '', unit: 'g' }, + { key: newRowKey(), name: '', amount: '', unit: 'g' }, ]); } @@ -173,7 +200,10 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { ); function addInstruction() { - setInstructions((currentInstructions) => [...currentInstructions, '']); + setInstructions((currentInstructions) => [ + ...currentInstructions, + { key: newRowKey(), text: '' }, + ]); } function removeInstruction(index: number) { @@ -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) => ({ @@ -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 = {}; @@ -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.' : '', ); @@ -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()) @@ -460,6 +523,9 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { onSubmit={handleSubmit} noValidate > +

+ {moveAnnouncement} +

@@ -755,6 +821,26 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) {
+ moveRow('ingredient', index, -1)} + disabled={index === 0} + /> + moveRow('ingredient', index, 1)} + disabled={index === ingredients.length - 1} + /> @@ -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) @@ -823,6 +909,26 @@ function RecipeEditor({ recipe }: { recipe?: Recipe }) { rows={2} />
+ moveRow('instruction', index, -1)} + disabled={index === 0} + /> + moveRow('instruction', index, 1)} + disabled={index === instructions.length - 1} + /> + + + ); +} + export function ChevronDownIcon(props: IconProps) { return (